text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
name: url_launcher_example description: Demonstrates how to use the url_launcher plugin. publish_to: none environment: sdk: ">=2.12.0 <3.0.0" flutter: ">=3.0.0" dependencies: flutter: sdk: flutter url_launcher_linux: # When depending on this package from a real application you should use: # url_launcher_linux: ^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.0.0 dev_dependencies: flutter_driver: sdk: flutter flutter_test: sdk: flutter integration_test: sdk: flutter flutter: uses-material-design: true
plugins/packages/url_launcher/url_launcher_linux/example/pubspec.yaml/0
{ "file_path": "plugins/packages/url_launcher/url_launcher_linux/example/pubspec.yaml", "repo_id": "plugins", "token_count": 290 }
1,322
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // 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({Key? key}) : super(key: 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({Key? key, required this.title}) : super(key: key); final String title; @override State<MyHomePage> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { Future<void>? _launched; Future<void> _launchInBrowser(String url) async { if (await UrlLauncherPlatform.instance.canLaunch(url)) { await UrlLauncherPlatform.instance.launch( url, useSafariVC: false, useWebView: false, enableJavaScript: false, enableDomStorage: false, universalLinksOnly: false, headers: <String, String>{}, ); } else { 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(''); } } @override Widget build(BuildContext context) { const String toLaunch = 'https://www.cylog.org/headers/'; return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: ListView( children: <Widget>[ Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ const Padding( padding: EdgeInsets.all(16.0), child: Text(toLaunch), ), ElevatedButton( onPressed: () => setState(() { _launched = _launchInBrowser(toLaunch); }), child: const Text('Launch in browser'), ), const Padding(padding: EdgeInsets.all(16.0)), FutureBuilder<void>(future: _launched, builder: _launchStatus), ], ), ], ), ); } }
plugins/packages/url_launcher/url_launcher_macos/example/lib/main.dart/0
{ "file_path": "plugins/packages/url_launcher/url_launcher_macos/example/lib/main.dart", "repo_id": "plugins", "token_count": 1101 }
1,323
# # To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html # Pod::Spec.new do |s| s.name = 'url_launcher_macos' s.version = '0.0.1' s.summary = 'Flutter macos plugin for launching a URL.' s.description = <<-DESC A macOS implementation of the url_launcher plugin. DESC s.homepage = 'https://github.com/flutter/plugins/tree/main/packages/url_launcher/url_launcher_macos' s.license = { :type => 'BSD', :file => '../LICENSE' } s.author = { 'Flutter Team' => '[email protected]' } s.source = { :http => 'https://github.com/flutter/plugins/tree/main/packages/url_launcher/url_launcher_macos' } s.source_files = 'Classes/**/*' s.dependency 'FlutterMacOS' s.platform = :osx, '10.11' s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' } s.swift_version = '5.0' end
plugins/packages/url_launcher/url_launcher_macos/macos/url_launcher_macos.podspec/0
{ "file_path": "plugins/packages/url_launcher/url_launcher_macos/macos/url_launcher_macos.podspec", "repo_id": "plugins", "token_count": 427 }
1,324
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:html' as html; // Fake interface for the logic that this package needs from (web-only) dart:ui. // This is conditionally exported so the analyzer sees these methods as available. // ignore_for_file: avoid_classes_with_only_static_members // ignore_for_file: camel_case_types /// Shim for web_ui engine.PlatformViewRegistry /// https://github.com/flutter/engine/blob/main/lib/web_ui/lib/ui.dart#L62 class platformViewRegistry { /// Shim for registerViewFactory /// https://github.com/flutter/engine/blob/main/lib/web_ui/lib/ui.dart#L72 static bool registerViewFactory( String viewTypeId, html.Element Function(int viewId) viewFactory, {bool isVisible = true}) { return false; } } /// Shim for web_ui engine.AssetManager. /// https://github.com/flutter/engine/blob/main/lib/web_ui/lib/src/engine/assets.dart#L12 class webOnlyAssetManager { /// Shim for getAssetUrl. /// https://github.com/flutter/engine/blob/main/lib/web_ui/lib/src/engine/assets.dart#L45 static String getAssetUrl(String asset) => ''; } /// Signature of callbacks that have no arguments and return no data. typedef VoidCallback = void Function();
plugins/packages/url_launcher/url_launcher_web/lib/src/shims/dart_ui_fake.dart/0
{ "file_path": "plugins/packages/url_launcher/url_launcher_web/lib/src/shims/dart_ui_fake.dart", "repo_id": "plugins", "token_count": 425 }
1,325
org.gradle.jvmargs=-Xmx4G android.useAndroidX=true android.enableJetifier=true android.enableR8=true
plugins/packages/video_player/video_player/example/android/gradle.properties/0
{ "file_path": "plugins/packages/video_player/video_player/example/android/gradle.properties", "repo_id": "plugins", "token_count": 38 }
1,326
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:pigeon/pigeon.dart'; @ConfigurePigeon(PigeonOptions( dartOut: 'lib/src/messages.g.dart', dartTestOut: 'test/test_api.g.dart', javaOut: 'android/src/main/java/io/flutter/plugins/videoplayer/Messages.java', javaOptions: JavaOptions( package: 'io.flutter.plugins.videoplayer', ), copyrightHeader: 'pigeons/copyright.txt', )) class TextureMessage { TextureMessage(this.textureId); int textureId; } class LoopingMessage { LoopingMessage(this.textureId, this.isLooping); int textureId; bool isLooping; } class VolumeMessage { VolumeMessage(this.textureId, this.volume); int textureId; double volume; } class PlaybackSpeedMessage { PlaybackSpeedMessage(this.textureId, this.speed); int textureId; double speed; } class PositionMessage { PositionMessage(this.textureId, this.position); int textureId; int position; } class CreateMessage { CreateMessage({required this.httpHeaders}); String? asset; String? uri; String? packageName; String? formatHint; Map<String?, String?> httpHeaders; } class MixWithOthersMessage { MixWithOthersMessage(this.mixWithOthers); bool mixWithOthers; } @HostApi(dartHostTestHandler: 'TestHostVideoPlayerApi') abstract class AndroidVideoPlayerApi { void initialize(); TextureMessage create(CreateMessage msg); void dispose(TextureMessage msg); void setLooping(LoopingMessage msg); void setVolume(VolumeMessage msg); void setPlaybackSpeed(PlaybackSpeedMessage msg); void play(TextureMessage msg); PositionMessage position(TextureMessage msg); void seekTo(PositionMessage msg); void pause(TextureMessage msg); void setMixWithOthers(MixWithOthersMessage msg); }
plugins/packages/video_player/video_player_android/pigeons/messages.dart/0
{ "file_path": "plugins/packages/video_player/video_player_android/pigeons/messages.dart", "repo_id": "plugins", "token_count": 587 }
1,327
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Autogenerated from Pigeon (v2.0.1), do not edit directly. // See also: https://pub.dev/packages/pigeon #import "messages.g.h" #import <Flutter/Flutter.h> #if !__has_feature(objc_arc) #error File requires ARC to be enabled. #endif static NSDictionary<NSString *, id> *wrapResult(id result, FlutterError *error) { NSDictionary *errorDict = (NSDictionary *)[NSNull null]; if (error) { errorDict = @{ @"code" : (error.code ? error.code : [NSNull null]), @"message" : (error.message ? error.message : [NSNull null]), @"details" : (error.details ? error.details : [NSNull null]), }; } return @{ @"result" : (result ? result : [NSNull null]), @"error" : errorDict, }; } static id GetNullableObject(NSDictionary *dict, id key) { id result = dict[key]; return (result == [NSNull null]) ? nil : result; } static id GetNullableObjectAtIndex(NSArray *array, NSInteger key) { id result = array[key]; return (result == [NSNull null]) ? nil : result; } @interface FLTTextureMessage () + (FLTTextureMessage *)fromMap:(NSDictionary *)dict; - (NSDictionary *)toMap; @end @interface FLTLoopingMessage () + (FLTLoopingMessage *)fromMap:(NSDictionary *)dict; - (NSDictionary *)toMap; @end @interface FLTVolumeMessage () + (FLTVolumeMessage *)fromMap:(NSDictionary *)dict; - (NSDictionary *)toMap; @end @interface FLTPlaybackSpeedMessage () + (FLTPlaybackSpeedMessage *)fromMap:(NSDictionary *)dict; - (NSDictionary *)toMap; @end @interface FLTPositionMessage () + (FLTPositionMessage *)fromMap:(NSDictionary *)dict; - (NSDictionary *)toMap; @end @interface FLTCreateMessage () + (FLTCreateMessage *)fromMap:(NSDictionary *)dict; - (NSDictionary *)toMap; @end @interface FLTMixWithOthersMessage () + (FLTMixWithOthersMessage *)fromMap:(NSDictionary *)dict; - (NSDictionary *)toMap; @end @implementation FLTTextureMessage + (instancetype)makeWithTextureId:(NSNumber *)textureId { FLTTextureMessage *pigeonResult = [[FLTTextureMessage alloc] init]; pigeonResult.textureId = textureId; return pigeonResult; } + (FLTTextureMessage *)fromMap:(NSDictionary *)dict { FLTTextureMessage *pigeonResult = [[FLTTextureMessage alloc] init]; pigeonResult.textureId = GetNullableObject(dict, @"textureId"); NSAssert(pigeonResult.textureId != nil, @""); return pigeonResult; } - (NSDictionary *)toMap { return [NSDictionary dictionaryWithObjectsAndKeys:(self.textureId ? self.textureId : [NSNull null]), @"textureId", nil]; } @end @implementation FLTLoopingMessage + (instancetype)makeWithTextureId:(NSNumber *)textureId isLooping:(NSNumber *)isLooping { FLTLoopingMessage *pigeonResult = [[FLTLoopingMessage alloc] init]; pigeonResult.textureId = textureId; pigeonResult.isLooping = isLooping; return pigeonResult; } + (FLTLoopingMessage *)fromMap:(NSDictionary *)dict { FLTLoopingMessage *pigeonResult = [[FLTLoopingMessage alloc] init]; pigeonResult.textureId = GetNullableObject(dict, @"textureId"); NSAssert(pigeonResult.textureId != nil, @""); pigeonResult.isLooping = GetNullableObject(dict, @"isLooping"); NSAssert(pigeonResult.isLooping != nil, @""); return pigeonResult; } - (NSDictionary *)toMap { return [NSDictionary dictionaryWithObjectsAndKeys:(self.textureId ? self.textureId : [NSNull null]), @"textureId", (self.isLooping ? self.isLooping : [NSNull null]), @"isLooping", nil]; } @end @implementation FLTVolumeMessage + (instancetype)makeWithTextureId:(NSNumber *)textureId volume:(NSNumber *)volume { FLTVolumeMessage *pigeonResult = [[FLTVolumeMessage alloc] init]; pigeonResult.textureId = textureId; pigeonResult.volume = volume; return pigeonResult; } + (FLTVolumeMessage *)fromMap:(NSDictionary *)dict { FLTVolumeMessage *pigeonResult = [[FLTVolumeMessage alloc] init]; pigeonResult.textureId = GetNullableObject(dict, @"textureId"); NSAssert(pigeonResult.textureId != nil, @""); pigeonResult.volume = GetNullableObject(dict, @"volume"); NSAssert(pigeonResult.volume != nil, @""); return pigeonResult; } - (NSDictionary *)toMap { return [NSDictionary dictionaryWithObjectsAndKeys:(self.textureId ? self.textureId : [NSNull null]), @"textureId", (self.volume ? self.volume : [NSNull null]), @"volume", nil]; } @end @implementation FLTPlaybackSpeedMessage + (instancetype)makeWithTextureId:(NSNumber *)textureId speed:(NSNumber *)speed { FLTPlaybackSpeedMessage *pigeonResult = [[FLTPlaybackSpeedMessage alloc] init]; pigeonResult.textureId = textureId; pigeonResult.speed = speed; return pigeonResult; } + (FLTPlaybackSpeedMessage *)fromMap:(NSDictionary *)dict { FLTPlaybackSpeedMessage *pigeonResult = [[FLTPlaybackSpeedMessage alloc] init]; pigeonResult.textureId = GetNullableObject(dict, @"textureId"); NSAssert(pigeonResult.textureId != nil, @""); pigeonResult.speed = GetNullableObject(dict, @"speed"); NSAssert(pigeonResult.speed != nil, @""); return pigeonResult; } - (NSDictionary *)toMap { return [NSDictionary dictionaryWithObjectsAndKeys:(self.textureId ? self.textureId : [NSNull null]), @"textureId", (self.speed ? self.speed : [NSNull null]), @"speed", nil]; } @end @implementation FLTPositionMessage + (instancetype)makeWithTextureId:(NSNumber *)textureId position:(NSNumber *)position { FLTPositionMessage *pigeonResult = [[FLTPositionMessage alloc] init]; pigeonResult.textureId = textureId; pigeonResult.position = position; return pigeonResult; } + (FLTPositionMessage *)fromMap:(NSDictionary *)dict { FLTPositionMessage *pigeonResult = [[FLTPositionMessage alloc] init]; pigeonResult.textureId = GetNullableObject(dict, @"textureId"); NSAssert(pigeonResult.textureId != nil, @""); pigeonResult.position = GetNullableObject(dict, @"position"); NSAssert(pigeonResult.position != nil, @""); return pigeonResult; } - (NSDictionary *)toMap { return [NSDictionary dictionaryWithObjectsAndKeys:(self.textureId ? self.textureId : [NSNull null]), @"textureId", (self.position ? self.position : [NSNull null]), @"position", nil]; } @end @implementation FLTCreateMessage + (instancetype)makeWithAsset:(nullable NSString *)asset uri:(nullable NSString *)uri packageName:(nullable NSString *)packageName formatHint:(nullable NSString *)formatHint httpHeaders:(NSDictionary<NSString *, NSString *> *)httpHeaders { FLTCreateMessage *pigeonResult = [[FLTCreateMessage alloc] init]; pigeonResult.asset = asset; pigeonResult.uri = uri; pigeonResult.packageName = packageName; pigeonResult.formatHint = formatHint; pigeonResult.httpHeaders = httpHeaders; return pigeonResult; } + (FLTCreateMessage *)fromMap:(NSDictionary *)dict { FLTCreateMessage *pigeonResult = [[FLTCreateMessage alloc] init]; pigeonResult.asset = GetNullableObject(dict, @"asset"); pigeonResult.uri = GetNullableObject(dict, @"uri"); pigeonResult.packageName = GetNullableObject(dict, @"packageName"); pigeonResult.formatHint = GetNullableObject(dict, @"formatHint"); pigeonResult.httpHeaders = GetNullableObject(dict, @"httpHeaders"); NSAssert(pigeonResult.httpHeaders != nil, @""); return pigeonResult; } - (NSDictionary *)toMap { return [NSDictionary dictionaryWithObjectsAndKeys:(self.asset ? self.asset : [NSNull null]), @"asset", (self.uri ? self.uri : [NSNull null]), @"uri", (self.packageName ? self.packageName : [NSNull null]), @"packageName", (self.formatHint ? self.formatHint : [NSNull null]), @"formatHint", (self.httpHeaders ? self.httpHeaders : [NSNull null]), @"httpHeaders", nil]; } @end @implementation FLTMixWithOthersMessage + (instancetype)makeWithMixWithOthers:(NSNumber *)mixWithOthers { FLTMixWithOthersMessage *pigeonResult = [[FLTMixWithOthersMessage alloc] init]; pigeonResult.mixWithOthers = mixWithOthers; return pigeonResult; } + (FLTMixWithOthersMessage *)fromMap:(NSDictionary *)dict { FLTMixWithOthersMessage *pigeonResult = [[FLTMixWithOthersMessage alloc] init]; pigeonResult.mixWithOthers = GetNullableObject(dict, @"mixWithOthers"); NSAssert(pigeonResult.mixWithOthers != nil, @""); return pigeonResult; } - (NSDictionary *)toMap { return [NSDictionary dictionaryWithObjectsAndKeys:(self.mixWithOthers ? self.mixWithOthers : [NSNull null]), @"mixWithOthers", nil]; } @end @interface FLTAVFoundationVideoPlayerApiCodecReader : FlutterStandardReader @end @implementation FLTAVFoundationVideoPlayerApiCodecReader - (nullable id)readValueOfType:(UInt8)type { switch (type) { case 128: return [FLTCreateMessage fromMap:[self readValue]]; case 129: return [FLTLoopingMessage fromMap:[self readValue]]; case 130: return [FLTMixWithOthersMessage fromMap:[self readValue]]; case 131: return [FLTPlaybackSpeedMessage fromMap:[self readValue]]; case 132: return [FLTPositionMessage fromMap:[self readValue]]; case 133: return [FLTTextureMessage fromMap:[self readValue]]; case 134: return [FLTVolumeMessage fromMap:[self readValue]]; default: return [super readValueOfType:type]; } } @end @interface FLTAVFoundationVideoPlayerApiCodecWriter : FlutterStandardWriter @end @implementation FLTAVFoundationVideoPlayerApiCodecWriter - (void)writeValue:(id)value { if ([value isKindOfClass:[FLTCreateMessage class]]) { [self writeByte:128]; [self writeValue:[value toMap]]; } else if ([value isKindOfClass:[FLTLoopingMessage class]]) { [self writeByte:129]; [self writeValue:[value toMap]]; } else if ([value isKindOfClass:[FLTMixWithOthersMessage class]]) { [self writeByte:130]; [self writeValue:[value toMap]]; } else if ([value isKindOfClass:[FLTPlaybackSpeedMessage class]]) { [self writeByte:131]; [self writeValue:[value toMap]]; } else if ([value isKindOfClass:[FLTPositionMessage class]]) { [self writeByte:132]; [self writeValue:[value toMap]]; } else if ([value isKindOfClass:[FLTTextureMessage class]]) { [self writeByte:133]; [self writeValue:[value toMap]]; } else if ([value isKindOfClass:[FLTVolumeMessage class]]) { [self writeByte:134]; [self writeValue:[value toMap]]; } else { [super writeValue:value]; } } @end @interface FLTAVFoundationVideoPlayerApiCodecReaderWriter : FlutterStandardReaderWriter @end @implementation FLTAVFoundationVideoPlayerApiCodecReaderWriter - (FlutterStandardWriter *)writerWithData:(NSMutableData *)data { return [[FLTAVFoundationVideoPlayerApiCodecWriter alloc] initWithData:data]; } - (FlutterStandardReader *)readerWithData:(NSData *)data { return [[FLTAVFoundationVideoPlayerApiCodecReader alloc] initWithData:data]; } @end NSObject<FlutterMessageCodec> *FLTAVFoundationVideoPlayerApiGetCodec() { static dispatch_once_t sPred = 0; static FlutterStandardMessageCodec *sSharedObject = nil; dispatch_once(&sPred, ^{ FLTAVFoundationVideoPlayerApiCodecReaderWriter *readerWriter = [[FLTAVFoundationVideoPlayerApiCodecReaderWriter alloc] init]; sSharedObject = [FlutterStandardMessageCodec codecWithReaderWriter:readerWriter]; }); return sSharedObject; } void FLTAVFoundationVideoPlayerApiSetup(id<FlutterBinaryMessenger> binaryMessenger, NSObject<FLTAVFoundationVideoPlayerApi> *api) { { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.AVFoundationVideoPlayerApi.initialize" binaryMessenger:binaryMessenger codec:FLTAVFoundationVideoPlayerApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(initialize:)], @"FLTAVFoundationVideoPlayerApi api (%@) doesn't respond to @selector(initialize:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { FlutterError *error; [api initialize:&error]; callback(wrapResult(nil, error)); }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.AVFoundationVideoPlayerApi.create" binaryMessenger:binaryMessenger codec:FLTAVFoundationVideoPlayerApiGetCodec()]; if (api) { NSCAssert( [api respondsToSelector:@selector(create:error:)], @"FLTAVFoundationVideoPlayerApi api (%@) doesn't respond to @selector(create:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; FLTCreateMessage *arg_msg = GetNullableObjectAtIndex(args, 0); FlutterError *error; FLTTextureMessage *output = [api create:arg_msg error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.AVFoundationVideoPlayerApi.dispose" binaryMessenger:binaryMessenger codec:FLTAVFoundationVideoPlayerApiGetCodec()]; if (api) { NSCAssert( [api respondsToSelector:@selector(dispose:error:)], @"FLTAVFoundationVideoPlayerApi api (%@) doesn't respond to @selector(dispose:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; FLTTextureMessage *arg_msg = GetNullableObjectAtIndex(args, 0); FlutterError *error; [api dispose:arg_msg error:&error]; callback(wrapResult(nil, error)); }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.AVFoundationVideoPlayerApi.setLooping" binaryMessenger:binaryMessenger codec:FLTAVFoundationVideoPlayerApiGetCodec()]; if (api) { NSCAssert( [api respondsToSelector:@selector(setLooping:error:)], @"FLTAVFoundationVideoPlayerApi api (%@) doesn't respond to @selector(setLooping:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; FLTLoopingMessage *arg_msg = GetNullableObjectAtIndex(args, 0); FlutterError *error; [api setLooping:arg_msg error:&error]; callback(wrapResult(nil, error)); }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.AVFoundationVideoPlayerApi.setVolume" binaryMessenger:binaryMessenger codec:FLTAVFoundationVideoPlayerApiGetCodec()]; if (api) { NSCAssert( [api respondsToSelector:@selector(setVolume:error:)], @"FLTAVFoundationVideoPlayerApi api (%@) doesn't respond to @selector(setVolume:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; FLTVolumeMessage *arg_msg = GetNullableObjectAtIndex(args, 0); FlutterError *error; [api setVolume:arg_msg error:&error]; callback(wrapResult(nil, error)); }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.AVFoundationVideoPlayerApi.setPlaybackSpeed" binaryMessenger:binaryMessenger codec:FLTAVFoundationVideoPlayerApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(setPlaybackSpeed:error:)], @"FLTAVFoundationVideoPlayerApi api (%@) doesn't respond to " @"@selector(setPlaybackSpeed:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; FLTPlaybackSpeedMessage *arg_msg = GetNullableObjectAtIndex(args, 0); FlutterError *error; [api setPlaybackSpeed:arg_msg error:&error]; callback(wrapResult(nil, error)); }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.AVFoundationVideoPlayerApi.play" binaryMessenger:binaryMessenger codec:FLTAVFoundationVideoPlayerApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(play:error:)], @"FLTAVFoundationVideoPlayerApi api (%@) doesn't respond to @selector(play:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; FLTTextureMessage *arg_msg = GetNullableObjectAtIndex(args, 0); FlutterError *error; [api play:arg_msg error:&error]; callback(wrapResult(nil, error)); }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.AVFoundationVideoPlayerApi.position" binaryMessenger:binaryMessenger codec:FLTAVFoundationVideoPlayerApiGetCodec()]; if (api) { NSCAssert( [api respondsToSelector:@selector(position:error:)], @"FLTAVFoundationVideoPlayerApi api (%@) doesn't respond to @selector(position:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; FLTTextureMessage *arg_msg = GetNullableObjectAtIndex(args, 0); FlutterError *error; FLTPositionMessage *output = [api position:arg_msg error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.AVFoundationVideoPlayerApi.seekTo" binaryMessenger:binaryMessenger codec:FLTAVFoundationVideoPlayerApiGetCodec()]; if (api) { NSCAssert( [api respondsToSelector:@selector(seekTo:error:)], @"FLTAVFoundationVideoPlayerApi api (%@) doesn't respond to @selector(seekTo:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; FLTPositionMessage *arg_msg = GetNullableObjectAtIndex(args, 0); FlutterError *error; [api seekTo:arg_msg error:&error]; callback(wrapResult(nil, error)); }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.AVFoundationVideoPlayerApi.pause" binaryMessenger:binaryMessenger codec:FLTAVFoundationVideoPlayerApiGetCodec()]; if (api) { NSCAssert( [api respondsToSelector:@selector(pause:error:)], @"FLTAVFoundationVideoPlayerApi api (%@) doesn't respond to @selector(pause:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; FLTTextureMessage *arg_msg = GetNullableObjectAtIndex(args, 0); FlutterError *error; [api pause:arg_msg error:&error]; callback(wrapResult(nil, error)); }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.AVFoundationVideoPlayerApi.setMixWithOthers" binaryMessenger:binaryMessenger codec:FLTAVFoundationVideoPlayerApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(setMixWithOthers:error:)], @"FLTAVFoundationVideoPlayerApi api (%@) doesn't respond to " @"@selector(setMixWithOthers:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; FLTMixWithOthersMessage *arg_msg = GetNullableObjectAtIndex(args, 0); FlutterError *error; [api setMixWithOthers:arg_msg error:&error]; callback(wrapResult(nil, error)); }]; } else { [channel setMessageHandler:nil]; } } }
plugins/packages/video_player/video_player_avfoundation/ios/Classes/messages.g.m/0
{ "file_path": "plugins/packages/video_player/video_player_avfoundation/ios/Classes/messages.g.m", "repo_id": "plugins", "token_count": 8496 }
1,328
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter_test/flutter_test.dart'; import 'package:video_player_platform_interface/video_player_platform_interface.dart'; void main() { test( 'VideoPlayerOptions allowBackgroundPlayback defaults to false', () { final VideoPlayerOptions options = VideoPlayerOptions(); expect(options.allowBackgroundPlayback, false); }, ); test( 'VideoPlayerOptions mixWithOthers defaults to false', () { final VideoPlayerOptions options = VideoPlayerOptions(); expect(options.mixWithOthers, false); }, ); }
plugins/packages/video_player/video_player_platform_interface/test/video_player_options_test.dart/0
{ "file_path": "plugins/packages/video_player/video_player_platform_interface/test/video_player_options_test.dart", "repo_id": "plugins", "token_count": 224 }
1,329
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /// The "length" of a video which doesn't have finite duration. // See: https://github.com/flutter/flutter/issues/107882 const Duration jsCompatibleTimeUnset = Duration( milliseconds: -9007199254740990, // Number.MIN_SAFE_INTEGER + 1. -(2^53 - 1) ); /// Converts a `num` duration coming from a [VideoElement] into a [Duration] that /// the plugin can use. /// /// From the documentation, `videoDuration` is "a double-precision floating-point /// value indicating the duration of the media in seconds. /// If no media data is available, the value `NaN` is returned. /// If the element's media doesn't have a known duration —such as for live media /// streams— the value of duration is `+Infinity`." /// /// If the `videoDuration` is finite, this method returns it as a `Duration`. /// If the `videoDuration` is `Infinity`, the duration will be /// `-9007199254740990` milliseconds. (See https://github.com/flutter/flutter/issues/107882) /// If the `videoDuration` is `NaN`, this will return null. Duration? convertNumVideoDurationToPluginDuration(num duration) { if (duration.isFinite) { return Duration( milliseconds: (duration * 1000).round(), ); } else if (duration.isInfinite) { return jsCompatibleTimeUnset; } return null; }
plugins/packages/video_player/video_player_web/lib/src/duration_utils.dart/0
{ "file_path": "plugins/packages/video_player/video_player_web/lib/src/duration_utils.dart", "repo_id": "plugins", "token_count": 421 }
1,330
// Mocks generated by Mockito 5.3.2 from annotations // in webview_flutter/test/legacy/webview_flutter_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i9; import 'package:flutter/foundation.dart' as _i3; import 'package:flutter/gestures.dart' as _i8; import 'package:flutter/widgets.dart' as _i2; import 'package:mockito/mockito.dart' as _i1; import 'package:webview_flutter_platform_interface/src/legacy/platform_interface/javascript_channel_registry.dart' as _i7; import 'package:webview_flutter_platform_interface/src/legacy/platform_interface/webview_platform.dart' as _i4; import 'package:webview_flutter_platform_interface/src/legacy/platform_interface/webview_platform_callbacks_handler.dart' as _i6; import 'package:webview_flutter_platform_interface/src/legacy/platform_interface/webview_platform_controller.dart' as _i10; import 'package:webview_flutter_platform_interface/src/legacy/types/types.dart' as _i5; // ignore_for_file: type=lint // ignore_for_file: avoid_redundant_argument_values // ignore_for_file: avoid_setters_without_getters // ignore_for_file: comment_references // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types // ignore_for_file: subtype_of_sealed_class class _FakeWidget_0 extends _i1.SmartFake implements _i2.Widget { _FakeWidget_0( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); @override String toString({_i3.DiagnosticLevel? minLevel = _i3.DiagnosticLevel.info}) => super.toString(); } /// A class which mocks [WebViewPlatform]. /// /// See the documentation for Mockito's code generation for more information. class MockWebViewPlatform extends _i1.Mock implements _i4.WebViewPlatform { MockWebViewPlatform() { _i1.throwOnMissingStub(this); } @override _i2.Widget build({ required _i2.BuildContext? context, required _i5.CreationParams? creationParams, required _i6.WebViewPlatformCallbacksHandler? webViewPlatformCallbacksHandler, required _i7.JavascriptChannelRegistry? javascriptChannelRegistry, _i4.WebViewPlatformCreatedCallback? onWebViewPlatformCreated, Set<_i3.Factory<_i8.OneSequenceGestureRecognizer>>? gestureRecognizers, }) => (super.noSuchMethod( Invocation.method( #build, [], { #context: context, #creationParams: creationParams, #webViewPlatformCallbacksHandler: webViewPlatformCallbacksHandler, #javascriptChannelRegistry: javascriptChannelRegistry, #onWebViewPlatformCreated: onWebViewPlatformCreated, #gestureRecognizers: gestureRecognizers, }, ), returnValue: _FakeWidget_0( this, Invocation.method( #build, [], { #context: context, #creationParams: creationParams, #webViewPlatformCallbacksHandler: webViewPlatformCallbacksHandler, #javascriptChannelRegistry: javascriptChannelRegistry, #onWebViewPlatformCreated: onWebViewPlatformCreated, #gestureRecognizers: gestureRecognizers, }, ), ), ) as _i2.Widget); @override _i9.Future<bool> clearCookies() => (super.noSuchMethod( Invocation.method( #clearCookies, [], ), returnValue: _i9.Future<bool>.value(false), ) as _i9.Future<bool>); } /// A class which mocks [WebViewPlatformController]. /// /// See the documentation for Mockito's code generation for more information. class MockWebViewPlatformController extends _i1.Mock implements _i10.WebViewPlatformController { MockWebViewPlatformController() { _i1.throwOnMissingStub(this); } @override _i9.Future<void> loadFile(String? absoluteFilePath) => (super.noSuchMethod( Invocation.method( #loadFile, [absoluteFilePath], ), returnValue: _i9.Future<void>.value(), returnValueForMissingStub: _i9.Future<void>.value(), ) as _i9.Future<void>); @override _i9.Future<void> loadFlutterAsset(String? key) => (super.noSuchMethod( Invocation.method( #loadFlutterAsset, [key], ), returnValue: _i9.Future<void>.value(), returnValueForMissingStub: _i9.Future<void>.value(), ) as _i9.Future<void>); @override _i9.Future<void> loadHtmlString( String? html, { String? baseUrl, }) => (super.noSuchMethod( Invocation.method( #loadHtmlString, [html], {#baseUrl: baseUrl}, ), returnValue: _i9.Future<void>.value(), returnValueForMissingStub: _i9.Future<void>.value(), ) as _i9.Future<void>); @override _i9.Future<void> loadUrl( String? url, Map<String, String>? headers, ) => (super.noSuchMethod( Invocation.method( #loadUrl, [ url, headers, ], ), returnValue: _i9.Future<void>.value(), returnValueForMissingStub: _i9.Future<void>.value(), ) as _i9.Future<void>); @override _i9.Future<void> loadRequest(_i5.WebViewRequest? request) => (super.noSuchMethod( Invocation.method( #loadRequest, [request], ), returnValue: _i9.Future<void>.value(), returnValueForMissingStub: _i9.Future<void>.value(), ) as _i9.Future<void>); @override _i9.Future<void> updateSettings(_i5.WebSettings? setting) => (super.noSuchMethod( Invocation.method( #updateSettings, [setting], ), returnValue: _i9.Future<void>.value(), returnValueForMissingStub: _i9.Future<void>.value(), ) as _i9.Future<void>); @override _i9.Future<String?> currentUrl() => (super.noSuchMethod( Invocation.method( #currentUrl, [], ), returnValue: _i9.Future<String?>.value(), ) as _i9.Future<String?>); @override _i9.Future<bool> canGoBack() => (super.noSuchMethod( Invocation.method( #canGoBack, [], ), returnValue: _i9.Future<bool>.value(false), ) as _i9.Future<bool>); @override _i9.Future<bool> canGoForward() => (super.noSuchMethod( Invocation.method( #canGoForward, [], ), returnValue: _i9.Future<bool>.value(false), ) as _i9.Future<bool>); @override _i9.Future<void> goBack() => (super.noSuchMethod( Invocation.method( #goBack, [], ), returnValue: _i9.Future<void>.value(), returnValueForMissingStub: _i9.Future<void>.value(), ) as _i9.Future<void>); @override _i9.Future<void> goForward() => (super.noSuchMethod( Invocation.method( #goForward, [], ), returnValue: _i9.Future<void>.value(), returnValueForMissingStub: _i9.Future<void>.value(), ) as _i9.Future<void>); @override _i9.Future<void> reload() => (super.noSuchMethod( Invocation.method( #reload, [], ), returnValue: _i9.Future<void>.value(), returnValueForMissingStub: _i9.Future<void>.value(), ) as _i9.Future<void>); @override _i9.Future<void> clearCache() => (super.noSuchMethod( Invocation.method( #clearCache, [], ), returnValue: _i9.Future<void>.value(), returnValueForMissingStub: _i9.Future<void>.value(), ) as _i9.Future<void>); @override _i9.Future<String> evaluateJavascript(String? javascript) => (super.noSuchMethod( Invocation.method( #evaluateJavascript, [javascript], ), returnValue: _i9.Future<String>.value(''), ) as _i9.Future<String>); @override _i9.Future<void> runJavascript(String? javascript) => (super.noSuchMethod( Invocation.method( #runJavascript, [javascript], ), returnValue: _i9.Future<void>.value(), returnValueForMissingStub: _i9.Future<void>.value(), ) as _i9.Future<void>); @override _i9.Future<String> runJavascriptReturningResult(String? javascript) => (super.noSuchMethod( Invocation.method( #runJavascriptReturningResult, [javascript], ), returnValue: _i9.Future<String>.value(''), ) as _i9.Future<String>); @override _i9.Future<void> addJavascriptChannels(Set<String>? javascriptChannelNames) => (super.noSuchMethod( Invocation.method( #addJavascriptChannels, [javascriptChannelNames], ), returnValue: _i9.Future<void>.value(), returnValueForMissingStub: _i9.Future<void>.value(), ) as _i9.Future<void>); @override _i9.Future<void> removeJavascriptChannels( Set<String>? javascriptChannelNames) => (super.noSuchMethod( Invocation.method( #removeJavascriptChannels, [javascriptChannelNames], ), returnValue: _i9.Future<void>.value(), returnValueForMissingStub: _i9.Future<void>.value(), ) as _i9.Future<void>); @override _i9.Future<String?> getTitle() => (super.noSuchMethod( Invocation.method( #getTitle, [], ), returnValue: _i9.Future<String?>.value(), ) as _i9.Future<String?>); @override _i9.Future<void> scrollTo( int? x, int? y, ) => (super.noSuchMethod( Invocation.method( #scrollTo, [ x, y, ], ), returnValue: _i9.Future<void>.value(), returnValueForMissingStub: _i9.Future<void>.value(), ) as _i9.Future<void>); @override _i9.Future<void> scrollBy( int? x, int? y, ) => (super.noSuchMethod( Invocation.method( #scrollBy, [ x, y, ], ), returnValue: _i9.Future<void>.value(), returnValueForMissingStub: _i9.Future<void>.value(), ) as _i9.Future<void>); @override _i9.Future<int> getScrollX() => (super.noSuchMethod( Invocation.method( #getScrollX, [], ), returnValue: _i9.Future<int>.value(0), ) as _i9.Future<int>); @override _i9.Future<int> getScrollY() => (super.noSuchMethod( Invocation.method( #getScrollY, [], ), returnValue: _i9.Future<int>.value(0), ) as _i9.Future<int>); }
plugins/packages/webview_flutter/webview_flutter/test/legacy/webview_flutter_test.mocks.dart/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter/test/legacy/webview_flutter_test.mocks.dart", "repo_id": "plugins", "token_count": 4963 }
1,331
<manifest package="io.flutter.plugins.webviewflutter"> </manifest>
plugins/packages/webview_flutter/webview_flutter_android/android/src/main/AndroidManifest.xml/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter_android/android/src/main/AndroidManifest.xml", "repo_id": "plugins", "token_count": 23 }
1,332
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.webviewflutter; import android.os.Handler; import android.os.IBinder; import android.view.View; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputConnection; /** * A fake View only exposed to InputMethodManager. * * <p>This follows a similar flow to Chromium's WebView (see * https://cs.chromium.org/chromium/src/content/public/android/java/src/org/chromium/content/browser/input/ThreadedInputConnectionProxyView.java). * WebView itself bounces its InputConnection around several different threads. We follow its logic * here to get the same working connection. * * <p>This exists solely to forward input creation to WebView's ThreadedInputConnectionProxyView on * the IME thread. The way that this is created in {@link * InputAwareWebView#checkInputConnectionProxy} guarantees that we have a handle to * ThreadedInputConnectionProxyView and {@link #onCreateInputConnection} is always called on the IME * thread. We delegate to ThreadedInputConnectionProxyView there to get WebView's input connection. */ final class ThreadedInputConnectionProxyAdapterView extends View { final Handler imeHandler; final IBinder windowToken; final View containerView; final View rootView; final View targetView; private boolean triggerDelayed = true; private boolean isLocked = false; private InputConnection cachedConnection; ThreadedInputConnectionProxyAdapterView(View containerView, View targetView, Handler imeHandler) { super(containerView.getContext()); this.imeHandler = imeHandler; this.containerView = containerView; this.targetView = targetView; windowToken = containerView.getWindowToken(); rootView = containerView.getRootView(); setFocusable(true); setFocusableInTouchMode(true); setVisibility(VISIBLE); } /** Returns whether or not this is currently asynchronously acquiring an input connection. */ boolean isTriggerDelayed() { return triggerDelayed; } /** Sets whether or not this should use its previously cached input connection. */ void setLocked(boolean locked) { isLocked = locked; } /** * This is expected to be called on the IME thread. See the setup required for this in {@link * InputAwareWebView#checkInputConnectionProxy(View)}. * * <p>Delegates to ThreadedInputConnectionProxyView to get WebView's input connection. */ @Override public InputConnection onCreateInputConnection(final EditorInfo outAttrs) { triggerDelayed = false; InputConnection inputConnection = (isLocked) ? cachedConnection : targetView.onCreateInputConnection(outAttrs); triggerDelayed = true; cachedConnection = inputConnection; return inputConnection; } @Override public boolean checkInputConnectionProxy(View view) { return true; } @Override public boolean hasWindowFocus() { // None of our views here correctly report they have window focus because of how we're embedding // the platform view inside of a virtual display. return true; } @Override public View getRootView() { return rootView; } @Override public boolean onCheckIsTextEditor() { return true; } @Override public boolean isFocused() { return true; } @Override public IBinder getWindowToken() { return windowToken; } @Override public Handler getHandler() { return imeHandler; } }
plugins/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/ThreadedInputConnectionProxyAdapterView.java/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/ThreadedInputConnectionProxyAdapterView.java", "repo_id": "plugins", "token_count": 1014 }
1,333
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.webviewflutter; 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 org.junit.Test; public class InstanceManagerTest { @Test public void addDartCreatedInstance() { final InstanceManager instanceManager = InstanceManager.open(identifier -> {}); final Object object = new Object(); instanceManager.addDartCreatedInstance(object, 0); assertEquals(object, instanceManager.getInstance(0)); assertEquals((Long) 0L, instanceManager.getIdentifierForStrongReference(object)); assertTrue(instanceManager.containsInstance(object)); instanceManager.close(); } @Test public void addHostCreatedInstance() { final InstanceManager instanceManager = InstanceManager.open(identifier -> {}); final Object object = new Object(); long identifier = instanceManager.addHostCreatedInstance(object); assertNotNull(instanceManager.getInstance(identifier)); assertEquals(object, instanceManager.getInstance(identifier)); assertTrue(instanceManager.containsInstance(object)); instanceManager.close(); } @Test public void remove() { final InstanceManager instanceManager = InstanceManager.open(identifier -> {}); Object object = new Object(); instanceManager.addDartCreatedInstance(object, 0); assertEquals(object, instanceManager.remove(0)); // To allow for object to be garbage collected. //noinspection UnusedAssignment object = null; Runtime.getRuntime().gc(); assertNull(instanceManager.getInstance(0)); instanceManager.close(); } @Test public void removeReturnsNullWhenClosed() { final Object object = new Object(); final InstanceManager instanceManager = InstanceManager.open(identifier -> {}); instanceManager.addDartCreatedInstance(object, 0); instanceManager.close(); assertNull(instanceManager.remove(0)); } @Test public void getIdentifierForStrongReferenceReturnsNullWhenClosed() { final Object object = new Object(); final InstanceManager instanceManager = InstanceManager.open(identifier -> {}); instanceManager.addDartCreatedInstance(object, 0); instanceManager.close(); assertNull(instanceManager.getIdentifierForStrongReference(object)); } @Test public void addHostCreatedInstanceReturnsNegativeOneWhenClosed() { final InstanceManager instanceManager = InstanceManager.open(identifier -> {}); instanceManager.close(); assertEquals(instanceManager.addHostCreatedInstance(new Object()), -1L); } @Test public void getInstanceReturnsNullWhenClosed() { final Object object = new Object(); final InstanceManager instanceManager = InstanceManager.open(identifier -> {}); instanceManager.addDartCreatedInstance(object, 0); instanceManager.close(); assertNull(instanceManager.getInstance(0)); } @Test public void containsInstanceReturnsFalseWhenClosed() { final Object object = new Object(); final InstanceManager instanceManager = InstanceManager.open(identifier -> {}); instanceManager.addDartCreatedInstance(object, 0); instanceManager.close(); assertFalse(instanceManager.containsInstance(object)); } }
plugins/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/InstanceManagerTest.java/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/InstanceManagerTest.java", "repo_id": "plugins", "token_count": 1025 }
1,334
org.gradle.jvmargs=-Xmx4G android.useAndroidX=true android.enableJetifier=true
plugins/packages/webview_flutter/webview_flutter_android/example/android/gradle.properties/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter_android/example/android/gradle.properties", "repo_id": "plugins", "token_count": 30 }
1,335
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // TODO(bparrishMines): Replace unused callback methods in constructors with // variables once automatic garbage collection is fully implemented. See // https://github.com/flutter/flutter/issues/107199. // ignore_for_file: avoid_unused_constructor_parameters // TODO(a14n): remove this import once Flutter 3.1 or later reaches stable (including flutter/flutter#104231) // ignore: unnecessary_import import 'dart:typed_data'; import 'dart:ui'; import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart' show BinaryMessenger; import 'package:flutter/widgets.dart' show AndroidViewSurface; import 'android_webview.g.dart'; import 'android_webview_api_impls.dart'; import 'instance_manager.dart'; export 'android_webview_api_impls.dart' show FileChooserMode; /// Root of the Java class hierarchy. /// /// See https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html. class JavaObject with Copyable { /// Constructs a [JavaObject] without creating the associated Java object. /// /// This should only be used by subclasses created by this library or to /// create copies. JavaObject.detached({ BinaryMessenger? binaryMessenger, InstanceManager? instanceManager, }) : _api = JavaObjectHostApiImpl( binaryMessenger: binaryMessenger, instanceManager: instanceManager, ); /// Global instance of [InstanceManager]. static final InstanceManager globalInstanceManager = InstanceManager( onWeakReferenceRemoved: (int identifier) { JavaObjectHostApiImpl().dispose(identifier); }, ); /// Pigeon Host Api implementation for [JavaObject]. final JavaObjectHostApiImpl _api; /// Release the reference to a native Java instance. static void dispose(JavaObject instance) { instance._api.instanceManager.removeWeakReference(instance); } @override JavaObject copy() { return JavaObject.detached(); } } /// An Android View that displays web pages. /// /// **Basic usage** /// In most cases, we recommend using a standard web browser, like Chrome, to /// deliver content to the user. To learn more about web browsers, read the /// guide on invoking a browser with /// [url_launcher](https://pub.dev/packages/url_launcher). /// /// WebView objects allow you to display web content as part of your widget /// layout, but lack some of the features of fully-developed browsers. A WebView /// is useful when you need increased control over the UI and advanced /// configuration options that will allow you to embed web pages in a /// specially-designed environment for your app. /// /// To learn more about WebView and alternatives for serving web content, read /// the documentation on /// [Web-based content](https://developer.android.com/guide/webapps). /// /// When a [WebView] is no longer needed [release] must be called. class WebView extends JavaObject { /// Constructs a new WebView. /// /// Due to changes in Flutter 3.0 the [useHybridComposition] doesn't have /// any effect and should not be exposed publicly. More info here: /// https://github.com/flutter/flutter/issues/108106 WebView({this.useHybridComposition = false}) : super.detached() { api.createFromInstance(this); } /// Constructs a [WebView] without creating the associated Java object. /// /// This should only be used by subclasses created by this library or to /// create copies. WebView.detached({this.useHybridComposition = false}) : super.detached(); /// Pigeon Host Api implementation for [WebView]. @visibleForTesting static WebViewHostApiImpl api = WebViewHostApiImpl(); /// Whether the [WebView] will be rendered with an [AndroidViewSurface]. /// /// This implementation uses hybrid composition to render the WebView Widget. /// This comes at the cost of some performance on Android versions below 10. /// See /// https://flutter.dev/docs/development/platform-integration/platform-views#performance /// for more information. /// /// Defaults to false. final bool useHybridComposition; /// The [WebSettings] object used to control the settings for this WebView. late final WebSettings settings = WebSettings(this); /// Enables debugging of web contents (HTML / CSS / JavaScript) loaded into any WebViews of this application. /// /// This flag can be enabled in order to facilitate debugging of web layouts /// and JavaScript code running inside WebViews. Please refer to [WebView] /// documentation for the debugging guide. The default is false. static Future<void> setWebContentsDebuggingEnabled(bool enabled) { return api.setWebContentsDebuggingEnabled(enabled); } /// Loads the given data into this WebView using a 'data' scheme URL. /// /// Note that JavaScript's same origin policy means that script running in a /// page loaded using this method will be unable to access content loaded /// using any scheme other than 'data', including 'http(s)'. To avoid this /// restriction, use [loadDataWithBaseURL()] with an appropriate base URL. /// /// The [encoding] parameter specifies whether the data is base64 or URL /// encoded. If the data is base64 encoded, the value of the encoding /// parameter must be `'base64'`. HTML can be encoded with /// `base64.encode(bytes)` like so: /// ```dart /// import 'dart:convert'; /// /// final unencodedHtml = ''' /// <html><body>'%28' is the code for '('</body></html> /// '''; /// final encodedHtml = base64.encode(utf8.encode(unencodedHtml)); /// print(encodedHtml); /// ``` /// /// The [mimeType] parameter specifies the format of the data. If WebView /// can't handle the specified MIME type, it will download the data. If /// `null`, defaults to 'text/html'. Future<void> loadData({ required String data, String? mimeType, String? encoding, }) { return api.loadDataFromInstance( this, data, mimeType, encoding, ); } /// Loads the given data into this WebView. /// /// The [baseUrl] is used as base URL for the content. It is used both to /// resolve relative URLs and when applying JavaScript's same origin policy. /// /// The [historyUrl] is used for the history entry. /// /// The [mimeType] parameter specifies the format of the data. If WebView /// can't handle the specified MIME type, it will download the data. If /// `null`, defaults to 'text/html'. /// /// Note that content specified in this way can access local device files (via /// 'file' scheme URLs) only if baseUrl specifies a scheme other than 'http', /// 'https', 'ftp', 'ftps', 'about' or 'javascript'. /// /// If the base URL uses the data scheme, this method is equivalent to calling /// [loadData] and the [historyUrl] is ignored, and the data will be treated /// as part of a data: URL, including the requirement that the content be /// URL-encoded or base64 encoded. If the base URL uses any other scheme, then /// the data will be loaded into the WebView as a plain string (i.e. not part /// of a data URL) and any URL-encoded entities in the string will not be /// decoded. /// /// Note that the [baseUrl] is sent in the 'Referer' HTTP header when /// requesting subresources (images, etc.) of the page loaded using this /// method. /// /// If a valid HTTP or HTTPS base URL is not specified in [baseUrl], then /// content loaded using this method will have a `window.origin` value of /// `"null"`. This must not be considered to be a trusted origin by the /// application or by any JavaScript code running inside the WebView (for /// example, event sources in DOM event handlers or web messages), because /// malicious content can also create frames with a null origin. If you need /// to identify the main frame's origin in a trustworthy way, you should use a /// valid HTTP or HTTPS base URL to set the origin. Future<void> loadDataWithBaseUrl({ String? baseUrl, required String data, String? mimeType, String? encoding, String? historyUrl, }) { return api.loadDataWithBaseUrlFromInstance( this, baseUrl, data, mimeType, encoding, historyUrl, ); } /// Loads the given URL with additional HTTP headers, specified as a map from name to value. /// /// Note that if this map contains any of the headers that are set by default /// by this WebView, such as those controlling caching, accept types or the /// User-Agent, their values may be overridden by this WebView's defaults. /// /// Also see compatibility note on [evaluateJavascript]. Future<void> loadUrl(String url, Map<String, String> headers) { return api.loadUrlFromInstance(this, url, headers); } /// Loads the URL with postData using "POST" method into this WebView. /// /// If url is not a network URL, it will be loaded with [loadUrl] instead, ignoring the postData param. Future<void> postUrl(String url, Uint8List data) { return api.postUrlFromInstance(this, url, data); } /// Gets the URL for the current page. /// /// This is not always the same as the URL passed to /// [WebViewClient.onPageStarted] because although the load for that URL has /// begun, the current page may not have changed. /// /// Returns null if no page has been loaded. Future<String?> getUrl() { return api.getUrlFromInstance(this); } /// Whether this WebView has a back history item. Future<bool> canGoBack() { return api.canGoBackFromInstance(this); } /// Whether this WebView has a forward history item. Future<bool> canGoForward() { return api.canGoForwardFromInstance(this); } /// Goes back in the history of this WebView. Future<void> goBack() { return api.goBackFromInstance(this); } /// Goes forward in the history of this WebView. Future<void> goForward() { return api.goForwardFromInstance(this); } /// Reloads the current URL. Future<void> reload() { return api.reloadFromInstance(this); } /// Clears the resource cache. /// /// Note that the cache is per-application, so this will clear the cache for /// all WebViews used. Future<void> clearCache(bool includeDiskFiles) { return api.clearCacheFromInstance(this, includeDiskFiles); } // TODO(bparrishMines): Update documentation once addJavascriptInterface is added. /// Asynchronously evaluates JavaScript in the context of the currently displayed page. /// /// If non-null, the returned value will be any result returned from that /// execution. /// /// Compatibility note. Applications targeting Android versions N or later, /// JavaScript state from an empty WebView is no longer persisted across /// navigations like [loadUrl]. For example, global variables and functions /// defined before calling [loadUrl]) will not exist in the loaded page. Future<String?> evaluateJavascript(String javascriptString) { return api.evaluateJavascriptFromInstance( this, javascriptString, ); } // TODO(bparrishMines): Update documentation when WebViewClient.onReceivedTitle is added. /// Gets the title for the current page. /// /// Returns null if no page has been loaded. Future<String?> getTitle() { return api.getTitleFromInstance(this); } // TODO(bparrishMines): Update documentation when onScrollChanged is added. /// Set the scrolled position of your view. Future<void> scrollTo(int x, int y) { return api.scrollToFromInstance(this, x, y); } // TODO(bparrishMines): Update documentation when onScrollChanged is added. /// Move the scrolled position of your view. Future<void> scrollBy(int x, int y) { return api.scrollByFromInstance(this, x, y); } /// Return the scrolled left position of this view. /// /// This is the left edge of the displayed part of your view. You do not /// need to draw any pixels farther left, since those are outside of the frame /// of your view on screen. Future<int> getScrollX() { return api.getScrollXFromInstance(this); } /// Return the scrolled top position of this view. /// /// This is the top edge of the displayed part of your view. You do not need /// to draw any pixels above it, since those are outside of the frame of your /// view on screen. Future<int> getScrollY() { return api.getScrollYFromInstance(this); } /// Returns the X and Y scroll position of this view. Future<Offset> getScrollPosition() { return api.getScrollPositionFromInstance(this); } /// Sets the [WebViewClient] that will receive various notifications and requests. /// /// This will replace the current handler. Future<void> setWebViewClient(WebViewClient webViewClient) { return api.setWebViewClientFromInstance(this, webViewClient); } /// Injects the supplied [JavascriptChannel] into this WebView. /// /// The object is injected into all frames of the web page, including all the /// iframes, using the supplied name. This allows the object's methods to /// be accessed from JavaScript. /// /// Note that injected objects will not appear in JavaScript until the page is /// next (re)loaded. JavaScript should be enabled before injecting the object. /// For example: /// /// ```dart /// webview.settings.setJavaScriptEnabled(true); /// webView.addJavascriptChannel(JavScriptChannel("injectedObject")); /// webView.loadUrl("about:blank", <String, String>{}); /// webView.loadUrl("javascript:injectedObject.postMessage("Hello, World!")", <String, String>{}); /// ``` /// /// **Important** /// * Because the object is exposed to all the frames, any frame could obtain /// the object name and call methods on it. There is no way to tell the /// calling frame's origin from the app side, so the app must not assume that /// the caller is trustworthy unless the app can guarantee that no third party /// content is ever loaded into the WebView even inside an iframe. Future<void> addJavaScriptChannel(JavaScriptChannel javaScriptChannel) { JavaScriptChannel.api.createFromInstance(javaScriptChannel); return api.addJavaScriptChannelFromInstance(this, javaScriptChannel); } /// Removes a previously injected [JavaScriptChannel] from this WebView. /// /// Note that the removal will not be reflected in JavaScript until the page /// is next (re)loaded. See [addJavaScriptChannel]. Future<void> removeJavaScriptChannel(JavaScriptChannel javaScriptChannel) { JavaScriptChannel.api.createFromInstance(javaScriptChannel); return api.removeJavaScriptChannelFromInstance(this, javaScriptChannel); } /// Registers the interface to be used when content can not be handled by the rendering engine, and should be downloaded instead. /// /// This will replace the current handler. Future<void> setDownloadListener(DownloadListener? listener) { return api.setDownloadListenerFromInstance(this, listener); } /// Sets the chrome handler. /// /// This is an implementation of [WebChromeClient] for use in handling /// JavaScript dialogs, favicons, titles, and the progress. This will replace /// the current handler. Future<void> setWebChromeClient(WebChromeClient? client) { return api.setWebChromeClientFromInstance(this, client); } /// Sets the background color of this WebView. Future<void> setBackgroundColor(Color color) { return api.setBackgroundColorFromInstance(this, color.value); } @override WebView copy() { return WebView.detached(useHybridComposition: useHybridComposition); } } /// Manages cookies globally for all webviews. class CookieManager { CookieManager._(); static CookieManager? _instance; /// Gets the globally set CookieManager instance. static CookieManager get instance => _instance ??= CookieManager._(); /// Setter for the singleton value, for testing purposes only. @visibleForTesting static set instance(CookieManager value) => _instance = value; /// Pigeon Host Api implementation for [CookieManager]. @visibleForTesting static CookieManagerHostApi api = CookieManagerHostApi(); /// Sets a single cookie (key-value pair) for the given URL. Any existing /// cookie with the same host, path and name will be replaced with the new /// cookie. The cookie being set will be ignored if it is expired. To set /// multiple cookies, your application should invoke this method multiple /// times. /// /// The value parameter must follow the format of the Set-Cookie HTTP /// response header defined by RFC6265bis. This is a key-value pair of the /// form "key=value", optionally followed by a list of cookie attributes /// delimited with semicolons (ex. "key=value; Max-Age=123"). Please consult /// the RFC specification for a list of valid attributes. /// /// Note: if specifying a value containing the "Secure" attribute, url must /// use the "https://" scheme. /// /// Params: /// url – the URL for which the cookie is to be set /// value – the cookie as a string, using the format of the 'Set-Cookie' HTTP response header Future<void> setCookie(String url, String value) => api.setCookie(url, value); /// Removes all cookies. /// /// The returned future resolves to true if any cookies were removed. Future<bool> clearCookies() => api.clearCookies(); } /// Manages settings state for a [WebView]. /// /// When a WebView is first created, it obtains a set of default settings. These /// default settings will be returned from any getter call. A WebSettings object /// obtained from [WebView.settings] is tied to the life of the WebView. If a /// WebView has been destroyed, any method call on [WebSettings] will throw an /// Exception. class WebSettings extends JavaObject { /// Constructs a [WebSettings]. /// /// This constructor is only used for testing. An instance should be obtained /// with [WebView.settings]. @visibleForTesting WebSettings(WebView webView) : super.detached() { api.createFromInstance(this, webView); } /// Constructs a [WebSettings] without creating the associated Java object. /// /// This should only be used by subclasses created by this library or to /// create copies. WebSettings.detached() : super.detached(); /// Pigeon Host Api implementation for [WebSettings]. @visibleForTesting static WebSettingsHostApiImpl api = WebSettingsHostApiImpl(); /// Sets whether the DOM storage API is enabled. /// /// The default value is false. Future<void> setDomStorageEnabled(bool flag) { return api.setDomStorageEnabledFromInstance(this, flag); } /// Tells JavaScript to open windows automatically. /// /// This applies to the JavaScript function `window.open()`. The default is /// false. Future<void> setJavaScriptCanOpenWindowsAutomatically(bool flag) { return api.setJavaScriptCanOpenWindowsAutomaticallyFromInstance( this, flag, ); } // TODO(bparrishMines): Update documentation when WebChromeClient.onCreateWindow is added. /// Sets whether the WebView should supports multiple windows. /// /// The default is false. Future<void> setSupportMultipleWindows(bool support) { return api.setSupportMultipleWindowsFromInstance(this, support); } /// Tells the WebView to enable JavaScript execution. /// /// The default is false. Future<void> setJavaScriptEnabled(bool flag) { return api.setJavaScriptEnabledFromInstance(this, flag); } /// Sets the WebView's user-agent string. /// /// If the string is empty, the system default value will be used. Note that /// starting from KITKAT Android version, changing the user-agent while /// loading a web page causes WebView to initiate loading once again. Future<void> setUserAgentString(String? userAgentString) { return api.setUserAgentStringFromInstance(this, userAgentString); } /// Sets whether the WebView requires a user gesture to play media. /// /// The default is true. Future<void> setMediaPlaybackRequiresUserGesture(bool require) { return api.setMediaPlaybackRequiresUserGestureFromInstance(this, require); } // TODO(bparrishMines): Update documentation when WebView.zoomIn and WebView.zoomOut are added. /// Sets whether the WebView should support zooming using its on-screen zoom controls and gestures. /// /// The particular zoom mechanisms that should be used can be set with /// [setBuiltInZoomControls]. /// /// The default is true. Future<void> setSupportZoom(bool support) { return api.setSupportZoomFromInstance(this, support); } /// Sets whether the WebView loads pages in overview mode, that is, zooms out the content to fit on screen by width. /// /// This setting is taken into account when the content width is greater than /// the width of the WebView control, for example, when [setUseWideViewPort] /// is enabled. /// /// The default is false. Future<void> setLoadWithOverviewMode(bool overview) { return api.setLoadWithOverviewModeFromInstance(this, overview); } /// Sets whether the WebView should enable support for the "viewport" HTML meta tag or should use a wide viewport. /// /// When the value of the setting is false, the layout width is always set to /// the width of the WebView control in device-independent (CSS) pixels. When /// the value is true and the page contains the viewport meta tag, the value /// of the width specified in the tag is used. If the page does not contain /// the tag or does not provide a width, then a wide viewport will be used. Future<void> setUseWideViewPort(bool use) { return api.setUseWideViewPortFromInstance(this, use); } // TODO(bparrishMines): Update documentation when ZoomButtonsController is added. /// Sets whether the WebView should display on-screen zoom controls when using the built-in zoom mechanisms. /// /// See [setBuiltInZoomControls]. The default is true. However, on-screen zoom /// controls are deprecated in Android so it's recommended to set this to /// false. Future<void> setDisplayZoomControls(bool enabled) { return api.setDisplayZoomControlsFromInstance(this, enabled); } // TODO(bparrishMines): Update documentation when ZoomButtonsController is added. /// Sets whether the WebView should use its built-in zoom mechanisms. /// /// The built-in zoom mechanisms comprise on-screen zoom controls, which are /// displayed over the WebView's content, and the use of a pinch gesture to /// control zooming. Whether or not these on-screen controls are displayed can /// be set with [setDisplayZoomControls]. The default is false. /// /// The built-in mechanisms are the only currently supported zoom mechanisms, /// so it is recommended that this setting is always enabled. However, /// on-screen zoom controls are deprecated in Android so it's recommended to /// disable [setDisplayZoomControls]. Future<void> setBuiltInZoomControls(bool enabled) { return api.setBuiltInZoomControlsFromInstance(this, enabled); } /// Enables or disables file access within WebView. /// /// This enables or disables file system access only. Assets and resources are /// still accessible using file:///android_asset and file:///android_res. The /// default value is true for apps targeting Build.VERSION_CODES.Q and below, /// and false when targeting Build.VERSION_CODES.R and above. Future<void> setAllowFileAccess(bool enabled) { return api.setAllowFileAccessFromInstance(this, enabled); } @override WebSettings copy() { return WebSettings.detached(); } } /// Exposes a channel to receive calls from javaScript. /// /// See [WebView.addJavaScriptChannel]. class JavaScriptChannel extends JavaObject { /// Constructs a [JavaScriptChannel]. JavaScriptChannel( this.channelName, { required this.postMessage, }) : super.detached() { AndroidWebViewFlutterApis.instance.ensureSetUp(); api.createFromInstance(this); } /// Constructs a [JavaScriptChannel] without creating the associated Java /// object. /// /// This should only be used by subclasses created by this library or to /// create copies. JavaScriptChannel.detached( this.channelName, { required this.postMessage, }) : super.detached(); /// Pigeon Host Api implementation for [JavaScriptChannel]. @visibleForTesting static JavaScriptChannelHostApiImpl api = JavaScriptChannelHostApiImpl(); /// Used to identify this object to receive messages from javaScript. final String channelName; /// Callback method when javaScript calls `postMessage` on the object instance passed. final void Function(String message) postMessage; @override JavaScriptChannel copy() { return JavaScriptChannel.detached(channelName, postMessage: postMessage); } } /// Receive various notifications and requests for [WebView]. class WebViewClient extends JavaObject { /// Constructs a [WebViewClient]. WebViewClient({ this.onPageStarted, this.onPageFinished, this.onReceivedRequestError, @Deprecated('Only called on Android version < 23.') this.onReceivedError, this.requestLoading, this.urlLoading, }) : super.detached() { AndroidWebViewFlutterApis.instance.ensureSetUp(); api.createFromInstance(this); } /// Constructs a [WebViewClient] without creating the associated Java object. /// /// This should only be used by subclasses created by this library or to /// create copies. WebViewClient.detached({ this.onPageStarted, this.onPageFinished, this.onReceivedRequestError, @Deprecated('Only called on Android version < 23.') this.onReceivedError, this.requestLoading, this.urlLoading, }) : super.detached(); /// User authentication failed on server. /// /// See https://developer.android.com/reference/android/webkit/WebViewClient#ERROR_AUTHENTICATION static const int errorAuthentication = -4; /// Malformed URL. /// /// See https://developer.android.com/reference/android/webkit/WebViewClient#ERROR_BAD_URL static const int errorBadUrl = -12; /// Failed to connect to the server. /// /// See https://developer.android.com/reference/android/webkit/WebViewClient#ERROR_CONNECT static const int errorConnect = -6; /// Failed to perform SSL handshake. /// /// See https://developer.android.com/reference/android/webkit/WebViewClient#ERROR_FAILED_SSL_HANDSHAKE static const int errorFailedSslHandshake = -11; /// Generic file error. /// /// See https://developer.android.com/reference/android/webkit/WebViewClient#ERROR_FILE static const int errorFile = -13; /// File not found. /// /// See https://developer.android.com/reference/android/webkit/WebViewClient#ERROR_FILE_NOT_FOUND static const int errorFileNotFound = -14; /// Server or proxy hostname lookup failed. /// /// See https://developer.android.com/reference/android/webkit/WebViewClient#ERROR_HOST_LOOKUP static const int errorHostLookup = -2; /// Failed to read or write to the server. /// /// See https://developer.android.com/reference/android/webkit/WebViewClient#ERROR_IO static const int errorIO = -7; /// User authentication failed on proxy. /// /// See https://developer.android.com/reference/android/webkit/WebViewClient#ERROR_PROXY_AUTHENTICATION static const int errorProxyAuthentication = -5; /// Too many redirects. /// /// See https://developer.android.com/reference/android/webkit/WebViewClient#ERROR_REDIRECT_LOOP static const int errorRedirectLoop = -9; /// Connection timed out. /// /// See https://developer.android.com/reference/android/webkit/WebViewClient#ERROR_TIMEOUT static const int errorTimeout = -8; /// Too many requests during this load. /// /// See https://developer.android.com/reference/android/webkit/WebViewClient#ERROR_TOO_MANY_REQUESTS static const int errorTooManyRequests = -15; /// Generic error. /// /// See https://developer.android.com/reference/android/webkit/WebViewClient#ERROR_UNKNOWN static const int errorUnknown = -1; /// Resource load was canceled by Safe Browsing. /// /// See https://developer.android.com/reference/android/webkit/WebViewClient#ERROR_UNSAFE_RESOURCE static const int errorUnsafeResource = -16; /// Unsupported authentication scheme (not basic or digest). /// /// See https://developer.android.com/reference/android/webkit/WebViewClient#ERROR_UNSUPPORTED_AUTH_SCHEME static const int errorUnsupportedAuthScheme = -3; /// Unsupported URI scheme. /// /// See https://developer.android.com/reference/android/webkit/WebViewClient#ERROR_UNSUPPORTED_SCHEME static const int errorUnsupportedScheme = -10; /// Pigeon Host Api implementation for [WebViewClient]. @visibleForTesting static WebViewClientHostApiImpl api = WebViewClientHostApiImpl(); /// Notify the host application that a page has started loading. /// /// This method is called once for each main frame load so a page with iframes /// or framesets will call onPageStarted one time for the main frame. This /// also means that [onPageStarted] will not be called when the contents of an /// embedded frame changes, i.e. clicking a link whose target is an iframe, it /// will also not be called for fragment navigations (navigations to /// #fragment_id). final void Function(WebView webView, String url)? onPageStarted; // TODO(bparrishMines): Update documentation when WebView.postVisualStateCallback is added. /// Notify the host application that a page has finished loading. /// /// This method is called only for main frame. Receiving an [onPageFinished] /// callback does not guarantee that the next frame drawn by WebView will /// reflect the state of the DOM at this point. final void Function(WebView webView, String url)? onPageFinished; /// Report web resource loading error to the host application. /// /// These errors usually indicate inability to connect to the server. Note /// that unlike the deprecated version of the callback, the new version will /// be called for any resource (iframe, image, etc.), not just for the main /// page. Thus, it is recommended to perform minimum required work in this /// callback. final void Function( WebView webView, WebResourceRequest request, WebResourceError error, )? onReceivedRequestError; /// Report an error to the host application. /// /// These errors are unrecoverable (i.e. the main resource is unavailable). /// The errorCode parameter corresponds to one of the error* constants. @Deprecated('Only called on Android version < 23.') final void Function( WebView webView, int errorCode, String description, String failingUrl, )? onReceivedError; /// When the current [WebView] wants to load a URL. /// /// The value set by [setSynchronousReturnValueForShouldOverrideUrlLoading] /// indicates whether the [WebView] loaded the request. final void Function(WebView webView, WebResourceRequest request)? requestLoading; /// When the current [WebView] wants to load a URL. /// /// The value set by [setSynchronousReturnValueForShouldOverrideUrlLoading] /// indicates whether the [WebView] loaded the URL. final void Function(WebView webView, String url)? urlLoading; /// Sets the required synchronous return value for the Java method, /// `WebViewClient.shouldOverrideUrlLoading(...)`. /// /// The Java method, `WebViewClient.shouldOverrideUrlLoading(...)`, requires /// a boolean to be returned and this method sets the returned value for all /// calls to the Java method. /// /// Setting this to true causes the current [WebView] to abort loading any URL /// received by [requestLoading] or [urlLoading], while setting this to false /// causes the [WebView] to continue loading a URL as usual. /// /// Defaults to false. Future<void> setSynchronousReturnValueForShouldOverrideUrlLoading( bool value, ) { return api.setShouldOverrideUrlLoadingReturnValueFromInstance(this, value); } @override WebViewClient copy() { return WebViewClient.detached( onPageStarted: onPageStarted, onPageFinished: onPageFinished, onReceivedRequestError: onReceivedRequestError, onReceivedError: onReceivedError, requestLoading: requestLoading, urlLoading: urlLoading, ); } } /// The interface to be used when content can not be handled by the rendering /// engine for [WebView], and should be downloaded instead. class DownloadListener extends JavaObject { /// Constructs a [DownloadListener]. DownloadListener({required this.onDownloadStart}) : super.detached() { AndroidWebViewFlutterApis.instance.ensureSetUp(); api.createFromInstance(this); } /// Constructs a [DownloadListener] without creating the associated Java /// object. /// /// This should only be used by subclasses created by this library or to /// create copies. DownloadListener.detached({required this.onDownloadStart}) : super.detached(); /// Pigeon Host Api implementation for [DownloadListener]. @visibleForTesting static DownloadListenerHostApiImpl api = DownloadListenerHostApiImpl(); /// Notify the host application that a file should be downloaded. final void Function( String url, String userAgent, String contentDisposition, String mimetype, int contentLength, ) onDownloadStart; @override DownloadListener copy() { return DownloadListener.detached(onDownloadStart: onDownloadStart); } } /// Handles JavaScript dialogs, favicons, titles, and the progress for [WebView]. class WebChromeClient extends JavaObject { /// Constructs a [WebChromeClient]. WebChromeClient({this.onProgressChanged, this.onShowFileChooser}) : super.detached() { AndroidWebViewFlutterApis.instance.ensureSetUp(); api.createFromInstance(this); } /// Constructs a [WebChromeClient] without creating the associated Java /// object. /// /// This should only be used by subclasses created by this library or to /// create copies. WebChromeClient.detached({ this.onProgressChanged, this.onShowFileChooser, }) : super.detached(); /// Pigeon Host Api implementation for [WebChromeClient]. @visibleForTesting static WebChromeClientHostApiImpl api = WebChromeClientHostApiImpl(); /// Notify the host application that a file should be downloaded. final void Function(WebView webView, int progress)? onProgressChanged; /// Indicates the client should show a file chooser. /// /// To handle the request for a file chooser with this callback, passing true /// to [setSynchronousReturnValueForOnShowFileChooser] is required. Otherwise, /// the returned list of strings will be ignored and the client will use the /// default handling of a file chooser request. /// /// Only invoked on Android versions 21+. final Future<List<String>> Function( WebView webView, FileChooserParams params, )? onShowFileChooser; /// Sets the required synchronous return value for the Java method, /// `WebChromeClient.onShowFileChooser(...)`. /// /// The Java method, `WebChromeClient.onShowFileChooser(...)`, requires /// a boolean to be returned and this method sets the returned value for all /// calls to the Java method. /// /// Setting this to true indicates that all file chooser requests should be /// handled by [onShowFileChooser] and the returned list of Strings will be /// returned to the WebView. Otherwise, the client will use the default /// handling and the returned value in [onShowFileChooser] will be ignored. /// /// Requires [onShowFileChooser] to be nonnull. /// /// Defaults to false. Future<void> setSynchronousReturnValueForOnShowFileChooser( bool value, ) { if (value && onShowFileChooser == null) { throw StateError( 'Setting this to true requires `onShowFileChooser` to be nonnull.', ); } return api.setSynchronousReturnValueForOnShowFileChooserFromInstance( this, value, ); } @override WebChromeClient copy() { return WebChromeClient.detached( onProgressChanged: onProgressChanged, onShowFileChooser: onShowFileChooser, ); } } /// Parameters received when a [WebChromeClient] should show a file chooser. /// /// See https://developer.android.com/reference/android/webkit/WebChromeClient.FileChooserParams. class FileChooserParams extends JavaObject { /// Constructs a [FileChooserParams] without creating the associated Java /// object. /// /// This should only be used by subclasses created by this library or to /// create copies. FileChooserParams.detached({ required this.isCaptureEnabled, required this.acceptTypes, required this.filenameHint, required this.mode, super.binaryMessenger, super.instanceManager, }) : super.detached(); /// Preference for a live media captured value (e.g. Camera, Microphone). final bool isCaptureEnabled; /// A list of acceptable MIME types. final List<String> acceptTypes; /// The file name of a default selection if specified, or null. final String? filenameHint; /// Mode of how to select files for a file chooser. final FileChooserMode mode; @override FileChooserParams copy() { return FileChooserParams.detached( isCaptureEnabled: isCaptureEnabled, acceptTypes: acceptTypes, filenameHint: filenameHint, mode: mode, ); } } /// Encompasses parameters to the [WebViewClient.requestLoading] method. class WebResourceRequest { /// Constructs a [WebResourceRequest]. WebResourceRequest({ required this.url, required this.isForMainFrame, required this.isRedirect, required this.hasGesture, required this.method, required this.requestHeaders, }); /// The URL for which the resource request was made. final String url; /// Whether the request was made in order to fetch the main frame's document. final bool isForMainFrame; /// Whether the request was a result of a server-side redirect. /// /// Only supported on Android version >= 24. final bool? isRedirect; /// Whether a gesture (such as a click) was associated with the request. final bool hasGesture; /// The method associated with the request, for example "GET". final String method; /// The headers associated with the request. final Map<String, String> requestHeaders; } /// Encapsulates information about errors occurred during loading of web resources. /// /// See [WebViewClient.onReceivedRequestError]. class WebResourceError { /// Constructs a [WebResourceError]. WebResourceError({ required this.errorCode, required this.description, }); /// The integer code of the error (e.g. [WebViewClient.errorAuthentication]. final int errorCode; /// Describes the error. final String description; } /// Manages Flutter assets that are part of Android's app bundle. class FlutterAssetManager { /// Constructs the [FlutterAssetManager]. const FlutterAssetManager(); /// Pigeon Host Api implementation for [FlutterAssetManager]. @visibleForTesting static FlutterAssetManagerHostApi api = FlutterAssetManagerHostApi(); /// Lists all assets at the given path. /// /// The assets are returned as a `List<String>`. The `List<String>` only /// contains files which are direct childs Future<List<String?>> list(String path) => api.list(path); /// Gets the relative file path to the Flutter asset with the given name. Future<String> getAssetFilePathByName(String name) => api.getAssetFilePathByName(name); } /// Manages the JavaScript storage APIs provided by the [WebView]. /// /// Wraps [WebStorage](https://developer.android.com/reference/android/webkit/WebStorage). class WebStorage extends JavaObject { /// Constructs a [WebStorage]. /// /// This constructor is only used for testing. An instance should be obtained /// with [WebStorage.instance]. @visibleForTesting WebStorage() : super.detached() { AndroidWebViewFlutterApis.instance.ensureSetUp(); api.createFromInstance(this); } /// Constructs a [WebStorage] without creating the associated Java object. /// /// This should only be used by subclasses created by this library or to /// create copies. WebStorage.detached() : super.detached(); /// Pigeon Host Api implementation for [WebStorage]. @visibleForTesting static WebStorageHostApiImpl api = WebStorageHostApiImpl(); /// The singleton instance of this class. static WebStorage instance = WebStorage(); /// Clears all storage currently being used by the JavaScript storage APIs. Future<void> deleteAllData() { return api.deleteAllDataFromInstance(this); } @override WebStorage copy() { return WebStorage.detached(); } }
plugins/packages/webview_flutter/webview_flutter_android/lib/src/android_webview.dart/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter_android/lib/src/android_webview.dart", "repo_id": "plugins", "token_count": 11597 }
1,336
name: webview_flutter_android description: A Flutter plugin that provides a WebView widget on Android. repository: https://github.com/flutter/plugins/tree/main/packages/webview_flutter/webview_flutter_android issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+webview%22 version: 3.3.0 environment: sdk: ">=2.17.0 <3.0.0" flutter: ">=3.0.0" flutter: plugin: implements: webview_flutter platforms: android: package: io.flutter.plugins.webviewflutter pluginClass: WebViewFlutterPlugin dartPluginClass: AndroidWebViewPlatform dependencies: flutter: sdk: flutter webview_flutter_platform_interface: ^2.0.0 dev_dependencies: build_runner: ^2.1.4 flutter_driver: sdk: flutter flutter_test: sdk: flutter mockito: ^5.3.2 pigeon: ^4.2.14
plugins/packages/webview_flutter/webview_flutter_android/pubspec.yaml/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter_android/pubspec.yaml", "repo_id": "plugins", "token_count": 352 }
1,337
## NEXT * Updates minimum Flutter version to 3.0. ## 2.0.1 * Improves error message when a platform interface class is used before `WebViewPlatform.instance` has been set. ## 2.0.0 * **Breaking Change**: Releases new interface. See [documentation](https://pub.dev/documentation/webview_flutter_platform_interface/2.0.0/) and [design doc](https://flutter.dev/go/webview_flutter_4_interface) for more details. * **Breaking Change**: Removes MethodChannel implementation of interface. All platform implementations will now need to create their own by implementing `WebViewPlatform`. ## 1.9.5 * Updates code for `no_leading_underscores_for_local_identifiers` lint. ## 1.9.4 * Updates imports for `prefer_relative_imports`. ## 1.9.3 * Updates minimum Flutter version to 2.10. * Removes `BuildParams` from v4 interface and adds `layoutDirection` to the creation params. ## 1.9.2 * Fixes avoid_redundant_argument_values lint warnings and minor typos. * Ignores unnecessary import warnings in preparation for [upcoming Flutter changes](https://github.com/flutter/flutter/pull/106316). * Adds missing build params for v4 WebViewWidget interface. ## 1.9.1 * Ignores unnecessary import warnings in preparation for [upcoming Flutter changes](https://github.com/flutter/flutter/pull/104231). ## 1.9.0 * Adds the first iteration of the v4 webview_flutter interface implementation. * Removes unnecessary imports. ## 1.8.2 * Migrates from `ui.hash*` to `Object.hash*`. * Updates minimum Flutter version to 2.5.0. ## 1.8.1 * Update to use the `verify` method introduced in platform_plugin_interface 2.1.0. ## 1.8.0 * Adds the `loadFlutterAsset` method to the platform interface. ## 1.7.0 * Add an option to set the background color of the webview. ## 1.6.1 * Revert deprecation of `clearCookies` in WebViewPlatform for later deprecation. ## 1.6.0 * Adds platform interface for cookie manager. * Deprecates `clearCookies` in WebViewPlatform in favour of `CookieManager#clearCookies`. * Expanded `CreationParams` to include cookies to be set at webview creation. ## 1.5.2 * Mirgrates from analysis_options_legacy.yaml to the more strict analysis_options.yaml. ## 1.5.1 * Reverts the addition of `onUrlChanged`, which was unintentionally a breaking change. ## 1.5.0 * Added `onUrlChanged` callback to platform callback handler. ## 1.4.0 * Added `loadFile` and `loadHtml` interface methods. ## 1.3.0 * Added `loadRequest` method to platform interface. ## 1.2.0 * Added `runJavascript` and `runJavascriptReturningResult` interface methods to supersede `evaluateJavascript`. ## 1.1.0 * Add `zoomEnabled` functionality to `WebSettings`. ## 1.0.0 * Extracted platform interface from `webview_flutter`.
plugins/packages/webview_flutter/webview_flutter_platform_interface/CHANGELOG.md/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter_platform_interface/CHANGELOG.md", "repo_id": "plugins", "token_count": 858 }
1,338
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /// Possible error type categorizations used by [WebResourceError]. enum WebResourceErrorType { /// User authentication failed on server. authentication, /// Malformed URL. badUrl, /// Failed to connect to the server. connect, /// Failed to perform SSL handshake. failedSslHandshake, /// Generic file error. file, /// File not found. fileNotFound, /// Server or proxy hostname lookup failed. hostLookup, /// Failed to read or write to the server. io, /// User authentication failed on proxy. proxyAuthentication, /// Too many redirects. redirectLoop, /// Connection timed out. timeout, /// Too many requests during this load. tooManyRequests, /// Generic error. unknown, /// Resource load was canceled by Safe Browsing. unsafeResource, /// Unsupported authentication scheme (not basic or digest). unsupportedAuthScheme, /// Unsupported URI scheme. unsupportedScheme, /// The web content process was terminated. webContentProcessTerminated, /// The web view was invalidated. webViewInvalidated, /// A JavaScript exception occurred. javaScriptExceptionOccurred, /// The result of JavaScript execution could not be returned. javaScriptResultTypeIsUnsupported, }
plugins/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/types/web_resource_error_type.dart/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/types/web_resource_error_type.dart", "repo_id": "plugins", "token_count": 370 }
1,339
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/painting.dart'; import '../platform_webview_controller.dart'; /// Object specifying creation parameters for creating a [WebViewWidgetDelegate]. /// /// Platform specific implementations can add additional fields by extending /// this class. /// /// {@tool sample} /// This example demonstrates how to extend the [PlatformWebViewWidgetCreationParams] to /// provide additional platform specific parameters. /// /// When extending [PlatformWebViewWidgetCreationParams] additional parameters /// should always accept `null` or have a default value to prevent breaking /// changes. /// /// ```dart /// class AndroidWebViewWidgetCreationParams /// extends PlatformWebViewWidgetCreationParams { /// AndroidWebViewWidgetCreationParams({ /// super.key, /// super.layoutDirection, /// super.gestureRecognizers, /// this.platformSpecificFieldExample, /// }); /// /// WKWebViewWidgetCreationParams.fromPlatformWebViewWidgetCreationParams( /// PlatformWebViewWidgetCreationParams params, { /// Object? platformSpecificFieldExample, /// }) : this( /// key: params.key, /// layoutDirection: params.layoutDirection, /// gestureRecognizers: params.gestureRecognizers, /// platformSpecificFieldExample: platformSpecificFieldExample, /// ); /// /// final Object? platformSpecificFieldExample; /// } /// ``` /// {@end-tool} @immutable class PlatformWebViewWidgetCreationParams { /// Used by the platform implementation to create a new [PlatformWebViewWidget]. const PlatformWebViewWidgetCreationParams({ this.key, required this.controller, this.layoutDirection = TextDirection.ltr, this.gestureRecognizers = const <Factory<OneSequenceGestureRecognizer>>{}, }); /// Controls how one widget replaces another widget in the tree. /// /// See also: /// /// * The discussions at [Key] and [GlobalKey]. final Key? key; /// The [PlatformWebViewController] that allows controlling the native web /// view. final PlatformWebViewController controller; /// The layout direction to use for the embedded WebView. final TextDirection layoutDirection; /// The `gestureRecognizers` specifies which gestures should be consumed by the /// web view. /// /// It is possible for other gesture recognizers to be competing with the web /// view on pointer events, e.g if the web view is inside a [ListView] the /// [ListView] will want to handle vertical drags. The web view will claim /// gestures that are recognized by any of the recognizers on this list. /// /// When `gestureRecognizers` is empty (default), the web view will only handle /// pointer events for gestures that were not claimed by any other gesture /// recognizer. final Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizers; }
plugins/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/platform_webview_widget_creation_params.dart/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/platform_webview_widget_creation_params.dart", "repo_id": "plugins", "token_count": 889 }
1,340
// 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:mockito/mockito.dart'; import 'package:plugin_platform_interface/plugin_platform_interface.dart'; import 'package:webview_flutter_platform_interface/webview_flutter_platform_interface.dart'; import 'webview_platform_test.mocks.dart'; void main() { setUp(() { WebViewPlatform.instance = MockWebViewPlatformWithMixin(); }); test('Cannot be implemented with `implements`', () { final MockWebViewControllerDelegate controller = MockWebViewControllerDelegate(); final PlatformWebViewWidgetCreationParams params = PlatformWebViewWidgetCreationParams(controller: controller); when(WebViewPlatform.instance!.createPlatformWebViewWidget(params)) .thenReturn(ImplementsWebViewWidgetDelegate()); expect(() { PlatformWebViewWidget(params); // In versions of `package:plugin_platform_interface` prior to fixing // https://github.com/flutter/flutter/issues/109339, an attempt to // implement a platform interface using `implements` would sometimes throw // a `NoSuchMethodError` and other times throw an `AssertionError`. After // the issue is fixed, an `AssertionError` will always be thrown. For the // purpose of this test, we don't really care what exception is thrown, so // just allow any exception. }, throwsA(anything)); }); test('Can be extended', () { final MockWebViewControllerDelegate controller = MockWebViewControllerDelegate(); final PlatformWebViewWidgetCreationParams params = PlatformWebViewWidgetCreationParams(controller: controller); when(WebViewPlatform.instance!.createPlatformWebViewWidget(params)) .thenReturn(ExtendsWebViewWidgetDelegate(params)); expect(PlatformWebViewWidget(params), isNotNull); }); test('Can be mocked with `implements`', () { final MockWebViewControllerDelegate controller = MockWebViewControllerDelegate(); final PlatformWebViewWidgetCreationParams params = PlatformWebViewWidgetCreationParams(controller: controller); when(WebViewPlatform.instance!.createPlatformWebViewWidget(params)) .thenReturn(MockWebViewWidgetDelegate()); expect(PlatformWebViewWidget(params), isNotNull); }); } class MockWebViewPlatformWithMixin extends MockWebViewPlatform with // ignore: prefer_mixin MockPlatformInterfaceMixin {} class ImplementsWebViewWidgetDelegate implements PlatformWebViewWidget { @override dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); } class MockWebViewWidgetDelegate extends Mock with // ignore: prefer_mixin MockPlatformInterfaceMixin implements PlatformWebViewWidget {} class ExtendsWebViewWidgetDelegate extends PlatformWebViewWidget { ExtendsWebViewWidgetDelegate(PlatformWebViewWidgetCreationParams params) : super.implementation(params); @override Widget build(BuildContext context) { throw UnimplementedError( 'build is not implemented for ExtendedWebViewWidgetDelegate.'); } } class MockWebViewControllerDelegate extends Mock with // ignore: prefer_mixin MockPlatformInterfaceMixin implements PlatformWebViewController {}
plugins/packages/webview_flutter/webview_flutter_platform_interface/test/platform_webview_widget_test.dart/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter_platform_interface/test/platform_webview_widget_test.dart", "repo_id": "plugins", "token_count": 1103 }
1,341
name: webview_flutter_web description: A Flutter plugin that provides a WebView widget on web. repository: https://github.com/flutter/plugins/tree/main/packages/webview_flutter/webview_flutter_web issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+webview%22 version: 0.2.2 environment: sdk: ">=2.14.0 <3.0.0" flutter: ">=3.0.0" flutter: plugin: implements: webview_flutter platforms: web: pluginClass: WebWebViewPlatform fileName: webview_flutter_web.dart dependencies: flutter: sdk: flutter flutter_web_plugins: sdk: flutter webview_flutter_platform_interface: ^2.0.0 dev_dependencies: build_runner: ^2.1.5 flutter_driver: sdk: flutter flutter_test: sdk: flutter mockito: ^5.3.2
plugins/packages/webview_flutter/webview_flutter_web/pubspec.yaml/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter_web/pubspec.yaml", "repo_id": "plugins", "token_count": 343 }
1,342
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @import Flutter; @import XCTest; @import webview_flutter_wkwebview; #import <OCMock/OCMock.h> @interface FWFUIDelegateHostApiTests : XCTestCase @end @implementation FWFUIDelegateHostApiTests /** * Creates a partially mocked FWFUIDelegate and adds it to instanceManager. * * @param instanceManager Instance manager to add the delegate to. * @param identifier Identifier for the delegate added to the instanceManager. * * @return A mock FWFUIDelegate. */ - (id)mockDelegateWithManager:(FWFInstanceManager *)instanceManager identifier:(long)identifier { FWFUIDelegate *delegate = [[FWFUIDelegate alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; [instanceManager addDartCreatedInstance:delegate withIdentifier:0]; return OCMPartialMock(delegate); } /** * Creates a mock FWFUIDelegateFlutterApiImpl with instanceManager. * * @param instanceManager Instance manager passed to the Flutter API. * * @return A mock FWFUIDelegateFlutterApiImpl. */ - (id)mockFlutterApiWithManager:(FWFInstanceManager *)instanceManager { FWFUIDelegateFlutterApiImpl *flutterAPI = [[FWFUIDelegateFlutterApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; return OCMPartialMock(flutterAPI); } - (void)testCreateWithIdentifier { FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; FWFUIDelegateHostApiImpl *hostAPI = [[FWFUIDelegateHostApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; FlutterError *error; [hostAPI createWithIdentifier:@0 error:&error]; FWFUIDelegate *delegate = (FWFUIDelegate *)[instanceManager instanceForIdentifier:0]; XCTAssertTrue([delegate conformsToProtocol:@protocol(WKUIDelegate)]); XCTAssertNil(error); } - (void)testOnCreateWebViewForDelegateWithIdentifier { FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; FWFUIDelegate *mockDelegate = [self mockDelegateWithManager:instanceManager identifier:0]; FWFUIDelegateFlutterApiImpl *mockFlutterAPI = [self mockFlutterApiWithManager:instanceManager]; OCMStub([mockDelegate UIDelegateAPI]).andReturn(mockFlutterAPI); WKWebView *mockWebView = OCMClassMock([WKWebView class]); [instanceManager addDartCreatedInstance:mockWebView withIdentifier:1]; WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init]; id mockConfigurationFlutterApi = OCMPartialMock(mockFlutterAPI.webViewConfigurationFlutterApi); NSNumber *__block configurationIdentifier; OCMStub([mockConfigurationFlutterApi createWithIdentifier:[OCMArg checkWithBlock:^BOOL(id value) { configurationIdentifier = value; return YES; }] completion:OCMOCK_ANY]); WKNavigationAction *mockNavigationAction = OCMClassMock([WKNavigationAction class]); OCMStub([mockNavigationAction request]) .andReturn([NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.flutter.dev"]]); WKFrameInfo *mockFrameInfo = OCMClassMock([WKFrameInfo class]); OCMStub([mockFrameInfo isMainFrame]).andReturn(YES); OCMStub([mockNavigationAction targetFrame]).andReturn(mockFrameInfo); [mockDelegate webView:mockWebView createWebViewWithConfiguration:configuration forNavigationAction:mockNavigationAction windowFeatures:OCMClassMock([WKWindowFeatures class])]; OCMVerify([mockFlutterAPI onCreateWebViewForDelegateWithIdentifier:@0 webViewIdentifier:@1 configurationIdentifier:configurationIdentifier navigationAction:[OCMArg isKindOfClass:[FWFWKNavigationActionData class]] completion:OCMOCK_ANY]); } @end
plugins/packages/webview_flutter/webview_flutter_wkwebview/example/ios/RunnerTests/FWFUIDelegateHostApiTests.m/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/example/ios/RunnerTests/FWFUIDelegateHostApiTests.m", "repo_id": "plugins", "token_count": 1640 }
1,343
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import <Flutter/Flutter.h> #import <WebKit/WebKit.h> #import "FWFGeneratedWebKitApis.h" #import "FWFInstanceManager.h" NS_ASSUME_NONNULL_BEGIN /** * Host api implementation for WKPreferences. * * Handles creating WKPreferences that intercommunicate with a paired Dart object. */ @interface FWFPreferencesHostApiImpl : NSObject <FWFWKPreferencesHostApi> - (instancetype)initWithInstanceManager:(FWFInstanceManager *)instanceManager; @end NS_ASSUME_NONNULL_END
plugins/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFPreferencesHostApi.h/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFPreferencesHostApi.h", "repo_id": "plugins", "token_count": 203 }
1,344
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:math'; // TODO(a14n): remove this import once Flutter 3.1 or later reaches stable (including flutter/flutter#106316) // ignore: unnecessary_import import 'package:flutter/painting.dart' show Color; import 'package:flutter/services.dart'; import '../common/instance_manager.dart'; import '../common/web_kit.g.dart'; import '../foundation/foundation.dart'; import '../web_kit/web_kit.dart'; import 'ui_kit.dart'; /// Host api implementation for [UIScrollView]. class UIScrollViewHostApiImpl extends UIScrollViewHostApi { /// Constructs a [UIScrollViewHostApiImpl]. UIScrollViewHostApiImpl({ this.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? NSObject.globalInstanceManager, super(binaryMessenger: binaryMessenger); /// Sends binary data across the Flutter platform barrier. /// /// If it is null, the default BinaryMessenger will be used which routes to /// the host platform. final BinaryMessenger? binaryMessenger; /// Maintains instances stored to communicate with Objective-C objects. final InstanceManager instanceManager; /// Calls [createFromWebView] with the ids of the provided object instances. Future<void> createFromWebViewForInstances( UIScrollView instance, WKWebView webView, ) { return createFromWebView( instanceManager.addDartCreatedInstance(instance), instanceManager.getIdentifier(webView)!, ); } /// Calls [getContentOffset] with the ids of the provided object instances. Future<Point<double>> getContentOffsetForInstances( UIScrollView instance, ) async { final List<double?> point = await getContentOffset( instanceManager.getIdentifier(instance)!, ); return Point<double>(point[0]!, point[1]!); } /// Calls [scrollBy] with the ids of the provided object instances. Future<void> scrollByForInstances( UIScrollView instance, Point<double> offset, ) { return scrollBy( instanceManager.getIdentifier(instance)!, offset.x, offset.y, ); } /// Calls [setContentOffset] with the ids of the provided object instances. Future<void> setContentOffsetForInstances( UIScrollView instance, Point<double> offset, ) async { return setContentOffset( instanceManager.getIdentifier(instance)!, offset.x, offset.y, ); } } /// Host api implementation for [UIView]. class UIViewHostApiImpl extends UIViewHostApi { /// Constructs a [UIViewHostApiImpl]. UIViewHostApiImpl({ this.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? NSObject.globalInstanceManager, super(binaryMessenger: binaryMessenger); /// Sends binary data across the Flutter platform barrier. /// /// If it is null, the default BinaryMessenger will be used which routes to /// the host platform. final BinaryMessenger? binaryMessenger; /// Maintains instances stored to communicate with Objective-C objects. final InstanceManager instanceManager; /// Calls [setBackgroundColor] with the ids of the provided object instances. Future<void> setBackgroundColorForInstances( UIView instance, Color? color, ) async { return setBackgroundColor( instanceManager.getIdentifier(instance)!, color?.value, ); } /// Calls [setOpaque] with the ids of the provided object instances. Future<void> setOpaqueForInstances( UIView instance, bool opaque, ) async { return setOpaque(instanceManager.getIdentifier(instance)!, opaque); } }
plugins/packages/webview_flutter/webview_flutter_wkwebview/lib/src/ui_kit/ui_kit_api_impls.dart/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/lib/src/ui_kit/ui_kit_api_impls.dart", "repo_id": "plugins", "token_count": 1209 }
1,345
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Autogenerated from Pigeon (v4.2.13), do not edit directly. // See also: https://pub.dev/packages/pigeon // ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, unnecessary_import // ignore_for_file: avoid_relative_lib_imports import 'dart:async'; import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:webview_flutter_wkwebview/src/common/web_kit.g.dart'; class _TestWKWebsiteDataStoreHostApiCodec extends StandardMessageCodec { const _TestWKWebsiteDataStoreHostApiCodec(); @override void writeValue(WriteBuffer buffer, Object? value) { if (value is WKWebsiteDataTypeEnumData) { buffer.putUint8(128); writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); } } @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: return WKWebsiteDataTypeEnumData.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } } } /// Mirror of WKWebsiteDataStore. /// /// See https://developer.apple.com/documentation/webkit/wkwebsitedatastore?language=objc. abstract class TestWKWebsiteDataStoreHostApi { static const MessageCodec<Object?> codec = _TestWKWebsiteDataStoreHostApiCodec(); void createFromWebViewConfiguration( int identifier, int configurationIdentifier); void createDefaultDataStore(int identifier); Future<bool> removeDataOfTypes( int identifier, List<WKWebsiteDataTypeEnumData?> dataTypes, double modificationTimeInSecondsSinceEpoch); static void setup(TestWKWebsiteDataStoreHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.WKWebsiteDataStoreHostApi.createFromWebViewConfiguration', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.WKWebsiteDataStoreHostApi.createFromWebViewConfiguration was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.WKWebsiteDataStoreHostApi.createFromWebViewConfiguration was null, expected non-null int.'); final int? arg_configurationIdentifier = (args[1] as int?); assert(arg_configurationIdentifier != null, 'Argument for dev.flutter.pigeon.WKWebsiteDataStoreHostApi.createFromWebViewConfiguration was null, expected non-null int.'); api.createFromWebViewConfiguration( arg_identifier!, arg_configurationIdentifier!); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.WKWebsiteDataStoreHostApi.createDefaultDataStore', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.WKWebsiteDataStoreHostApi.createDefaultDataStore was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.WKWebsiteDataStoreHostApi.createDefaultDataStore was null, expected non-null int.'); api.createDefaultDataStore(arg_identifier!); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.WKWebsiteDataStoreHostApi.removeDataOfTypes', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.WKWebsiteDataStoreHostApi.removeDataOfTypes was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.WKWebsiteDataStoreHostApi.removeDataOfTypes was null, expected non-null int.'); final List<WKWebsiteDataTypeEnumData?>? arg_dataTypes = (args[1] as List<Object?>?)?.cast<WKWebsiteDataTypeEnumData?>(); assert(arg_dataTypes != null, 'Argument for dev.flutter.pigeon.WKWebsiteDataStoreHostApi.removeDataOfTypes was null, expected non-null List<WKWebsiteDataTypeEnumData?>.'); final double? arg_modificationTimeInSecondsSinceEpoch = (args[2] as double?); assert(arg_modificationTimeInSecondsSinceEpoch != null, 'Argument for dev.flutter.pigeon.WKWebsiteDataStoreHostApi.removeDataOfTypes was null, expected non-null double.'); final bool output = await api.removeDataOfTypes(arg_identifier!, arg_dataTypes!, arg_modificationTimeInSecondsSinceEpoch!); return <Object?>[output]; }); } } } } /// Mirror of UIView. /// /// See https://developer.apple.com/documentation/uikit/uiview?language=objc. abstract class TestUIViewHostApi { static const MessageCodec<Object?> codec = StandardMessageCodec(); void setBackgroundColor(int identifier, int? value); void setOpaque(int identifier, bool opaque); static void setup(TestUIViewHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.UIViewHostApi.setBackgroundColor', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.UIViewHostApi.setBackgroundColor was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.UIViewHostApi.setBackgroundColor was null, expected non-null int.'); final int? arg_value = (args[1] as int?); api.setBackgroundColor(arg_identifier!, arg_value); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.UIViewHostApi.setOpaque', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.UIViewHostApi.setOpaque was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.UIViewHostApi.setOpaque was null, expected non-null int.'); final bool? arg_opaque = (args[1] as bool?); assert(arg_opaque != null, 'Argument for dev.flutter.pigeon.UIViewHostApi.setOpaque was null, expected non-null bool.'); api.setOpaque(arg_identifier!, arg_opaque!); return <Object?>[]; }); } } } } /// Mirror of UIScrollView. /// /// See https://developer.apple.com/documentation/uikit/uiscrollview?language=objc. abstract class TestUIScrollViewHostApi { static const MessageCodec<Object?> codec = StandardMessageCodec(); void createFromWebView(int identifier, int webViewIdentifier); List<double?> getContentOffset(int identifier); void scrollBy(int identifier, double x, double y); void setContentOffset(int identifier, double x, double y); static void setup(TestUIScrollViewHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.UIScrollViewHostApi.createFromWebView', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.UIScrollViewHostApi.createFromWebView was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.UIScrollViewHostApi.createFromWebView was null, expected non-null int.'); final int? arg_webViewIdentifier = (args[1] as int?); assert(arg_webViewIdentifier != null, 'Argument for dev.flutter.pigeon.UIScrollViewHostApi.createFromWebView was null, expected non-null int.'); api.createFromWebView(arg_identifier!, arg_webViewIdentifier!); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.UIScrollViewHostApi.getContentOffset', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.UIScrollViewHostApi.getContentOffset was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.UIScrollViewHostApi.getContentOffset was null, expected non-null int.'); final List<double?> output = api.getContentOffset(arg_identifier!); return <Object?>[output]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.UIScrollViewHostApi.scrollBy', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.UIScrollViewHostApi.scrollBy was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.UIScrollViewHostApi.scrollBy was null, expected non-null int.'); final double? arg_x = (args[1] as double?); assert(arg_x != null, 'Argument for dev.flutter.pigeon.UIScrollViewHostApi.scrollBy was null, expected non-null double.'); final double? arg_y = (args[2] as double?); assert(arg_y != null, 'Argument for dev.flutter.pigeon.UIScrollViewHostApi.scrollBy was null, expected non-null double.'); api.scrollBy(arg_identifier!, arg_x!, arg_y!); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.UIScrollViewHostApi.setContentOffset', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.UIScrollViewHostApi.setContentOffset was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.UIScrollViewHostApi.setContentOffset was null, expected non-null int.'); final double? arg_x = (args[1] as double?); assert(arg_x != null, 'Argument for dev.flutter.pigeon.UIScrollViewHostApi.setContentOffset was null, expected non-null double.'); final double? arg_y = (args[2] as double?); assert(arg_y != null, 'Argument for dev.flutter.pigeon.UIScrollViewHostApi.setContentOffset was null, expected non-null double.'); api.setContentOffset(arg_identifier!, arg_x!, arg_y!); return <Object?>[]; }); } } } } class _TestWKWebViewConfigurationHostApiCodec extends StandardMessageCodec { const _TestWKWebViewConfigurationHostApiCodec(); @override void writeValue(WriteBuffer buffer, Object? value) { if (value is WKAudiovisualMediaTypeEnumData) { buffer.putUint8(128); writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); } } @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: return WKAudiovisualMediaTypeEnumData.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } } } /// Mirror of WKWebViewConfiguration. /// /// See https://developer.apple.com/documentation/webkit/wkwebviewconfiguration?language=objc. abstract class TestWKWebViewConfigurationHostApi { static const MessageCodec<Object?> codec = _TestWKWebViewConfigurationHostApiCodec(); void create(int identifier); void createFromWebView(int identifier, int webViewIdentifier); void setAllowsInlineMediaPlayback(int identifier, bool allow); void setMediaTypesRequiringUserActionForPlayback( int identifier, List<WKAudiovisualMediaTypeEnumData?> types); static void setup(TestWKWebViewConfigurationHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.WKWebViewConfigurationHostApi.create', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.WKWebViewConfigurationHostApi.create was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.WKWebViewConfigurationHostApi.create was null, expected non-null int.'); api.create(arg_identifier!); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.WKWebViewConfigurationHostApi.createFromWebView', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.WKWebViewConfigurationHostApi.createFromWebView was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.WKWebViewConfigurationHostApi.createFromWebView was null, expected non-null int.'); final int? arg_webViewIdentifier = (args[1] as int?); assert(arg_webViewIdentifier != null, 'Argument for dev.flutter.pigeon.WKWebViewConfigurationHostApi.createFromWebView was null, expected non-null int.'); api.createFromWebView(arg_identifier!, arg_webViewIdentifier!); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.WKWebViewConfigurationHostApi.setAllowsInlineMediaPlayback', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.WKWebViewConfigurationHostApi.setAllowsInlineMediaPlayback was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.WKWebViewConfigurationHostApi.setAllowsInlineMediaPlayback was null, expected non-null int.'); final bool? arg_allow = (args[1] as bool?); assert(arg_allow != null, 'Argument for dev.flutter.pigeon.WKWebViewConfigurationHostApi.setAllowsInlineMediaPlayback was null, expected non-null bool.'); api.setAllowsInlineMediaPlayback(arg_identifier!, arg_allow!); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.WKWebViewConfigurationHostApi.setMediaTypesRequiringUserActionForPlayback', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.WKWebViewConfigurationHostApi.setMediaTypesRequiringUserActionForPlayback was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.WKWebViewConfigurationHostApi.setMediaTypesRequiringUserActionForPlayback was null, expected non-null int.'); final List<WKAudiovisualMediaTypeEnumData?>? arg_types = (args[1] as List<Object?>?) ?.cast<WKAudiovisualMediaTypeEnumData?>(); assert(arg_types != null, 'Argument for dev.flutter.pigeon.WKWebViewConfigurationHostApi.setMediaTypesRequiringUserActionForPlayback was null, expected non-null List<WKAudiovisualMediaTypeEnumData?>.'); api.setMediaTypesRequiringUserActionForPlayback( arg_identifier!, arg_types!); return <Object?>[]; }); } } } } class _TestWKUserContentControllerHostApiCodec extends StandardMessageCodec { const _TestWKUserContentControllerHostApiCodec(); @override void writeValue(WriteBuffer buffer, Object? value) { if (value is WKUserScriptData) { buffer.putUint8(128); writeValue(buffer, value.encode()); } else if (value is WKUserScriptInjectionTimeEnumData) { buffer.putUint8(129); writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); } } @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: return WKUserScriptData.decode(readValue(buffer)!); case 129: return WKUserScriptInjectionTimeEnumData.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } } } /// Mirror of WKUserContentController. /// /// See https://developer.apple.com/documentation/webkit/wkusercontentcontroller?language=objc. abstract class TestWKUserContentControllerHostApi { static const MessageCodec<Object?> codec = _TestWKUserContentControllerHostApiCodec(); void createFromWebViewConfiguration( int identifier, int configurationIdentifier); void addScriptMessageHandler( int identifier, int handlerIdentifier, String name); void removeScriptMessageHandler(int identifier, String name); void removeAllScriptMessageHandlers(int identifier); void addUserScript(int identifier, WKUserScriptData userScript); void removeAllUserScripts(int identifier); static void setup(TestWKUserContentControllerHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.WKUserContentControllerHostApi.createFromWebViewConfiguration', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.WKUserContentControllerHostApi.createFromWebViewConfiguration was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.WKUserContentControllerHostApi.createFromWebViewConfiguration was null, expected non-null int.'); final int? arg_configurationIdentifier = (args[1] as int?); assert(arg_configurationIdentifier != null, 'Argument for dev.flutter.pigeon.WKUserContentControllerHostApi.createFromWebViewConfiguration was null, expected non-null int.'); api.createFromWebViewConfiguration( arg_identifier!, arg_configurationIdentifier!); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.WKUserContentControllerHostApi.addScriptMessageHandler', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.WKUserContentControllerHostApi.addScriptMessageHandler was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.WKUserContentControllerHostApi.addScriptMessageHandler was null, expected non-null int.'); final int? arg_handlerIdentifier = (args[1] as int?); assert(arg_handlerIdentifier != null, 'Argument for dev.flutter.pigeon.WKUserContentControllerHostApi.addScriptMessageHandler was null, expected non-null int.'); final String? arg_name = (args[2] as String?); assert(arg_name != null, 'Argument for dev.flutter.pigeon.WKUserContentControllerHostApi.addScriptMessageHandler was null, expected non-null String.'); api.addScriptMessageHandler( arg_identifier!, arg_handlerIdentifier!, arg_name!); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.WKUserContentControllerHostApi.removeScriptMessageHandler', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.WKUserContentControllerHostApi.removeScriptMessageHandler was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.WKUserContentControllerHostApi.removeScriptMessageHandler was null, expected non-null int.'); final String? arg_name = (args[1] as String?); assert(arg_name != null, 'Argument for dev.flutter.pigeon.WKUserContentControllerHostApi.removeScriptMessageHandler was null, expected non-null String.'); api.removeScriptMessageHandler(arg_identifier!, arg_name!); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.WKUserContentControllerHostApi.removeAllScriptMessageHandlers', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.WKUserContentControllerHostApi.removeAllScriptMessageHandlers was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.WKUserContentControllerHostApi.removeAllScriptMessageHandlers was null, expected non-null int.'); api.removeAllScriptMessageHandlers(arg_identifier!); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.WKUserContentControllerHostApi.addUserScript', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.WKUserContentControllerHostApi.addUserScript was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.WKUserContentControllerHostApi.addUserScript was null, expected non-null int.'); final WKUserScriptData? arg_userScript = (args[1] as WKUserScriptData?); assert(arg_userScript != null, 'Argument for dev.flutter.pigeon.WKUserContentControllerHostApi.addUserScript was null, expected non-null WKUserScriptData.'); api.addUserScript(arg_identifier!, arg_userScript!); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.WKUserContentControllerHostApi.removeAllUserScripts', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.WKUserContentControllerHostApi.removeAllUserScripts was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.WKUserContentControllerHostApi.removeAllUserScripts was null, expected non-null int.'); api.removeAllUserScripts(arg_identifier!); return <Object?>[]; }); } } } } /// Mirror of WKUserPreferences. /// /// See https://developer.apple.com/documentation/webkit/wkpreferences?language=objc. abstract class TestWKPreferencesHostApi { static const MessageCodec<Object?> codec = StandardMessageCodec(); void createFromWebViewConfiguration( int identifier, int configurationIdentifier); void setJavaScriptEnabled(int identifier, bool enabled); static void setup(TestWKPreferencesHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.WKPreferencesHostApi.createFromWebViewConfiguration', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.WKPreferencesHostApi.createFromWebViewConfiguration was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.WKPreferencesHostApi.createFromWebViewConfiguration was null, expected non-null int.'); final int? arg_configurationIdentifier = (args[1] as int?); assert(arg_configurationIdentifier != null, 'Argument for dev.flutter.pigeon.WKPreferencesHostApi.createFromWebViewConfiguration was null, expected non-null int.'); api.createFromWebViewConfiguration( arg_identifier!, arg_configurationIdentifier!); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.WKPreferencesHostApi.setJavaScriptEnabled', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.WKPreferencesHostApi.setJavaScriptEnabled was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.WKPreferencesHostApi.setJavaScriptEnabled was null, expected non-null int.'); final bool? arg_enabled = (args[1] as bool?); assert(arg_enabled != null, 'Argument for dev.flutter.pigeon.WKPreferencesHostApi.setJavaScriptEnabled was null, expected non-null bool.'); api.setJavaScriptEnabled(arg_identifier!, arg_enabled!); return <Object?>[]; }); } } } } /// Mirror of WKScriptMessageHandler. /// /// See https://developer.apple.com/documentation/webkit/wkscriptmessagehandler?language=objc. abstract class TestWKScriptMessageHandlerHostApi { static const MessageCodec<Object?> codec = StandardMessageCodec(); void create(int identifier); static void setup(TestWKScriptMessageHandlerHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.WKScriptMessageHandlerHostApi.create', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.WKScriptMessageHandlerHostApi.create was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.WKScriptMessageHandlerHostApi.create was null, expected non-null int.'); api.create(arg_identifier!); return <Object?>[]; }); } } } } /// Mirror of WKNavigationDelegate. /// /// See https://developer.apple.com/documentation/webkit/wknavigationdelegate?language=objc. abstract class TestWKNavigationDelegateHostApi { static const MessageCodec<Object?> codec = StandardMessageCodec(); void create(int identifier); static void setup(TestWKNavigationDelegateHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.WKNavigationDelegateHostApi.create', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.WKNavigationDelegateHostApi.create was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.WKNavigationDelegateHostApi.create was null, expected non-null int.'); api.create(arg_identifier!); return <Object?>[]; }); } } } } class _TestNSObjectHostApiCodec extends StandardMessageCodec { const _TestNSObjectHostApiCodec(); @override void writeValue(WriteBuffer buffer, Object? value) { if (value is NSKeyValueObservingOptionsEnumData) { buffer.putUint8(128); writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); } } @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: return NSKeyValueObservingOptionsEnumData.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } } } /// Mirror of NSObject. /// /// See https://developer.apple.com/documentation/objectivec/nsobject. abstract class TestNSObjectHostApi { static const MessageCodec<Object?> codec = _TestNSObjectHostApiCodec(); void dispose(int identifier); void addObserver(int identifier, int observerIdentifier, String keyPath, List<NSKeyValueObservingOptionsEnumData?> options); void removeObserver(int identifier, int observerIdentifier, String keyPath); static void setup(TestNSObjectHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.NSObjectHostApi.dispose', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.NSObjectHostApi.dispose was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.NSObjectHostApi.dispose was null, expected non-null int.'); api.dispose(arg_identifier!); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.NSObjectHostApi.addObserver', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.NSObjectHostApi.addObserver was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.NSObjectHostApi.addObserver was null, expected non-null int.'); final int? arg_observerIdentifier = (args[1] as int?); assert(arg_observerIdentifier != null, 'Argument for dev.flutter.pigeon.NSObjectHostApi.addObserver was null, expected non-null int.'); final String? arg_keyPath = (args[2] as String?); assert(arg_keyPath != null, 'Argument for dev.flutter.pigeon.NSObjectHostApi.addObserver was null, expected non-null String.'); final List<NSKeyValueObservingOptionsEnumData?>? arg_options = (args[3] as List<Object?>?) ?.cast<NSKeyValueObservingOptionsEnumData?>(); assert(arg_options != null, 'Argument for dev.flutter.pigeon.NSObjectHostApi.addObserver was null, expected non-null List<NSKeyValueObservingOptionsEnumData?>.'); api.addObserver(arg_identifier!, arg_observerIdentifier!, arg_keyPath!, arg_options!); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.NSObjectHostApi.removeObserver', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.NSObjectHostApi.removeObserver was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.NSObjectHostApi.removeObserver was null, expected non-null int.'); final int? arg_observerIdentifier = (args[1] as int?); assert(arg_observerIdentifier != null, 'Argument for dev.flutter.pigeon.NSObjectHostApi.removeObserver was null, expected non-null int.'); final String? arg_keyPath = (args[2] as String?); assert(arg_keyPath != null, 'Argument for dev.flutter.pigeon.NSObjectHostApi.removeObserver was null, expected non-null String.'); api.removeObserver( arg_identifier!, arg_observerIdentifier!, arg_keyPath!); return <Object?>[]; }); } } } } class _TestWKWebViewHostApiCodec extends StandardMessageCodec { const _TestWKWebViewHostApiCodec(); @override void writeValue(WriteBuffer buffer, Object? value) { if (value is NSErrorData) { buffer.putUint8(128); writeValue(buffer, value.encode()); } else if (value is NSHttpCookieData) { buffer.putUint8(129); writeValue(buffer, value.encode()); } else if (value is NSHttpCookiePropertyKeyEnumData) { buffer.putUint8(130); writeValue(buffer, value.encode()); } else if (value is NSKeyValueChangeKeyEnumData) { buffer.putUint8(131); writeValue(buffer, value.encode()); } else if (value is NSKeyValueObservingOptionsEnumData) { buffer.putUint8(132); writeValue(buffer, value.encode()); } else if (value is NSUrlRequestData) { buffer.putUint8(133); writeValue(buffer, value.encode()); } else if (value is WKAudiovisualMediaTypeEnumData) { buffer.putUint8(134); writeValue(buffer, value.encode()); } else if (value is WKFrameInfoData) { buffer.putUint8(135); writeValue(buffer, value.encode()); } else if (value is WKNavigationActionData) { buffer.putUint8(136); writeValue(buffer, value.encode()); } else if (value is WKNavigationActionPolicyEnumData) { buffer.putUint8(137); writeValue(buffer, value.encode()); } else if (value is WKScriptMessageData) { buffer.putUint8(138); writeValue(buffer, value.encode()); } else if (value is WKUserScriptData) { buffer.putUint8(139); writeValue(buffer, value.encode()); } else if (value is WKUserScriptInjectionTimeEnumData) { buffer.putUint8(140); writeValue(buffer, value.encode()); } else if (value is WKWebsiteDataTypeEnumData) { buffer.putUint8(141); writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); } } @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: return NSErrorData.decode(readValue(buffer)!); case 129: return NSHttpCookieData.decode(readValue(buffer)!); case 130: return NSHttpCookiePropertyKeyEnumData.decode(readValue(buffer)!); case 131: return NSKeyValueChangeKeyEnumData.decode(readValue(buffer)!); case 132: return NSKeyValueObservingOptionsEnumData.decode(readValue(buffer)!); case 133: return NSUrlRequestData.decode(readValue(buffer)!); case 134: return WKAudiovisualMediaTypeEnumData.decode(readValue(buffer)!); case 135: return WKFrameInfoData.decode(readValue(buffer)!); case 136: return WKNavigationActionData.decode(readValue(buffer)!); case 137: return WKNavigationActionPolicyEnumData.decode(readValue(buffer)!); case 138: return WKScriptMessageData.decode(readValue(buffer)!); case 139: return WKUserScriptData.decode(readValue(buffer)!); case 140: return WKUserScriptInjectionTimeEnumData.decode(readValue(buffer)!); case 141: return WKWebsiteDataTypeEnumData.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } } } /// Mirror of WKWebView. /// /// See https://developer.apple.com/documentation/webkit/wkwebview?language=objc. abstract class TestWKWebViewHostApi { static const MessageCodec<Object?> codec = _TestWKWebViewHostApiCodec(); void create(int identifier, int configurationIdentifier); void setUIDelegate(int identifier, int? uiDelegateIdentifier); void setNavigationDelegate(int identifier, int? navigationDelegateIdentifier); String? getUrl(int identifier); double getEstimatedProgress(int identifier); void loadRequest(int identifier, NSUrlRequestData request); void loadHtmlString(int identifier, String string, String? baseUrl); void loadFileUrl(int identifier, String url, String readAccessUrl); void loadFlutterAsset(int identifier, String key); bool canGoBack(int identifier); bool canGoForward(int identifier); void goBack(int identifier); void goForward(int identifier); void reload(int identifier); String? getTitle(int identifier); void setAllowsBackForwardNavigationGestures(int identifier, bool allow); void setCustomUserAgent(int identifier, String? userAgent); Future<Object?> evaluateJavaScript(int identifier, String javaScriptString); static void setup(TestWKWebViewHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.WKWebViewHostApi.create', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.WKWebViewHostApi.create was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.WKWebViewHostApi.create was null, expected non-null int.'); final int? arg_configurationIdentifier = (args[1] as int?); assert(arg_configurationIdentifier != null, 'Argument for dev.flutter.pigeon.WKWebViewHostApi.create was null, expected non-null int.'); api.create(arg_identifier!, arg_configurationIdentifier!); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.WKWebViewHostApi.setUIDelegate', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.WKWebViewHostApi.setUIDelegate was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.WKWebViewHostApi.setUIDelegate was null, expected non-null int.'); final int? arg_uiDelegateIdentifier = (args[1] as int?); api.setUIDelegate(arg_identifier!, arg_uiDelegateIdentifier); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.WKWebViewHostApi.setNavigationDelegate', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.WKWebViewHostApi.setNavigationDelegate was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.WKWebViewHostApi.setNavigationDelegate was null, expected non-null int.'); final int? arg_navigationDelegateIdentifier = (args[1] as int?); api.setNavigationDelegate( arg_identifier!, arg_navigationDelegateIdentifier); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.WKWebViewHostApi.getUrl', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.WKWebViewHostApi.getUrl was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.WKWebViewHostApi.getUrl was null, expected non-null int.'); final String? output = api.getUrl(arg_identifier!); return <Object?>[output]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.WKWebViewHostApi.getEstimatedProgress', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.WKWebViewHostApi.getEstimatedProgress was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.WKWebViewHostApi.getEstimatedProgress was null, expected non-null int.'); final double output = api.getEstimatedProgress(arg_identifier!); return <Object?>[output]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.WKWebViewHostApi.loadRequest', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.WKWebViewHostApi.loadRequest was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.WKWebViewHostApi.loadRequest was null, expected non-null int.'); final NSUrlRequestData? arg_request = (args[1] as NSUrlRequestData?); assert(arg_request != null, 'Argument for dev.flutter.pigeon.WKWebViewHostApi.loadRequest was null, expected non-null NSUrlRequestData.'); api.loadRequest(arg_identifier!, arg_request!); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.WKWebViewHostApi.loadHtmlString', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.WKWebViewHostApi.loadHtmlString was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.WKWebViewHostApi.loadHtmlString was null, expected non-null int.'); final String? arg_string = (args[1] as String?); assert(arg_string != null, 'Argument for dev.flutter.pigeon.WKWebViewHostApi.loadHtmlString was null, expected non-null String.'); final String? arg_baseUrl = (args[2] as String?); api.loadHtmlString(arg_identifier!, arg_string!, arg_baseUrl); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.WKWebViewHostApi.loadFileUrl', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.WKWebViewHostApi.loadFileUrl was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.WKWebViewHostApi.loadFileUrl was null, expected non-null int.'); final String? arg_url = (args[1] as String?); assert(arg_url != null, 'Argument for dev.flutter.pigeon.WKWebViewHostApi.loadFileUrl was null, expected non-null String.'); final String? arg_readAccessUrl = (args[2] as String?); assert(arg_readAccessUrl != null, 'Argument for dev.flutter.pigeon.WKWebViewHostApi.loadFileUrl was null, expected non-null String.'); api.loadFileUrl(arg_identifier!, arg_url!, arg_readAccessUrl!); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.WKWebViewHostApi.loadFlutterAsset', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.WKWebViewHostApi.loadFlutterAsset was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.WKWebViewHostApi.loadFlutterAsset was null, expected non-null int.'); final String? arg_key = (args[1] as String?); assert(arg_key != null, 'Argument for dev.flutter.pigeon.WKWebViewHostApi.loadFlutterAsset was null, expected non-null String.'); api.loadFlutterAsset(arg_identifier!, arg_key!); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.WKWebViewHostApi.canGoBack', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.WKWebViewHostApi.canGoBack was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.WKWebViewHostApi.canGoBack was null, expected non-null int.'); final bool output = api.canGoBack(arg_identifier!); return <Object?>[output]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.WKWebViewHostApi.canGoForward', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.WKWebViewHostApi.canGoForward was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.WKWebViewHostApi.canGoForward was null, expected non-null int.'); final bool output = api.canGoForward(arg_identifier!); return <Object?>[output]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.WKWebViewHostApi.goBack', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.WKWebViewHostApi.goBack was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.WKWebViewHostApi.goBack was null, expected non-null int.'); api.goBack(arg_identifier!); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.WKWebViewHostApi.goForward', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.WKWebViewHostApi.goForward was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.WKWebViewHostApi.goForward was null, expected non-null int.'); api.goForward(arg_identifier!); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.WKWebViewHostApi.reload', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.WKWebViewHostApi.reload was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.WKWebViewHostApi.reload was null, expected non-null int.'); api.reload(arg_identifier!); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.WKWebViewHostApi.getTitle', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.WKWebViewHostApi.getTitle was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.WKWebViewHostApi.getTitle was null, expected non-null int.'); final String? output = api.getTitle(arg_identifier!); return <Object?>[output]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.WKWebViewHostApi.setAllowsBackForwardNavigationGestures', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.WKWebViewHostApi.setAllowsBackForwardNavigationGestures was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.WKWebViewHostApi.setAllowsBackForwardNavigationGestures was null, expected non-null int.'); final bool? arg_allow = (args[1] as bool?); assert(arg_allow != null, 'Argument for dev.flutter.pigeon.WKWebViewHostApi.setAllowsBackForwardNavigationGestures was null, expected non-null bool.'); api.setAllowsBackForwardNavigationGestures( arg_identifier!, arg_allow!); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.WKWebViewHostApi.setCustomUserAgent', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.WKWebViewHostApi.setCustomUserAgent was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.WKWebViewHostApi.setCustomUserAgent was null, expected non-null int.'); final String? arg_userAgent = (args[1] as String?); api.setCustomUserAgent(arg_identifier!, arg_userAgent); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.WKWebViewHostApi.evaluateJavaScript', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.WKWebViewHostApi.evaluateJavaScript was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.WKWebViewHostApi.evaluateJavaScript was null, expected non-null int.'); final String? arg_javaScriptString = (args[1] as String?); assert(arg_javaScriptString != null, 'Argument for dev.flutter.pigeon.WKWebViewHostApi.evaluateJavaScript was null, expected non-null String.'); final Object? output = await api.evaluateJavaScript( arg_identifier!, arg_javaScriptString!); return <Object?>[output]; }); } } } } /// Mirror of WKUIDelegate. /// /// See https://developer.apple.com/documentation/webkit/wkuidelegate?language=objc. abstract class TestWKUIDelegateHostApi { static const MessageCodec<Object?> codec = StandardMessageCodec(); void create(int identifier); static void setup(TestWKUIDelegateHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.WKUIDelegateHostApi.create', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.WKUIDelegateHostApi.create was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.WKUIDelegateHostApi.create was null, expected non-null int.'); api.create(arg_identifier!); return <Object?>[]; }); } } } } class _TestWKHttpCookieStoreHostApiCodec extends StandardMessageCodec { const _TestWKHttpCookieStoreHostApiCodec(); @override void writeValue(WriteBuffer buffer, Object? value) { if (value is NSHttpCookieData) { buffer.putUint8(128); writeValue(buffer, value.encode()); } else if (value is NSHttpCookiePropertyKeyEnumData) { buffer.putUint8(129); writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); } } @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: return NSHttpCookieData.decode(readValue(buffer)!); case 129: return NSHttpCookiePropertyKeyEnumData.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } } } /// Mirror of WKHttpCookieStore. /// /// See https://developer.apple.com/documentation/webkit/wkhttpcookiestore?language=objc. abstract class TestWKHttpCookieStoreHostApi { static const MessageCodec<Object?> codec = _TestWKHttpCookieStoreHostApiCodec(); void createFromWebsiteDataStore( int identifier, int websiteDataStoreIdentifier); Future<void> setCookie(int identifier, NSHttpCookieData cookie); static void setup(TestWKHttpCookieStoreHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.WKHttpCookieStoreHostApi.createFromWebsiteDataStore', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.WKHttpCookieStoreHostApi.createFromWebsiteDataStore was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.WKHttpCookieStoreHostApi.createFromWebsiteDataStore was null, expected non-null int.'); final int? arg_websiteDataStoreIdentifier = (args[1] as int?); assert(arg_websiteDataStoreIdentifier != null, 'Argument for dev.flutter.pigeon.WKHttpCookieStoreHostApi.createFromWebsiteDataStore was null, expected non-null int.'); api.createFromWebsiteDataStore( arg_identifier!, arg_websiteDataStoreIdentifier!); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.WKHttpCookieStoreHostApi.setCookie', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.WKHttpCookieStoreHostApi.setCookie was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.WKHttpCookieStoreHostApi.setCookie was null, expected non-null int.'); final NSHttpCookieData? arg_cookie = (args[1] as NSHttpCookieData?); assert(arg_cookie != null, 'Argument for dev.flutter.pigeon.WKHttpCookieStoreHostApi.setCookie was null, expected non-null NSHttpCookieData.'); await api.setCookie(arg_identifier!, arg_cookie!); return <Object?>[]; }); } } } }
plugins/packages/webview_flutter/webview_flutter_wkwebview/test/src/common/test_web_kit.g.dart/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/test/src/common/test_web_kit.g.dart", "repo_id": "plugins", "token_count": 27552 }
1,346
# Plugins that deliberately use their own analysis_options.yaml. # # This only exists to allow incrementally adopting new analysis options in # cases where a new option can't be applied to the entire repository at # once. Do not add anything to this file without an issue reference and # a concrete plan for removing it relatively quickly. # # DO NOT move or delete this file without updating # https://github.com/dart-lang/sdk/blob/master/tools/bots/flutter/analyze_flutter_plugins.sh # which references this file from source, but out-of-repo. # Contact stuartmorgan or devoncarew for assistance if necessary.
plugins/script/configs/custom_analysis.yaml/0
{ "file_path": "plugins/script/configs/custom_analysis.yaml", "repo_id": "plugins", "token_count": 159 }
1,347
// 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:file/file.dart'; import 'package:platform/platform.dart'; import 'package:yaml/yaml.dart'; import 'common/core.dart'; import 'common/package_looping_command.dart'; import 'common/process_runner.dart'; import 'common/repository_package.dart'; /// A command to run Dart analysis on packages. class AnalyzeCommand extends PackageLoopingCommand { /// Creates a analysis command instance. AnalyzeCommand( Directory packagesDir, { ProcessRunner processRunner = const ProcessRunner(), Platform platform = const LocalPlatform(), }) : super(packagesDir, processRunner: processRunner, platform: platform) { argParser.addMultiOption(_customAnalysisFlag, help: 'Directories (comma separated) that are allowed to have their own ' 'analysis options.\n\n' 'Alternately, a list of one or more YAML files that contain a list ' 'of allowed directories.', defaultsTo: <String>[]); argParser.addOption(_analysisSdk, valueHelp: 'dart-sdk', help: 'An optional path to a Dart SDK; this is used to override the ' 'SDK used to provide analysis.'); } static const String _customAnalysisFlag = 'custom-analysis'; static const String _analysisSdk = 'analysis-sdk'; late String _dartBinaryPath; Set<String> _allowedCustomAnalysisDirectories = const <String>{}; @override final String name = 'analyze'; @override final String description = 'Analyzes all packages using dart analyze.\n\n' 'This command requires "dart" and "flutter" to be in your path.'; @override final bool hasLongOutput = false; /// Checks that there are no unexpected analysis_options.yaml files. bool _hasUnexpecetdAnalysisOptions(RepositoryPackage package) { final List<FileSystemEntity> files = package.directory.listSync(recursive: true); for (final FileSystemEntity file in files) { if (file.basename != 'analysis_options.yaml' && file.basename != '.analysis_options') { continue; } final bool allowed = _allowedCustomAnalysisDirectories.any( (String directory) => directory.isNotEmpty && path.isWithin( packagesDir.childDirectory(directory).path, file.path)); if (allowed) { continue; } printError( 'Found an extra analysis_options.yaml at ${file.absolute.path}.'); printError( 'If this was deliberate, pass the package to the analyze command ' 'with the --$_customAnalysisFlag flag and try again.'); return true; } return false; } @override Future<void> initializeRun() async { _allowedCustomAnalysisDirectories = getStringListArg(_customAnalysisFlag).expand<String>((String item) { if (item.endsWith('.yaml')) { final File file = packagesDir.fileSystem.file(item); final Object? yaml = loadYaml(file.readAsStringSync()); if (yaml == null) { return <String>[]; } return (yaml as YamlList).toList().cast<String>(); } return <String>[item]; }).toSet(); // Use the Dart SDK override if one was passed in. final String? dartSdk = argResults![_analysisSdk] as String?; _dartBinaryPath = dartSdk == null ? 'dart' : path.join(dartSdk, 'bin', 'dart'); } @override Future<PackageResult> runForPackage(RepositoryPackage package) async { // Analysis runs over the package and all subpackages (unless only lib/ is // being analyzed), so all of them need `flutter pub get` run before // analyzing. `example` packages can be skipped since 'flutter packages get' // automatically runs `pub get` in examples as part of handling the parent // directory. final List<RepositoryPackage> packagesToGet = <RepositoryPackage>[ package, ...await getSubpackages(package).toList(), ]; for (final RepositoryPackage packageToGet in packagesToGet) { if (packageToGet.directory.basename != 'example' || !RepositoryPackage(packageToGet.directory.parent) .pubspecFile .existsSync()) { if (!await _runPubCommand(packageToGet, 'get')) { return PackageResult.fail(<String>['Unable to get dependencies']); } } } if (_hasUnexpecetdAnalysisOptions(package)) { return PackageResult.fail(<String>['Unexpected local analysis options']); } final int exitCode = await processRunner.runAndStream( _dartBinaryPath, <String>['analyze', '--fatal-infos'], workingDir: package.directory); if (exitCode != 0) { return PackageResult.fail(); } return PackageResult.success(); } Future<bool> _runPubCommand(RepositoryPackage package, String command) async { final int exitCode = await processRunner.runAndStream( flutterCommand, <String>['pub', command], workingDir: package.directory); return exitCode == 0; } }
plugins/script/tool/lib/src/analyze_command.dart/0
{ "file_path": "plugins/script/tool/lib/src/analyze_command.dart", "repo_id": "plugins", "token_count": 1872 }
1,348
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24.0" android:viewportHeight="24.0"> <path android:fillColor="#FF000000" android:pathData="M10,20v-6h4v6h5v-8h3L12,3 2,12h3v8z" /> </vector>
samples/add_to_app/android_view/android_view/app/src/main/res/drawable/ic_home_black_24dp.xml/0
{ "file_path": "samples/add_to_app/android_view/android_view/app/src/main/res/drawable/ic_home_black_24dp.xml", "repo_id": "samples", "token_count": 146 }
1,349
// Copyright 2019 The Flutter team. 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:math'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:sensors/sensors.dart'; // This is on alternate entrypoint for this module to display Flutter UI in // a (multi-)view integration scenario. void main() { runApp(const Cell()); } class Cell extends StatefulWidget { const Cell({super.key}); @override State<StatefulWidget> createState() => _CellState(); } class _CellState extends State<Cell> with WidgetsBindingObserver { static const double gravity = 9.81; static final AccelerometerEvent defaultPosition = AccelerometerEvent(0, 0, 0); int cellNumber = 0; Random? _random; AppLifecycleState? appLifecycleState; @override void initState() { const channel = MethodChannel('dev.flutter.example/cell'); channel.setMethodCallHandler((call) async { if (call.method == 'setCellNumber') { setState(() { cellNumber = call.arguments as int; _random = Random(cellNumber); }); } }); // Keep track of what the current platform lifecycle state is. WidgetsBinding.instance.addObserver(this); super.initState(); } @override void dispose() { WidgetsBinding.instance.removeObserver(this); super.dispose(); } @override void didChangeAppLifecycleState(AppLifecycleState state) { setState(() { appLifecycleState = state; }); } // Show a random bright color. Color randomLightColor() { _random ??= Random(cellNumber); return Color.fromARGB(255, _random!.nextInt(50) + 205, _random!.nextInt(50) + 205, _random!.nextInt(50) + 205); } @override Widget build(BuildContext context) { return MaterialApp( // The Flutter cells will be noticeably different (due to background color // and the Flutter logo). The banner breaks immersion. debugShowCheckedModeBanner: false, home: Container( color: Colors.white, child: Builder( builder: (context) { return Card( // Mimic the platform Material look. margin: const EdgeInsets.symmetric(horizontal: 36, vertical: 24), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(16), ), elevation: 16, color: randomLightColor(), child: Stack( children: [ Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( // Show a number provided by the platform based on // the cell's index. cellNumber.toString(), style: Theme.of(context).textTheme.displaySmall, ), ], ), ), Positioned( left: 42, top: 0, bottom: 0, child: Opacity( opacity: 0.2, child: StreamBuilder<AccelerometerEvent>( // Don't continuously rebuild for nothing when the // cell isn't visible. stream: appLifecycleState == AppLifecycleState.resumed ? accelerometerEvents : Stream.value(defaultPosition), initialData: defaultPosition, builder: (context, snapshot) { return Transform( // Figure out the phone's orientation relative // to gravity's direction. Ignore the z vector. transform: Matrix4.rotationX( snapshot.data!.y / gravity * pi / 2) ..multiply(Matrix4.rotationY( snapshot.data!.x / gravity * pi / 2)), alignment: Alignment.center, child: const FlutterLogo(size: 72)); }, ), ), ), ], ), ); }, ), ), ); } }
samples/add_to_app/android_view/flutter_module_using_plugin/lib/cell.dart/0
{ "file_path": "samples/add_to_app/android_view/flutter_module_using_plugin/lib/cell.dart", "repo_id": "samples", "token_count": 2266 }
1,350
<?xml version="1.0" encoding="utf-8"?> <resources> <color name="colorPrimary">#6200EE</color> <color name="colorPrimaryDark">#3700B3</color> <color name="colorAccent">#03DAC5</color> </resources>
samples/add_to_app/books/android_books/app/src/main/res/values/colors.xml/0
{ "file_path": "samples/add_to_app/books/android_books/app/src/main/res/values/colors.xml", "repo_id": "samples", "token_count": 81 }
1,351
name: flutter_module_books description: A Flutter module using the Pigeon package to demonstrate integrating Flutter in a realistic scenario where the existing platform app already has business logic and middleware constraints. version: 1.0.0+1 environment: sdk: ^3.2.0 dependencies: flutter: sdk: flutter dev_dependencies: analysis_defaults: path: ../../../analysis_defaults pigeon: ">=11.0.0 <18.0.0" flutter_test: sdk: flutter flutter: uses-material-design: true # This section identifies your Flutter project as a module meant for # embedding in a native host app. These identifiers should _not_ ordinarily # be changed after generation - they are used to ensure that the tooling can # maintain consistency when adding or modifying assets and plugins. # They also do not have any bearing on your native host application's # identifiers, which may be completely independent or the same as these. module: androidX: true androidPackage: dev.flutter.example.flutter_module_books iosBundleIdentifier: dev.flutter.example.flutterModuleBooks
samples/add_to_app/books/flutter_module_books/pubspec.yaml/0
{ "file_path": "samples/add_to_app/books/flutter_module_books/pubspec.yaml", "repo_id": "samples", "token_count": 322 }
1,352
import UIKit class BookCell: UITableViewCell { @IBOutlet weak var title: UILabel! @IBOutlet weak var subtitle: UILabel! @IBOutlet weak var byLine: UILabel! @IBOutlet weak var editButton: UIButton! }
samples/add_to_app/books/ios_books/IosBooks/BookCell.swift/0
{ "file_path": "samples/add_to_app/books/ios_books/IosBooks/BookCell.swift", "repo_id": "samples", "token_count": 75 }
1,353
// Copyright 2019 The Flutter team. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package dev.flutter.example.androidfullscreen import android.os.Bundle import android.widget.Button import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import io.flutter.embedding.android.FlutterActivity class MainActivity : AppCompatActivity() { private lateinit var counterLabel: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) counterLabel = findViewById(R.id.counter_label) val button = findViewById<Button>(R.id.launch_button) button.setOnClickListener { val intent = FlutterActivity .withCachedEngine(ENGINE_ID) .build(this) startActivity(intent) } } override fun onResume() { super.onResume() val app = application as MyApplication counterLabel.text = "Current count: ${app.count}" } }
samples/add_to_app/fullscreen/android_fullscreen/app/src/main/java/dev/flutter/example/androidfullscreen/MainActivity.kt/0
{ "file_path": "samples/add_to_app/fullscreen/android_fullscreen/app/src/main/java/dev/flutter/example/androidfullscreen/MainActivity.kt", "repo_id": "samples", "token_count": 415 }
1,354
// Copyright 2019 The Flutter team. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:provider/provider.dart'; /// The entrypoint for the flutter module. void main() { // This call ensures the Flutter binding has been set up before creating the // MethodChannel-based model. WidgetsFlutterBinding.ensureInitialized(); final model = CounterModel(); runApp( ChangeNotifierProvider.value( value: model, child: const MyApp(), ), ); } /// A simple model that uses a [MethodChannel] as the source of truth for the /// state of a counter. /// /// Rather than storing app state data within the Flutter module itself (where /// the native portions of the app can't access it), this module passes messages /// back to the containing app whenever it needs to increment or retrieve the /// value of the counter. class CounterModel extends ChangeNotifier { CounterModel() { _channel.setMethodCallHandler(_handleMessage); _channel.invokeMethod<void>('requestCounter'); } final _channel = const MethodChannel('dev.flutter.example/counter'); int _count = 0; int get count => _count; void increment() { _channel.invokeMethod<void>('incrementCounter'); } Future<dynamic> _handleMessage(MethodCall call) async { if (call.method == 'reportCounter') { _count = call.arguments as int; notifyListeners(); } } } /// The "app" displayed by this module. /// /// It offers two routes, one suitable for displaying as a full screen and /// another designed to be part of a larger UI.class MyApp extends StatelessWidget { class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Module Title', theme: ThemeData.light(), routes: { '/': (context) => const FullScreenView(), '/mini': (context) => const Contents(), }, ); } } /// Wraps [Contents] in a Material [Scaffold] so it looks correct when displayed /// full-screen. class FullScreenView extends StatelessWidget { const FullScreenView({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Full-screen Flutter'), ), body: const Contents(showExit: true), ); } } /// The actual content displayed by the module. /// /// This widget displays info about the state of a counter and how much room (in /// logical pixels) it's been given. It also offers buttons to increment the /// counter and (optionally) close the Flutter view. class Contents extends StatelessWidget { final bool showExit; const Contents({this.showExit = false, super.key}); @override Widget build(BuildContext context) { final mediaInfo = MediaQuery.of(context); return SizedBox.expand( child: Stack( children: [ Positioned.fill( child: DecoratedBox( decoration: BoxDecoration( color: Theme.of(context).scaffoldBackgroundColor, ), ), ), const Positioned.fill( child: Opacity( opacity: .25, child: FittedBox( fit: BoxFit.cover, child: FlutterLogo(), ), ), ), Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( 'Window is ${mediaInfo.size.width.toStringAsFixed(1)} x ' '${mediaInfo.size.height.toStringAsFixed(1)}', style: Theme.of(context).textTheme.headlineSmall, ), const SizedBox(height: 16), Consumer<CounterModel>( builder: (context, model, child) { return Text( 'Taps: ${model.count}', style: Theme.of(context).textTheme.headlineSmall, ); }, ), const SizedBox(height: 16), Consumer<CounterModel>( builder: (context, model, child) { return ElevatedButton( onPressed: () => model.increment(), child: const Text('Tap me!'), ); }, ), if (showExit) ...[ const SizedBox(height: 16), ElevatedButton( onPressed: () => SystemNavigator.pop(animated: true), child: const Text('Exit this screen'), ), ], ], ), ), ], ), ); } }
samples/add_to_app/fullscreen/flutter_module/lib/main.dart/0
{ "file_path": "samples/add_to_app/fullscreen/flutter_module/lib/main.dart", "repo_id": "samples", "token_count": 2111 }
1,355
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>CFBundleDevelopmentRegion</key> <string>$(DEVELOPMENT_LANGUAGE)</string> <key>CFBundleExecutable</key> <string>$(EXECUTABLE_NAME)</string> <key>CFBundleIdentifier</key> <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundleName</key> <string>$(PRODUCT_NAME)</string> <key>CFBundlePackageType</key> <string>APPL</string> <key>CFBundleShortVersionString</key> <string>1.0</string> <key>CFBundleVersion</key> <string>1</string> <key>LSRequiresIPhoneOS</key> <true/> <key>UILaunchStoryboardName</key> <string>LaunchScreen</string> <key>UIMainStoryboardFile</key> <string>Main</string> <key>UIRequiredDeviceCapabilities</key> <array> <string>armv7</string> </array> <key>UISupportedInterfaceOrientations</key> <array> <string>UIInterfaceOrientationPortrait</string> <string>UIInterfaceOrientationLandscapeLeft</string> <string>UIInterfaceOrientationLandscapeRight</string> </array> <key>UISupportedInterfaceOrientations~ipad</key> <array> <string>UIInterfaceOrientationPortrait</string> <string>UIInterfaceOrientationPortraitUpsideDown</string> <string>UIInterfaceOrientationLandscapeLeft</string> <string>UIInterfaceOrientationLandscapeRight</string> </array> <key>NSBonjourServices</key> <array> <string>_dartobservatory._tcp</string> </array> <key>NSLocalNetworkUsageDescription</key> <string>Allow Flutter tools on your computer to connect and debug your application. This prompt will not appear on release builds.</string> </dict> </plist>
samples/add_to_app/fullscreen/ios_fullscreen/IOSFullScreen/Info-Debug.plist/0
{ "file_path": "samples/add_to_app/fullscreen/ios_fullscreen/IOSFullScreen/Info-Debug.plist", "repo_id": "samples", "token_count": 663 }
1,356
package dev.flutter.multipleflutters import android.app.Application import io.flutter.embedding.engine.FlutterEngineGroup /** * Application class for this app. * * This holds onto our engine group. */ class App : Application() { lateinit var engines: FlutterEngineGroup override fun onCreate() { super.onCreate() engines = FlutterEngineGroup(this) } }
samples/add_to_app/multiple_flutters/multiple_flutters_android/app/src/main/java/dev/flutter/multipleflutters/App.kt/0
{ "file_path": "samples/add_to_app/multiple_flutters/multiple_flutters_android/app/src/main/java/dev/flutter/multipleflutters/App.kt", "repo_id": "samples", "token_count": 125 }
1,357
// Copyright 2021 The Flutter team. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import UIKit /// The UIWindowSceneDelegate for the app. class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene( _ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions ) { guard let _ = (scene as? UIWindowScene) else { return } } func sceneDidDisconnect(_ scene: UIScene) { } func sceneDidBecomeActive(_ scene: UIScene) { } func sceneWillResignActive(_ scene: UIScene) { } func sceneWillEnterForeground(_ scene: UIScene) { } func sceneDidEnterBackground(_ scene: UIScene) { } }
samples/add_to_app/multiple_flutters/multiple_flutters_ios/MultipleFluttersIos/SceneDelegate.swift/0
{ "file_path": "samples/add_to_app/multiple_flutters/multiple_flutters_ios/MultipleFluttersIos/SceneDelegate.swift", "repo_id": "samples", "token_count": 254 }
1,358
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="dev.flutter.example.androidusingplugin"> <application android:name=".MyApplication" android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity" android:exported="true"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="io.flutter.embedding.android.FlutterActivity" android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density" android:hardwareAccelerated="true" android:windowSoftInputMode="adjustResize" android:exported="true" /> </application> </manifest>
samples/add_to_app/plugin/android_using_plugin/app/src/main/AndroidManifest.xml/0
{ "file_path": "samples/add_to_app/plugin/android_using_plugin/app/src/main/AndroidManifest.xml", "repo_id": "samples", "token_count": 531 }
1,359
include: package:analysis_defaults/flutter.yaml
samples/add_to_app/plugin/flutter_module_using_plugin/analysis_options.yaml/0
{ "file_path": "samples/add_to_app/plugin/flutter_module_using_plugin/analysis_options.yaml", "repo_id": "samples", "token_count": 15 }
1,360
# ios_using_prebuilt_module An example iOS application used in the Flutter add-to-app samples. For more information on how to use it, see the [README](../README.md) file located in the [/add_to_app](/add_to_app) directory of this repo. ## Getting Started For more information about Flutter, check out [flutter.dev](https://flutter.dev). For instructions on how to integrate Flutter modules into your existing applications, see Flutter's [add-to-app documentation](https://flutter.dev/docs/development/add-to-app). ## Requirements * Flutter * Android * Android Studio * iOS * Xcode * Cocoapods
samples/add_to_app/prebuilt_module/ios_using_prebuilt_module/README.md/0
{ "file_path": "samples/add_to_app/prebuilt_module/ios_using_prebuilt_module/README.md", "repo_id": "samples", "token_count": 185 }
1,361
<!-- ~ Copyright (C) 2021 The Android Open Source Project ~ ~ Licensed under the Apache License, Version 2.0 (the "License"); ~ you may not use this file except in compliance with the License. ~ You may obtain a copy of the License at ~ ~ http://www.apache.org/licenses/LICENSE-2.0 ~ ~ Unless required by applicable law or agreed to in writing, software ~ distributed under the License is distributed on an "AS IS" BASIS, ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ~ See the License for the specific language governing permissions and ~ limitations under the License. --> <!-- This layout is the first frame of the interpolation animation. --> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:id="@+id/icon_background" android:layout_width="192dp" android:layout_height="192dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.5" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:srcCompat="@drawable/android_background" /> <ImageView android:id="@+id/imageView" android:layout_width="160dp" android:layout_height="160dp" android:layout_marginBottom="6dp" android:src="@drawable/android" app:layout_constraintBottom_toBottomOf="@+id/icon_background" app:layout_constraintEnd_toEndOf="@+id/icon_background" app:layout_constraintStart_toStartOf="@+id/icon_background" app:layout_constraintTop_toTopOf="@+id/icon_background" app:srcCompat="@drawable/android" /> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="32dp" android:text="Super Splash Screen Demo" android:textSize="24dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.495" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/imageView" /> </androidx.constraintlayout.widget.ConstraintLayout>
samples/android_splash_screen/android/app/src/main/res/layout/main_activity.xml/0
{ "file_path": "samples/android_splash_screen/android/app/src/main/res/layout/main_activity.xml", "repo_id": "samples", "token_count": 917 }
1,362
// Copyright 2019 The Flutter team. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; class PageRouteBuilderDemo extends StatelessWidget { const PageRouteBuilderDemo({super.key}); static const String routeName = 'basics/page_route_builder'; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Page 1'), ), body: Center( child: ElevatedButton( child: const Text('Go!'), onPressed: () { Navigator.of(context).push<void>(_createRoute()); }, ), ), ); } } Route _createRoute() { return PageRouteBuilder<SlideTransition>( pageBuilder: (context, animation, secondaryAnimation) => _Page2(), transitionsBuilder: (context, animation, secondaryAnimation, child) { var tween = Tween<Offset>(begin: const Offset(0.0, 1.0), end: Offset.zero); var curveTween = CurveTween(curve: Curves.ease); return SlideTransition( position: animation.drive(curveTween).drive(tween), child: child, ); }, ); } class _Page2 extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Page 2'), ), body: Center( child: Text('Page 2!', style: Theme.of(context).textTheme.headlineMedium), ), ); } }
samples/animations/lib/src/basics/page_route_builder.dart/0
{ "file_path": "samples/animations/lib/src/basics/page_route_builder.dart", "repo_id": "samples", "token_count": 614 }
1,363
.dockerignore Dockerfile docker-compose.yml Makefile README.md */build/ */.dart_tool/ .git/ .github/ .gitignore */.idea/ */.packages
samples/code_sharing/server/.dockerignore/0
{ "file_path": "samples/code_sharing/server/.dockerignore", "repo_id": "samples", "token_count": 58 }
1,364
name: shared description: Common data models required by our client and server version: 1.0.0 environment: sdk: ^3.2.0 dependencies: freezed_annotation: ^2.1.0 json_annotation: ^4.7.0 dev_dependencies: build_runner: ^2.2.1 freezed: ^2.1.1 json_serializable: ^6.4.0 lints: ">=2.0.0 <4.0.0" test: ^1.16.0
samples/code_sharing/shared/pubspec.yaml/0
{ "file_path": "samples/code_sharing/shared/pubspec.yaml", "repo_id": "samples", "token_count": 144 }
1,365
import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; typedef PlatformCallback = void Function(TargetPlatform platform); class PlatformSelector extends StatefulWidget { const PlatformSelector({ super.key, required this.onChangedPlatform, }); final PlatformCallback onChangedPlatform; @override State<PlatformSelector> createState() => _PlatformSelectorState(); } class _PlatformSelectorState extends State<PlatformSelector> { static const int targetPlatformStringLength = 15; // 'TargetPlatform.'.length static String _platformToString(TargetPlatform platform) { return platform.toString().substring(targetPlatformStringLength); } final TargetPlatform originaPlatform = defaultTargetPlatform; @override Widget build(BuildContext context) { return SizedBox( width: 170.0, child: DropdownButton<TargetPlatform>( value: defaultTargetPlatform, icon: const Icon(Icons.arrow_downward), elevation: 16, onChanged: (value) { if (value == null) { return; } widget.onChangedPlatform(value); setState(() {}); }, items: TargetPlatform.values.map((platform) { return DropdownMenuItem<TargetPlatform>( value: platform, child: Row( children: <Widget>[ if (platform == originaPlatform) const Icon( Icons.home, color: Color(0xff616161), ), Text(_platformToString(platform)), ], ), ); }).toList(), ), ); } }
samples/context_menus/lib/platform_selector.dart/0
{ "file_path": "samples/context_menus/lib/platform_selector.dart", "repo_id": "samples", "token_count": 698 }
1,366
#include "../../Flutter/Flutter-Debug.xcconfig" #include "Warnings.xcconfig"
samples/context_menus/macos/Runner/Configs/Debug.xcconfig/0
{ "file_path": "samples/context_menus/macos/Runner/Configs/Debug.xcconfig", "repo_id": "samples", "token_count": 32 }
1,367
import 'package:context_menus/custom_menu_page.dart'; import 'package:context_menus/main.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Shows default buttons in a custom context menu', (tester) async { await tester.pumpWidget(const MyApp()); // Navigate to the CustomMenuPage example. await tester.dragUntilVisible( find.text(CustomMenuPage.title), find.byType(ListView), const Offset(0.0, -200.0), ); await tester.pumpAndSettle(); await tester.tap(find.text(CustomMenuPage.title)); await tester.pumpAndSettle(); // Right click on the text field to show the context menu. final TestGesture gesture = await tester.startGesture( tester.getCenter(find.byType(EditableText)), kind: PointerDeviceKind.mouse, buttons: kSecondaryMouseButton, ); await tester.pump(); await gesture.up(); await gesture.removePointer(); await tester.pumpAndSettle(); // A custom context menu is shown, and the buttons are the default ones. expect(find.byType(AdaptiveTextSelectionToolbar), findsNothing); expect(find.byType(CupertinoAdaptiveTextSelectionToolbar), findsNothing); switch (defaultTargetPlatform) { case TargetPlatform.iOS: expect( find.byType(CupertinoTextSelectionToolbarButton), findsNWidgets(2)); case TargetPlatform.macOS: expect(find.byType(CupertinoDesktopTextSelectionToolbarButton), findsNWidgets(2)); case TargetPlatform.android: case TargetPlatform.fuchsia: expect(find.byType(TextSelectionToolbarTextButton), findsNWidgets(1)); case TargetPlatform.linux: case TargetPlatform.windows: expect( find.byType(DesktopTextSelectionToolbarButton), findsNWidgets(1)); } }); }
samples/context_menus/test/custom_menu_page_test.dart/0
{ "file_path": "samples/context_menus/test/custom_menu_page_test.dart", "repo_id": "samples", "token_count": 743 }
1,368
// Copyright 2018-present the Flutter authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. enum Category { all, accessories, clothing, home, } class ProductsRepository { static const _allProducts = <Product>[ Product( category: Category.accessories, id: 0, name: 'Vagabond sack', price: 120, ), Product( category: Category.accessories, id: 1, name: 'Stella sunglasses', price: 58, ), Product( category: Category.accessories, id: 2, name: 'Whitney belt', price: 35, ), Product( category: Category.accessories, id: 3, name: 'Garden strand', price: 98, ), Product( category: Category.accessories, id: 4, name: 'Strut earrings', price: 34, ), Product( category: Category.accessories, id: 5, name: 'Varsity socks', price: 12, ), Product( category: Category.accessories, id: 6, name: 'Weave keyring', price: 16, ), Product( category: Category.accessories, id: 7, name: 'Gatsby hat', price: 40, ), Product( category: Category.accessories, id: 8, name: 'Shrug bag', price: 198, ), Product( category: Category.home, id: 9, name: 'Gilt desk trio', price: 58, ), Product( category: Category.home, id: 10, name: 'Copper wire rack', price: 18, ), Product( category: Category.home, id: 11, name: 'Soothe ceramic set', price: 28, ), Product( category: Category.home, id: 12, name: 'Hurrahs tea set', price: 34, ), Product( category: Category.home, id: 13, name: 'Blue stone mug', price: 18, ), Product( category: Category.home, id: 14, name: 'Rainwater tray', price: 27, ), Product( category: Category.home, id: 15, name: 'Chambray napkins', price: 16, ), Product( category: Category.home, id: 16, name: 'Succulent planters', price: 16, ), Product( category: Category.home, id: 17, name: 'Quartet table', price: 175, ), Product( category: Category.home, id: 18, name: 'Kitchen quattro', price: 129, ), Product( category: Category.clothing, id: 19, name: 'Clay sweater', price: 48, ), Product( category: Category.clothing, id: 20, name: 'Sea tunic', price: 45, ), Product( category: Category.clothing, id: 21, name: 'Plaster tunic', price: 38, ), Product( category: Category.clothing, id: 22, name: 'White pinstripe shirt', price: 70, ), Product( category: Category.clothing, id: 23, name: 'Chambray shirt', price: 70, ), Product( category: Category.clothing, id: 24, name: 'Seabreeze sweater', price: 60, ), Product( category: Category.clothing, id: 25, name: 'Gentry jacket', price: 178, ), Product( category: Category.clothing, id: 26, name: 'Navy trousers', price: 74, ), Product( category: Category.clothing, id: 27, name: 'Walter henley (white)', price: 38, ), Product( category: Category.clothing, id: 28, name: 'Surf and perf shirt', price: 48, ), Product( category: Category.clothing, id: 29, name: 'Ginger scarf', price: 98, ), Product( category: Category.clothing, id: 30, name: 'Ramona crossover', price: 68, ), Product( category: Category.clothing, id: 31, name: 'Chambray shirt', price: 38, ), Product( category: Category.clothing, id: 32, name: 'Classic white collar', price: 58, ), Product( category: Category.clothing, id: 33, name: 'Cerise scallop tee', price: 42, ), Product( category: Category.clothing, id: 34, name: 'Shoulder rolls tee', price: 27, ), Product( category: Category.clothing, id: 35, name: 'Grey slouch tank', price: 24, ), Product( category: Category.clothing, id: 36, name: 'Sunshirt dress', price: 58, ), Product( category: Category.clothing, id: 37, name: 'Fine lines tee', price: 58, ), ]; static List<Product> loadProducts({Category category = Category.all}) { if (category == Category.all) { return _allProducts; } else { return _allProducts.where((p) => p.category == category).toList(); } } static Product loadProduct({required int id}) { return _allProducts.firstWhere((Product p) => p.id == id); } } String getCategoryTitle(Category category) => switch (category) { Category.all => 'All', Category.accessories => 'Accessories', Category.clothing => 'Clothing', Category.home => 'Home Decorations' }; class Product { const Product({ required this.category, required this.id, required this.name, required this.price, }); final Category category; final int id; final String name; final int price; String get assetName => '$id-0.jpg'; String get assetName2X => '2.0x/$id-0.jpg'; String get assetPackage => 'shrine_images'; @override String toString() => '$name (id=$id)'; }
samples/deeplink_store_example/lib/model/products_repository.dart/0
{ "file_path": "samples/deeplink_store_example/lib/model/products_repository.dart", "repo_id": "samples", "token_count": 2739 }
1,369
#include "ephemeral/Flutter-Generated.xcconfig"
samples/deeplink_store_example/macos/Flutter/Flutter-Debug.xcconfig/0
{ "file_path": "samples/deeplink_store_example/macos/Flutter/Flutter-Debug.xcconfig", "repo_id": "samples", "token_count": 19 }
1,370
// Copyright 2019 The Flutter team. 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:built_collection/built_collection.dart'; import 'package:built_value/serializer.dart'; import 'package:built_value/standard_json_plugin.dart'; import 'model/search.dart'; import 'unsplash/api_error.dart'; import 'unsplash/current_user_collections.dart'; import 'unsplash/exif.dart'; import 'unsplash/links.dart'; import 'unsplash/location.dart'; import 'unsplash/photo.dart'; import 'unsplash/position.dart'; import 'unsplash/search_photos_response.dart'; import 'unsplash/tags.dart'; import 'unsplash/urls.dart'; import 'unsplash/user.dart'; part 'serializers.g.dart'; //add all of the built value types that require serialization @SerializersFor([Search, ApiError, Photo, SearchPhotosResponse]) final Serializers serializers = (_$serializers.toBuilder()..addPlugin(StandardJsonPlugin())).build();
samples/desktop_photo_search/fluent_ui/lib/src/serializers.dart/0
{ "file_path": "samples/desktop_photo_search/fluent_ui/lib/src/serializers.dart", "repo_id": "samples", "token_count": 322 }
1,371
// Copyright 2019 The Flutter team. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert'; import 'package:built_collection/built_collection.dart'; import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; import '../serializers.dart'; import 'photo.dart'; part 'search_photos_response.g.dart'; abstract class SearchPhotosResponse implements Built<SearchPhotosResponse, SearchPhotosResponseBuilder> { factory SearchPhotosResponse( [void Function(SearchPhotosResponseBuilder)? updates]) = _$SearchPhotosResponse; SearchPhotosResponse._(); @BuiltValueField(wireName: 'total') int? get total; @BuiltValueField(wireName: 'total_pages') int? get totalPages; @BuiltValueField(wireName: 'results') BuiltList<Photo> get results; String toJson() { return json.encode( serializers.serializeWith(SearchPhotosResponse.serializer, this)); } static SearchPhotosResponse? fromJson(String jsonString) { return serializers.deserializeWith( SearchPhotosResponse.serializer, json.decode(jsonString)); } static Serializer<SearchPhotosResponse> get serializer => _$searchPhotosResponseSerializer; }
samples/desktop_photo_search/fluent_ui/lib/src/unsplash/search_photos_response.dart/0
{ "file_path": "samples/desktop_photo_search/fluent_ui/lib/src/unsplash/search_photos_response.dart", "repo_id": "samples", "token_count": 402 }
1,372
// Copyright 2019 The Flutter team. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:logging/logging.dart'; import 'package:menubar/menubar.dart' as menubar; import 'package:provider/provider.dart'; import 'package:window_size/window_size.dart'; import 'src/model/photo_search_model.dart'; import 'src/unsplash/unsplash.dart'; import 'src/widgets/photo_search_dialog.dart'; import 'src/widgets/policy_dialog.dart'; import 'src/widgets/unsplash_notice.dart'; import 'src/widgets/unsplash_search_content.dart'; import 'unsplash_access_key.dart'; void main() { Logger.root.level = Level.ALL; Logger.root.onRecord.listen((rec) { // ignore: avoid_print print('${rec.loggerName} ${rec.level.name}: ${rec.time}: ${rec.message}'); }); if (unsplashAccessKey.isEmpty) { Logger('main').severe('Unsplash Access Key is required. ' 'Please add to `lib/unsplash_access_key.dart`.'); exit(1); } setupWindow(); runApp( ChangeNotifierProvider<PhotoSearchModel>( create: (context) => PhotoSearchModel( Unsplash(accessKey: unsplashAccessKey), ), child: const UnsplashSearchApp(), ), ); } const double windowWidth = 1024; const double windowHeight = 800; void setupWindow() { if (!kIsWeb && (Platform.isWindows || Platform.isLinux || Platform.isMacOS)) { WidgetsFlutterBinding.ensureInitialized(); setWindowMinSize(const Size(windowWidth, windowHeight)); } } class UnsplashSearchApp extends StatelessWidget { const UnsplashSearchApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Photo Search', theme: ThemeData( colorSchemeSeed: Colors.orange, ), home: const UnsplashHomePage(title: 'Photo Search'), ); } } class UnsplashHomePage extends StatelessWidget { const UnsplashHomePage({required this.title, super.key}); final String title; @override Widget build(BuildContext context) { final photoSearchModel = Provider.of<PhotoSearchModel>(context); menubar.setApplicationMenu([ menubar.NativeSubmenu(label: 'Search', children: [ menubar.NativeMenuItem( label: 'Search…', onSelected: () { showDialog<void>( context: context, builder: (context) => PhotoSearchDialog(callback: photoSearchModel.addSearch), ); }, ), if (!Platform.isMacOS) menubar.NativeMenuItem( label: 'Quit', onSelected: () { SystemNavigator.pop(); }, ), ]), menubar.NativeSubmenu(label: 'About', children: [ menubar.NativeMenuItem( label: 'About', onSelected: () { showDialog<void>( context: context, builder: (context) => const PolicyDialog(), ); }, ), ]) ]); return UnsplashNotice( child: Scaffold( appBar: AppBar( title: Text(title), ), body: photoSearchModel.entries.isNotEmpty ? const UnsplashSearchContent() : const Center( child: Text('Search for Photos using the Fab button'), ), floatingActionButton: FloatingActionButton( onPressed: () => showDialog<void>( context: context, builder: (context) => PhotoSearchDialog(callback: photoSearchModel.addSearch), ), tooltip: 'Search for a photo', child: const Icon(Icons.search), ), ), ); } }
samples/desktop_photo_search/material/lib/main.dart/0
{ "file_path": "samples/desktop_photo_search/material/lib/main.dart", "repo_id": "samples", "token_count": 1637 }
1,373
// Copyright 2019 The Flutter team. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert'; import 'package:built_collection/built_collection.dart'; import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; import '../serializers.dart'; import 'current_user_collections.dart'; import 'exif.dart'; import 'links.dart'; import 'location.dart'; import 'tags.dart'; import 'urls.dart'; import 'user.dart'; part 'photo.g.dart'; abstract class Photo implements Built<Photo, PhotoBuilder> { factory Photo([void Function(PhotoBuilder)? updates]) = _$Photo; Photo._(); @BuiltValueField(wireName: 'id') String get id; @BuiltValueField(wireName: 'created_at') String? get createdAt; @BuiltValueField(wireName: 'updated_at') String? get updatedAt; @BuiltValueField(wireName: 'width') int? get width; @BuiltValueField(wireName: 'height') int? get height; @BuiltValueField(wireName: 'color') String? get color; @BuiltValueField(wireName: 'downloads') int? get downloads; @BuiltValueField(wireName: 'likes') int? get likes; @BuiltValueField(wireName: 'liked_by_user') bool? get likedByUser; @BuiltValueField(wireName: 'description') String? get description; @BuiltValueField(wireName: 'exif') Exif? get exif; @BuiltValueField(wireName: 'location') Location? get location; @BuiltValueField(wireName: 'tags') BuiltList<Tags>? get tags; @BuiltValueField(wireName: 'current_user_collections') BuiltList<CurrentUserCollections>? get currentUserCollections; @BuiltValueField(wireName: 'urls') Urls? get urls; @BuiltValueField(wireName: 'links') Links? get links; @BuiltValueField(wireName: 'user') User? get user; String toJson() { return json.encode(serializers.serializeWith(Photo.serializer, this)); } static Photo? fromJson(String jsonString) { return serializers.deserializeWith( Photo.serializer, json.decode(jsonString)); } static Serializer<Photo> get serializer => _$photoSerializer; }
samples/desktop_photo_search/material/lib/src/unsplash/photo.dart/0
{ "file_path": "samples/desktop_photo_search/material/lib/src/unsplash/photo.dart", "repo_id": "samples", "token_count": 707 }
1,374
// Copyright 2019 The Chromium 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:math'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; /// A widget that takes two children, lays them out along [axis], and allows /// the user to resize them. /// /// The user can customize the amount of space allocated to each child by /// dragging a divider between them. /// /// [initialFirstFraction] defines how much space to give the [firstChild] /// when first building this widget. [secondChild] will take the remaining /// space. /// /// The user can drag the widget with key [dividerKey] to change /// the space allocated between [firstChild] and [secondChild]. // TODO(djshuckerow): introduce support for a minimum fraction a child // is allowed. class Split extends StatefulWidget { /// Builds a split oriented along [axis]. const Split({ super.key, required this.axis, required this.firstChild, required this.secondChild, double? initialFirstFraction, }) : initialFirstFraction = initialFirstFraction ?? 0.5; /// The main axis the children will lay out on. /// /// If [Axis.horizontal], the children will be placed in a [Row] /// and they will be horizontally resizable. /// /// If [Axis.vertical], the children will be placed in a [Column] /// and they will be vertically resizable. /// /// Cannot be null. final Axis axis; /// The child that will be laid out first along [axis]. final Widget firstChild; /// The child that will be laid out last along [axis]. final Widget secondChild; /// The fraction of the layout to allocate to [firstChild]. /// /// [secondChild] will receive a fraction of `1 - initialFirstFraction`. final double initialFirstFraction; /// The key passed to the divider between [firstChild] and [secondChild]. /// /// Visible to grab it in tests. @visibleForTesting Key get dividerKey => Key('$this dividerKey'); /// The size of the divider between [firstChild] and [secondChild] in /// logical pixels (dp, not px). static const double dividerMainAxisSize = 10; static Axis axisFor(BuildContext context, double horizontalAspectRatio) { final screenSize = MediaQuery.of(context).size; final aspectRatio = screenSize.width / screenSize.height; if (aspectRatio >= horizontalAspectRatio) { return Axis.horizontal; } return Axis.vertical; } @override State<StatefulWidget> createState() => _SplitState(); } class _SplitState extends State<Split> { late double firstFraction; double get secondFraction => 1 - firstFraction; bool get isHorizontal => widget.axis == Axis.horizontal; @override void initState() { super.initState(); firstFraction = widget.initialFirstFraction; } @override Widget build(BuildContext context) { return LayoutBuilder(builder: _buildLayout); } Widget _buildLayout(BuildContext context, BoxConstraints constraints) { final width = constraints.maxWidth; final height = constraints.maxHeight; final axisSize = isHorizontal ? width : height; final crossAxisSize = isHorizontal ? height : width; const halfDivider = Split.dividerMainAxisSize / 2.0; // Determine what fraction to give each child, including enough space to // display the divider. var firstSize = axisSize * firstFraction; var secondSize = axisSize * secondFraction; // Clamp the sizes to be sure there is enough space for the dividers. firstSize = firstSize.clamp(halfDivider, axisSize - halfDivider); secondSize = secondSize.clamp(halfDivider, axisSize - halfDivider); // Remove space from each child to place the divider in the middle. firstSize = firstSize - halfDivider; secondSize = secondSize - halfDivider; void updateSpacing(DragUpdateDetails dragDetails) { final delta = isHorizontal ? dragDetails.delta.dx : dragDetails.delta.dy; final fractionalDelta = delta / axisSize; setState(() { // Update the fraction of space consumed by the children, // being sure not to allocate any negative space. firstFraction += fractionalDelta; firstFraction = firstFraction.clamp(0.0, 1.0); }); } // TODO(https://github.com/flutter/flutter/issues/43747): use an icon. // The material icon for a drag handle is not currently available. // For now, draw an indicator that is 3 lines running in the direction // of the main axis, like a hamburger menu. // TODO(https://github.com/flutter/devtools/issues/1265): update mouse // to indicate that this is resizable. final dragIndicator = Flex( direction: isHorizontal ? Axis.vertical : Axis.horizontal, mainAxisSize: MainAxisSize.min, children: [ for (var i = 0; i < min(crossAxisSize / 6.0, 3).floor(); i++) Padding( padding: EdgeInsets.symmetric( vertical: isHorizontal ? 2.0 : 0.0, horizontal: isHorizontal ? 0.0 : 2.0, ), child: DecoratedBox( decoration: BoxDecoration( color: Theme.of(context).dividerColor, borderRadius: BorderRadius.circular(Split.dividerMainAxisSize), ), child: SizedBox( height: isHorizontal ? 2.0 : Split.dividerMainAxisSize - 2.0, width: isHorizontal ? Split.dividerMainAxisSize - 2.0 : 2.0, ), ), ), ], ); final children = [ SizedBox( width: isHorizontal ? firstSize : width, height: isHorizontal ? height : firstSize, child: widget.firstChild, ), GestureDetector( key: widget.dividerKey, behavior: HitTestBehavior.translucent, onHorizontalDragUpdate: isHorizontal ? updateSpacing : null, onVerticalDragUpdate: isHorizontal ? null : updateSpacing, // DartStartBehavior.down is needed to keep the mouse pointer stuck to // the drag bar. There still appears to be a few frame lag before the // drag action triggers which is't ideal but isn't a launch blocker. dragStartBehavior: DragStartBehavior.down, child: SizedBox( width: isHorizontal ? Split.dividerMainAxisSize : width, height: isHorizontal ? height : Split.dividerMainAxisSize, child: Center( child: dragIndicator, ), ), ), SizedBox( width: isHorizontal ? secondSize : width, height: isHorizontal ? height : secondSize, child: widget.secondChild, ), ]; return Flex(direction: widget.axis, children: children); } }
samples/desktop_photo_search/material/lib/src/widgets/split.dart/0
{ "file_path": "samples/desktop_photo_search/material/lib/src/widgets/split.dart", "repo_id": "samples", "token_count": 2391 }
1,375
// // Generated file. Do not edit. // import FlutterMacOS import Foundation import file_selector_macos import menubar import url_launcher_macos import window_size func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { FileSelectorPlugin.register(with: registry.registrar(forPlugin: "FileSelectorPlugin")) MenubarPlugin.register(with: registry.registrar(forPlugin: "MenubarPlugin")) UrlLauncherPlugin.register(with: registry.registrar(forPlugin: "UrlLauncherPlugin")) WindowSizePlugin.register(with: registry.registrar(forPlugin: "WindowSizePlugin")) }
samples/desktop_photo_search/material/macos/Flutter/GeneratedPluginRegistrant.swift/0
{ "file_path": "samples/desktop_photo_search/material/macos/Flutter/GeneratedPluginRegistrant.swift", "repo_id": "samples", "token_count": 178 }
1,376
# Master channel samples In this directory, you'll find samples that target Flutter's master channel. They may take advantage of new SDK features that haven't landed in the stable channel, and they may crash, lock up your machine, or otherwise fail to run correctly. In other words, consider everything in this directory to be an experiment. We're maintaining these samples here so that folks can see some of Flutter's upcoming features as they evolve and get a sense for how they'll eventually be used. If you'd like to run the apps, make sure to switch to the master channel first: ```bash flutter channel master flutter upgrade ``` When you're done, use this command to return to the safety of the stable channel: ```bash flutter channel stable ``` ## Want more info about the repo in general? See the [README](../README.md) in the repo's root folder.
samples/experimental/README.md/0
{ "file_path": "samples/experimental/README.md", "repo_id": "samples", "token_count": 218 }
1,377
include: package:analysis_defaults/flutter.yaml
samples/experimental/federated_plugin/federated_plugin/example/analysis_options.yaml/0
{ "file_path": "samples/experimental/federated_plugin/federated_plugin/example/analysis_options.yaml", "repo_id": "samples", "token_count": 15 }
1,378
// // Generated file. Do not edit. // import FlutterMacOS import Foundation import federated_plugin_macos func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { FederatedPluginMacosPlugin.register(with: registry.registrar(forPlugin: "FederatedPluginMacosPlugin")) }
samples/experimental/federated_plugin/federated_plugin/example/macos/Flutter/GeneratedPluginRegistrant.swift/0
{ "file_path": "samples/experimental/federated_plugin/federated_plugin/example/macos/Flutter/GeneratedPluginRegistrant.swift", "repo_id": "samples", "token_count": 87 }
1,379
# federated_plugin_macos_example To view the usage of plugin, head over to [federated_plugin/example](../../federated_plugin/example).
samples/experimental/federated_plugin/federated_plugin_macos/example/README.md/0
{ "file_path": "samples/experimental/federated_plugin/federated_plugin_macos/example/README.md", "repo_id": "samples", "token_count": 42 }
1,380
// Copyright 2020 The Flutter team. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:html' as html; import 'package:federated_plugin_platform_interface/federated_plugin_platform_interface.dart'; import 'package:flutter/services.dart'; import 'package:flutter_web_plugins/flutter_web_plugins.dart'; /// Web Implementation of [FederatedPluginInterface] to retrieve current battery /// level of device. class FederatedPlugin extends FederatedPluginInterface { final html.Navigator _navigator; /// Constructor to override the navigator object for testing purpose. FederatedPlugin({html.Navigator? navigator}) : _navigator = navigator ?? html.window.navigator; /// Method to register the plugin which sets [FederatedPlugin] to be the default /// instance of [FederatedPluginInterface]. static void registerWith(Registrar registrar) { FederatedPluginInterface.instance = FederatedPlugin(); } /// Returns the current battery level of device. /// /// If any error, it's assume that the BatteryManager API is not supported by /// browser. @override Future<int> getBatteryLevel() async { try { final battery = await _navigator.getBattery() as html.BatteryManager; // The battery level retrieved is in range of 0.0 to 1.0. return battery.level! * 100 as int; } catch (error) { throw PlatformException( code: 'STATUS_UNAVAILABLE', message: 'The plugin is not supported by the browser.', details: null, ); } } }
samples/experimental/federated_plugin/federated_plugin_web/lib/federated_plugin_web.dart/0
{ "file_path": "samples/experimental/federated_plugin/federated_plugin_web/lib/federated_plugin_web.dart", "repo_id": "samples", "token_count": 489 }
1,381
// Copyright 2021 The Flutter team. 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:context_menus/context_menus.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart' show SystemUiOverlayStyle; import 'package:linting_tool/layout/adaptive.dart'; import 'package:linting_tool/model/editing_controller.dart'; import 'package:linting_tool/model/profiles_store.dart'; import 'package:linting_tool/widgets/saved_rule_tile.dart'; import 'package:provider/provider.dart'; class RulesPage extends StatelessWidget { final int selectedProfileIndex; const RulesPage({ required this.selectedProfileIndex, super.key, }); @override Widget build(BuildContext context) { final isDesktop = isDisplayLarge(context); final isTablet = isDisplayMedium(context); final textTheme = Theme.of(context).textTheme; final startPadding = isTablet ? 60.0 : isDesktop ? 120.0 : 16.0; final endPadding = isTablet ? 60.0 : isDesktop ? 120.0 : 4.0; return Scaffold( appBar: AppBar( title: Text( context .read<ProfilesStore>() .savedProfiles[selectedProfileIndex] .name, style: textTheme.titleSmall!.copyWith( color: textTheme.bodyLarge!.color, ), ), leading: Padding( padding: const EdgeInsets.only(left: 80.0), child: TextButton.icon( onPressed: () { Navigator.pop(context); }, icon: const Icon(Icons.arrow_back_ios_new), label: const Text('Back'), ), ), leadingWidth: 160.0, toolbarHeight: 38.0, backgroundColor: Colors.white, systemOverlayStyle: SystemUiOverlayStyle.dark, ), /// ContextMenuOverlay is required to show /// right-click context menus using ContextMenuRegion. body: ContextMenuOverlay( child: Consumer<ProfilesStore>( builder: (context, profilesStore, child) { var profile = profilesStore.savedProfiles[selectedProfileIndex]; return profile.rules.isEmpty ? const Center( child: Text('There are no rules added to the profile.'), ) : Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ Expanded( child: ListView.separated( padding: EdgeInsetsDirectional.only( start: startPadding, end: endPadding, top: isDesktop ? 28 : 16, bottom: isDesktop ? kToolbarHeight : 16, ), itemCount: profile.rules.length, cacheExtent: 5, itemBuilder: (context, index) { /// Show right-click context menu to delete rule. return ContextMenuRegion( contextMenu: GenericContextMenu( buttonConfigs: [ ContextMenuButtonConfig( 'Remove rule from profile', onPressed: () { context .read<ProfilesStore>() .removeRuleFromProfile( profile, profile.rules[index]); }, ), ], ), child: SavedRuleTile( rule: profile.rules[index], ), ); }, separatorBuilder: (context, index) => const SizedBox(height: 4), ), ), Padding( padding: const EdgeInsetsDirectional.only(top: 28), child: Row( children: [ Consumer<EditingController>( builder: (context, editingController, child) { var isEditing = editingController.isEditing; return isEditing ? Column( children: [ IconButton( icon: const Icon(Icons.done), onPressed: () { editingController.isEditing = false; }, ), if (editingController .selectedRules.isNotEmpty) IconButton( icon: const Icon(Icons.delete), onPressed: () { editingController .deleteSelected( profile, profilesStore, ); }, ), ], ) : IconButton( icon: const Icon(Icons.edit), onPressed: () { editingController.isEditing = true; }, ); }, ), SizedBox( width: isTablet ? 30 : isDesktop ? 60 : 16), ], ), ), ], ); }, ), ), ); } }
samples/experimental/linting_tool/lib/pages/rules_page.dart/0
{ "file_path": "samples/experimental/linting_tool/lib/pages/rules_page.dart", "repo_id": "samples", "token_count": 4483 }
1,382
# # Generated file, do not edit. # list(APPEND FLUTTER_PLUGIN_LIST file_selector_linux url_launcher_linux window_size ) 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)
samples/experimental/linting_tool/linux/flutter/generated_plugins.cmake/0
{ "file_path": "samples/experimental/linting_tool/linux/flutter/generated_plugins.cmake", "repo_id": "samples", "token_count": 333 }
1,383
name: linting_tool description: A new Flutter project. version: 1.0.0+1 publish_to: "none" environment: sdk: ^3.2.0 dependencies: flutter: sdk: flutter adaptive_breakpoints: ^0.1.1 cupertino_icons: ^1.0.2 equatable: ^2.0.3 file_selector: ^1.0.0 flutter_markdown: ^0.6.2 google_fonts: ^6.0.0 hive: ^2.0.4 hive_flutter: ^1.1.0 http: ^1.2.1 json2yaml: ^3.0.0 json_annotation: ^4.8.1 mockito: ^5.0.13 provider: ^6.0.2 yaml: ^3.1.0 context_menus: ^1.0.1 window_size: git: url: https://github.com/google/flutter-desktop-embedding.git path: plugins/window_size dev_dependencies: analysis_defaults: path: ../../analysis_defaults flutter_test: sdk: flutter build_runner: ^2.4.6 hive_generator: ^2.0.0 json_serializable: ^6.7.1 flutter: uses-material-design: true
samples/experimental/linting_tool/pubspec.yaml/0
{ "file_path": "samples/experimental/linting_tool/pubspec.yaml", "repo_id": "samples", "token_count": 399 }
1,384
# FFIgen + JNIgen pedometer This is a demo for some of our tooling around calling platform APIs directly from dart code. This repository represents a demo of a plugin that leverages FFIgen & JNIgen. There is also an example pedometer app that uses the bindings generated from these tools. - [FFIgen](https://pub.dev/packages/ffigen) is used to generate bindings for C, Objective-C and Swift APIs. - [JNIgen](https://pub.dev/packages/jnigen) is used to generate bindings for Java and Kotlin APIs. **These tools are both experimental and are currently a work in progress.** If you find any issues or have feedback, please file it on the corresponding GitHub repositories. ## Re-generating bindings The bindings that allow the Dart code to call the platform code have already been generated in the [`\lib` folder](./lib). You can regenerate them by following the steps below: ### FFIgen Configuration of FFIgen for the [CoreMotion framework](https://developer.apple.com/documentation/coremotion) is in the [`ffigen.yaml` file](./ffigen.yaml). FFIgen currently does not support autogenerating code to handle callbacks. So, there are a few extra steps needed to appropriately handle callbacks in Objective-C. You can read more about this limitation on [dart.dev](https://dart.dev/interop/objective-c-interop#callbacks-and-multithreading-limitations). ```bash dart run ffigen --config ffigen.yaml ``` ### JNIgen Configuration of JNIgen for the [HealthConnect API](https://developer.android.com/guide/health-and-fitness/health-connect) is in the [`jnigen.yaml` file](./jnigen.yaml). 1. Build an Android APK file from the example app. Currently, JNIgen requires at least one APK build to obtain the classpaths of Android Gradle libraries. ```bash cd example && flutter build apk ``` 2. Return to the `/pedometer` directory and run `jnigen`: ```bash cd .. && dart run jnigen --config jnigen.yaml ``` ## Running the example app The example app is located in the [`/example`](./example) directory, and the following commands assume they are being run from that location. Note that step counting is only available on physical devices. ### iOS - Run `flutter run` and choose your physical device. - Allow the *pedometer* app access to step counting. ### Android - Make sure that [Google Fit](https://play.google.com/store/apps/details?id=com.google.android.apps.fitness) is installed (to ensure that steps are being counted). - Run `flutter run` and choose your physical device. - Install [Health Connect](https://play.google.com/store/apps/details?id=com.google.android.apps.healthdata) and grant access to Google Fit and the *jni_demo* app. ## Project structure * `src`: Contains the native source code, and a `CMakeLists.txt` file for building that source code into a dynamic library. * `lib`: Contains the Dart code that defines the API of the plugin and calls into the native code using `dart:ffi`. * platform folders (`ios` etc.): Contain the build files for building and bundling the native code library with the platform application. * `example`: Contains the native source code for building that source code into a dynamic library.
samples/experimental/pedometer/README.md/0
{ "file_path": "samples/experimental/pedometer/README.md", "repo_id": "samples", "token_count": 927 }
1,385
/* * Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file * for details. All rights reserved. Use of this source code is governed by a * BSD-style license that can be found in the LICENSE file. */ #ifndef RUNTIME_INCLUDE_DART_API_H_ #define RUNTIME_INCLUDE_DART_API_H_ /** \mainpage Dart Embedding API Reference * * This reference describes the Dart Embedding API, which is used to embed the * Dart Virtual Machine within C/C++ applications. * * This reference is generated from the header include/dart_api.h. */ /* __STDC_FORMAT_MACROS has to be defined before including <inttypes.h> to * enable platform independent printf format specifiers. */ #ifndef __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS #endif #include <assert.h> #include <inttypes.h> #include <stdbool.h> #ifdef __cplusplus #define DART_EXTERN_C extern "C" #else #define DART_EXTERN_C extern #endif #if defined(__CYGWIN__) #error Tool chain and platform not supported. #elif defined(_WIN32) #if defined(DART_SHARED_LIB) #define DART_EXPORT DART_EXTERN_C __declspec(dllexport) #else #define DART_EXPORT DART_EXTERN_C #endif #else #if __GNUC__ >= 4 #if defined(DART_SHARED_LIB) #define DART_EXPORT \ DART_EXTERN_C __attribute__((visibility("default"))) __attribute((used)) #else #define DART_EXPORT DART_EXTERN_C #endif #else #error Tool chain not supported. #endif #endif #if __GNUC__ #define DART_WARN_UNUSED_RESULT __attribute__((warn_unused_result)) #elif _MSC_VER #define DART_WARN_UNUSED_RESULT _Check_return_ #else #define DART_WARN_UNUSED_RESULT #endif /* * ======= * Handles * ======= */ /** * An isolate is the unit of concurrency in Dart. Each isolate has * its own memory and thread of control. No state is shared between * isolates. Instead, isolates communicate by message passing. * * Each thread keeps track of its current isolate, which is the * isolate which is ready to execute on the current thread. The * current isolate may be NULL, in which case no isolate is ready to * execute. Most of the Dart apis require there to be a current * isolate in order to function without error. The current isolate is * set by any call to Dart_CreateIsolateGroup or Dart_EnterIsolate. */ typedef struct _Dart_Isolate* Dart_Isolate; typedef struct _Dart_IsolateGroup* Dart_IsolateGroup; /** * An object reference managed by the Dart VM garbage collector. * * Because the garbage collector may move objects, it is unsafe to * refer to objects directly. Instead, we refer to objects through * handles, which are known to the garbage collector and updated * automatically when the object is moved. Handles should be passed * by value (except in cases like out-parameters) and should never be * allocated on the heap. * * Most functions in the Dart Embedding API return a handle. When a * function completes normally, this will be a valid handle to an * object in the Dart VM heap. This handle may represent the result of * the operation or it may be a special valid handle used merely to * indicate successful completion. Note that a valid handle may in * some cases refer to the null object. * * --- Error handles --- * * When a function encounters a problem that prevents it from * completing normally, it returns an error handle (See Dart_IsError). * An error handle has an associated error message that gives more * details about the problem (See Dart_GetError). * * There are four kinds of error handles that can be produced, * depending on what goes wrong: * * - Api error handles are produced when an api function is misused. * This happens when a Dart embedding api function is called with * invalid arguments or in an invalid context. * * - Unhandled exception error handles are produced when, during the * execution of Dart code, an exception is thrown but not caught. * Prototypically this would occur during a call to Dart_Invoke, but * it can occur in any function which triggers the execution of Dart * code (for example, Dart_ToString). * * An unhandled exception error provides access to an exception and * stacktrace via the functions Dart_ErrorGetException and * Dart_ErrorGetStackTrace. * * - Compilation error handles are produced when, during the execution * of Dart code, a compile-time error occurs. As above, this can * occur in any function which triggers the execution of Dart code. * * - Fatal error handles are produced when the system wants to shut * down the current isolate. * * --- Propagating errors --- * * When an error handle is returned from the top level invocation of * Dart code in a program, the embedder must handle the error as they * see fit. Often, the embedder will print the error message produced * by Dart_Error and exit the program. * * When an error is returned while in the body of a native function, * it can be propagated up the call stack by calling * Dart_PropagateError, Dart_SetReturnValue, or Dart_ThrowException. * Errors should be propagated unless there is a specific reason not * to. If an error is not propagated then it is ignored. For * example, if an unhandled exception error is ignored, that * effectively "catches" the unhandled exception. Fatal errors must * always be propagated. * * When an error is propagated, any current scopes created by * Dart_EnterScope will be exited. * * Using Dart_SetReturnValue to propagate an exception is somewhat * more convenient than using Dart_PropagateError, and should be * preferred for reasons discussed below. * * Dart_PropagateError and Dart_ThrowException do not return. Instead * they transfer control non-locally using a setjmp-like mechanism. * This can be inconvenient if you have resources that you need to * clean up before propagating the error. * * When relying on Dart_PropagateError, we often return error handles * rather than propagating them from helper functions. Consider the * following contrived example: * * 1 Dart_Handle isLongStringHelper(Dart_Handle arg) { * 2 intptr_t* length = 0; * 3 result = Dart_StringLength(arg, &length); * 4 if (Dart_IsError(result)) { * 5 return result; * 6 } * 7 return Dart_NewBoolean(length > 100); * 8 } * 9 * 10 void NativeFunction_isLongString(Dart_NativeArguments args) { * 11 Dart_EnterScope(); * 12 AllocateMyResource(); * 13 Dart_Handle arg = Dart_GetNativeArgument(args, 0); * 14 Dart_Handle result = isLongStringHelper(arg); * 15 if (Dart_IsError(result)) { * 16 FreeMyResource(); * 17 Dart_PropagateError(result); * 18 abort(); // will not reach here * 19 } * 20 Dart_SetReturnValue(result); * 21 FreeMyResource(); * 22 Dart_ExitScope(); * 23 } * * In this example, we have a native function which calls a helper * function to do its work. On line 5, the helper function could call * Dart_PropagateError, but that would not give the native function a * chance to call FreeMyResource(), causing a leak. Instead, the * helper function returns the error handle to the caller, giving the * caller a chance to clean up before propagating the error handle. * * When an error is propagated by calling Dart_SetReturnValue, the * native function will be allowed to complete normally and then the * exception will be propagated only once the native call * returns. This can be convenient, as it allows the C code to clean * up normally. * * The example can be written more simply using Dart_SetReturnValue to * propagate the error. * * 1 Dart_Handle isLongStringHelper(Dart_Handle arg) { * 2 intptr_t* length = 0; * 3 result = Dart_StringLength(arg, &length); * 4 if (Dart_IsError(result)) { * 5 return result * 6 } * 7 return Dart_NewBoolean(length > 100); * 8 } * 9 * 10 void NativeFunction_isLongString(Dart_NativeArguments args) { * 11 Dart_EnterScope(); * 12 AllocateMyResource(); * 13 Dart_Handle arg = Dart_GetNativeArgument(args, 0); * 14 Dart_SetReturnValue(isLongStringHelper(arg)); * 15 FreeMyResource(); * 16 Dart_ExitScope(); * 17 } * * In this example, the call to Dart_SetReturnValue on line 14 will * either return the normal return value or the error (potentially * generated on line 3). The call to FreeMyResource on line 15 will * execute in either case. * * --- Local and persistent handles --- * * Local handles are allocated within the current scope (see * Dart_EnterScope) and go away when the current scope exits. Unless * otherwise indicated, callers should assume that all functions in * the Dart embedding api return local handles. * * Persistent handles are allocated within the current isolate. They * can be used to store objects across scopes. Persistent handles have * the lifetime of the current isolate unless they are explicitly * deallocated (see Dart_DeletePersistentHandle). * The type Dart_Handle represents a handle (both local and persistent). * The type Dart_PersistentHandle is a Dart_Handle and it is used to * document that a persistent handle is expected as a parameter to a call * or the return value from a call is a persistent handle. * * FinalizableHandles are persistent handles which are auto deleted when * the object is garbage collected. It is never safe to use these handles * unless you know the object is still reachable. * * WeakPersistentHandles are persistent handles which are automatically set * to point Dart_Null when the object is garbage collected. They are not auto * deleted, so it is safe to use them after the object has become unreachable. */ typedef struct _Dart_Handle* Dart_Handle; typedef Dart_Handle Dart_PersistentHandle; typedef struct _Dart_WeakPersistentHandle* Dart_WeakPersistentHandle; typedef struct _Dart_FinalizableHandle* Dart_FinalizableHandle; // These structs are versioned by DART_API_DL_MAJOR_VERSION, bump the // version when changing this struct. typedef void (*Dart_HandleFinalizer)(void* isolate_callback_data, void* peer); /** * Is this an error handle? * * Requires there to be a current isolate. */ DART_EXPORT bool Dart_IsError(Dart_Handle handle); /** * Is this an api error handle? * * Api error handles are produced when an api function is misused. * This happens when a Dart embedding api function is called with * invalid arguments or in an invalid context. * * Requires there to be a current isolate. */ DART_EXPORT bool Dart_IsApiError(Dart_Handle handle); /** * Is this an unhandled exception error handle? * * Unhandled exception error handles are produced when, during the * execution of Dart code, an exception is thrown but not caught. * This can occur in any function which triggers the execution of Dart * code. * * See Dart_ErrorGetException and Dart_ErrorGetStackTrace. * * Requires there to be a current isolate. */ DART_EXPORT bool Dart_IsUnhandledExceptionError(Dart_Handle handle); /** * Is this a compilation error handle? * * Compilation error handles are produced when, during the execution * of Dart code, a compile-time error occurs. This can occur in any * function which triggers the execution of Dart code. * * Requires there to be a current isolate. */ DART_EXPORT bool Dart_IsCompilationError(Dart_Handle handle); /** * Is this a fatal error handle? * * Fatal error handles are produced when the system wants to shut down * the current isolate. * * Requires there to be a current isolate. */ DART_EXPORT bool Dart_IsFatalError(Dart_Handle handle); /** * Gets the error message from an error handle. * * Requires there to be a current isolate. * * \return A C string containing an error message if the handle is * error. An empty C string ("") if the handle is valid. This C * String is scope allocated and is only valid until the next call * to Dart_ExitScope. */ DART_EXPORT const char* Dart_GetError(Dart_Handle handle); /** * Is this an error handle for an unhandled exception? */ DART_EXPORT bool Dart_ErrorHasException(Dart_Handle handle); /** * Gets the exception Object from an unhandled exception error handle. */ DART_EXPORT Dart_Handle Dart_ErrorGetException(Dart_Handle handle); /** * Gets the stack trace Object from an unhandled exception error handle. */ DART_EXPORT Dart_Handle Dart_ErrorGetStackTrace(Dart_Handle handle); /** * Produces an api error handle with the provided error message. * * Requires there to be a current isolate. * * \param error the error message. */ DART_EXPORT Dart_Handle Dart_NewApiError(const char* error); DART_EXPORT Dart_Handle Dart_NewCompilationError(const char* error); /** * Produces a new unhandled exception error handle. * * Requires there to be a current isolate. * * \param exception An instance of a Dart object to be thrown or * an ApiError or CompilationError handle. * When an ApiError or CompilationError handle is passed in * a string object of the error message is created and it becomes * the Dart object to be thrown. */ DART_EXPORT Dart_Handle Dart_NewUnhandledExceptionError(Dart_Handle exception); /** * Propagates an error. * * If the provided handle is an unhandled exception error, this * function will cause the unhandled exception to be rethrown. This * will proceed in the standard way, walking up Dart frames until an * appropriate 'catch' block is found, executing 'finally' blocks, * etc. * * If the error is not an unhandled exception error, we will unwind * the stack to the next C frame. Intervening Dart frames will be * discarded; specifically, 'finally' blocks will not execute. This * is the standard way that compilation errors (and the like) are * handled by the Dart runtime. * * In either case, when an error is propagated any current scopes * created by Dart_EnterScope will be exited. * * See the additional discussion under "Propagating Errors" at the * beginning of this file. * * \param An error handle (See Dart_IsError) * * \return On success, this function does not return. On failure, the * process is terminated. */ DART_EXPORT void Dart_PropagateError(Dart_Handle handle); /** * Converts an object to a string. * * May generate an unhandled exception error. * * \return The converted string if no error occurs during * the conversion. If an error does occur, an error handle is * returned. */ DART_EXPORT Dart_Handle Dart_ToString(Dart_Handle object); /** * Checks to see if two handles refer to identically equal objects. * * If both handles refer to instances, this is equivalent to using the top-level * function identical() from dart:core. Otherwise, returns whether the two * argument handles refer to the same object. * * \param obj1 An object to be compared. * \param obj2 An object to be compared. * * \return True if the objects are identically equal. False otherwise. */ DART_EXPORT bool Dart_IdentityEquals(Dart_Handle obj1, Dart_Handle obj2); /** * Allocates a handle in the current scope from a persistent handle. */ DART_EXPORT Dart_Handle Dart_HandleFromPersistent(Dart_PersistentHandle object); /** * Allocates a handle in the current scope from a weak persistent handle. * * This will be a handle to Dart_Null if the object has been garbage collected. */ DART_EXPORT Dart_Handle Dart_HandleFromWeakPersistent(Dart_WeakPersistentHandle object); /** * Allocates a persistent handle for an object. * * This handle has the lifetime of the current isolate unless it is * explicitly deallocated by calling Dart_DeletePersistentHandle. * * Requires there to be a current isolate. */ DART_EXPORT Dart_PersistentHandle Dart_NewPersistentHandle(Dart_Handle object); /** * Assign value of local handle to a persistent handle. * * Requires there to be a current isolate. * * \param obj1 A persistent handle whose value needs to be set. * \param obj2 An object whose value needs to be set to the persistent handle. * * \return Success if the persistent handle was set * Otherwise, returns an error. */ DART_EXPORT void Dart_SetPersistentHandle(Dart_PersistentHandle obj1, Dart_Handle obj2); /** * Deallocates a persistent handle. * * Requires there to be a current isolate group. */ DART_EXPORT void Dart_DeletePersistentHandle(Dart_PersistentHandle object); /** * Allocates a weak persistent handle for an object. * * This handle has the lifetime of the current isolate. The handle can also be * explicitly deallocated by calling Dart_DeleteWeakPersistentHandle. * * If the object becomes unreachable the callback is invoked with the peer as * argument. The callback can be executed on any thread, will have a current * isolate group, but will not have a current isolate. The callback can only * call Dart_DeletePersistentHandle or Dart_DeleteWeakPersistentHandle. This * gives the embedder the ability to cleanup data associated with the object. * The handle will point to the Dart_Null object after the finalizer has been * run. It is illegal to call into the VM with any other Dart_* functions from * the callback. If the handle is deleted before the object becomes * unreachable, the callback is never invoked. * * Requires there to be a current isolate. * * \param object An object with identity. * \param peer A pointer to a native object or NULL. This value is * provided to callback when it is invoked. * \param external_allocation_size The number of externally allocated * bytes for peer. Used to inform the garbage collector. * \param callback A function pointer that will be invoked sometime * after the object is garbage collected, unless the handle has been deleted. * A valid callback needs to be specified it cannot be NULL. * * \return The weak persistent handle or NULL. NULL is returned in case of bad * parameters. */ DART_EXPORT Dart_WeakPersistentHandle Dart_NewWeakPersistentHandle(Dart_Handle object, void* peer, intptr_t external_allocation_size, Dart_HandleFinalizer callback); /** * Deletes the given weak persistent [object] handle. * * Requires there to be a current isolate group. */ DART_EXPORT void Dart_DeleteWeakPersistentHandle( Dart_WeakPersistentHandle object); /** * Updates the external memory size for the given weak persistent handle. * * May trigger garbage collection. */ DART_EXPORT void Dart_UpdateExternalSize(Dart_WeakPersistentHandle object, intptr_t external_allocation_size); /** * Allocates a finalizable handle for an object. * * This handle has the lifetime of the current isolate group unless the object * pointed to by the handle is garbage collected, in this case the VM * automatically deletes the handle after invoking the callback associated * with the handle. The handle can also be explicitly deallocated by * calling Dart_DeleteFinalizableHandle. * * If the object becomes unreachable the callback is invoked with the * the peer as argument. The callback can be executed on any thread, will have * an isolate group, but will not have a current isolate. The callback can only * call Dart_DeletePersistentHandle or Dart_DeleteWeakPersistentHandle. * This gives the embedder the ability to cleanup data associated with the * object and clear out any cached references to the handle. All references to * this handle after the callback will be invalid. It is illegal to call into * the VM with any other Dart_* functions from the callback. If the handle is * deleted before the object becomes unreachable, the callback is never * invoked. * * Requires there to be a current isolate. * * \param object An object with identity. * \param peer A pointer to a native object or NULL. This value is * provided to callback when it is invoked. * \param external_allocation_size The number of externally allocated * bytes for peer. Used to inform the garbage collector. * \param callback A function pointer that will be invoked sometime * after the object is garbage collected, unless the handle has been deleted. * A valid callback needs to be specified it cannot be NULL. * * \return The finalizable handle or NULL. NULL is returned in case of bad * parameters. */ DART_EXPORT Dart_FinalizableHandle Dart_NewFinalizableHandle(Dart_Handle object, void* peer, intptr_t external_allocation_size, Dart_HandleFinalizer callback); /** * Deletes the given finalizable [object] handle. * * The caller has to provide the actual Dart object the handle was created from * to prove the object (and therefore the finalizable handle) is still alive. * * Requires there to be a current isolate. */ DART_EXPORT void Dart_DeleteFinalizableHandle(Dart_FinalizableHandle object, Dart_Handle strong_ref_to_object); /** * Updates the external memory size for the given finalizable handle. * * The caller has to provide the actual Dart object the handle was created from * to prove the object (and therefore the finalizable handle) is still alive. * * May trigger garbage collection. */ DART_EXPORT void Dart_UpdateFinalizableExternalSize( Dart_FinalizableHandle object, Dart_Handle strong_ref_to_object, intptr_t external_allocation_size); /* * ========================== * Initialization and Globals * ========================== */ /** * Gets the version string for the Dart VM. * * The version of the Dart VM can be accessed without initializing the VM. * * \return The version string for the embedded Dart VM. */ DART_EXPORT const char* Dart_VersionString(); /** * Isolate specific flags are set when creating a new isolate using the * Dart_IsolateFlags structure. * * Current version of flags is encoded in a 32-bit integer with 16 bits used * for each part. */ #define DART_FLAGS_CURRENT_VERSION (0x0000000c) typedef struct { int32_t version; bool enable_asserts; bool use_field_guards; bool use_osr; bool obfuscate; bool load_vmservice_library; bool copy_parent_code; bool null_safety; bool is_system_isolate; } Dart_IsolateFlags; /** * Initialize Dart_IsolateFlags with correct version and default values. */ DART_EXPORT void Dart_IsolateFlagsInitialize(Dart_IsolateFlags* flags); /** * An isolate creation and initialization callback function. * * This callback, provided by the embedder, is called when the VM * needs to create an isolate. The callback should create an isolate * by calling Dart_CreateIsolateGroup and load any scripts required for * execution. * * This callback may be called on a different thread than the one * running the parent isolate. * * When the function returns NULL, it is the responsibility of this * function to ensure that Dart_ShutdownIsolate has been called if * required (for example, if the isolate was created successfully by * Dart_CreateIsolateGroup() but the root library fails to load * successfully, then the function should call Dart_ShutdownIsolate * before returning). * * When the function returns NULL, the function should set *error to * a malloc-allocated buffer containing a useful error message. The * caller of this function (the VM) will make sure that the buffer is * freed. * * \param script_uri The uri of the main source file or snapshot to load. * Either the URI of the parent isolate set in Dart_CreateIsolateGroup for * Isolate.spawn, or the argument to Isolate.spawnUri canonicalized by the * library tag handler of the parent isolate. * The callback is responsible for loading the program by a call to * Dart_LoadScriptFromKernel. * \param main The name of the main entry point this isolate will * eventually run. This is provided for advisory purposes only to * improve debugging messages. The main function is not invoked by * this function. * \param package_root Ignored. * \param package_config Uri of the package configuration file (either in format * of .packages or .dart_tool/package_config.json) for this isolate * to resolve package imports against. If this parameter is not passed the * package resolution of the parent isolate should be used. * \param flags Default flags for this isolate being spawned. Either inherited * from the spawning isolate or passed as parameters when spawning the * isolate from Dart code. * \param isolate_data The isolate data which was passed to the * parent isolate when it was created by calling Dart_CreateIsolateGroup(). * \param error A structure into which the embedder can place a * C string containing an error message in the case of failures. * * \return The embedder returns NULL if the creation and * initialization was not successful and the isolate if successful. */ typedef Dart_Isolate (*Dart_IsolateGroupCreateCallback)( const char* script_uri, const char* main, const char* package_root, const char* package_config, Dart_IsolateFlags* flags, void* isolate_data, char** error); /** * An isolate initialization callback function. * * This callback, provided by the embedder, is called when the VM has created an * isolate within an existing isolate group (i.e. from the same source as an * existing isolate). * * The callback should setup native resolvers and might want to set a custom * message handler via [Dart_SetMessageNotifyCallback] and mark the isolate as * runnable. * * This callback may be called on a different thread than the one * running the parent isolate. * * When the function returns `false`, it is the responsibility of this * function to ensure that `Dart_ShutdownIsolate` has been called. * * When the function returns `false`, the function should set *error to * a malloc-allocated buffer containing a useful error message. The * caller of this function (the VM) will make sure that the buffer is * freed. * * \param child_isolate_data The callback data to associate with the new * child isolate. * \param error A structure into which the embedder can place a * C string containing an error message in the case the initialization fails. * * \return The embedder returns true if the initialization was successful and * false otherwise (in which case the VM will terminate the isolate). */ typedef bool (*Dart_InitializeIsolateCallback)(void** child_isolate_data, char** error); /** * An isolate unhandled exception callback function. * * This callback has been DEPRECATED. */ typedef void (*Dart_IsolateUnhandledExceptionCallback)(Dart_Handle error); /** * An isolate shutdown callback function. * * This callback, provided by the embedder, is called before the vm * shuts down an isolate. The isolate being shutdown will be the current * isolate. It is safe to run Dart code. * * This function should be used to dispose of native resources that * are allocated to an isolate in order to avoid leaks. * * \param isolate_group_data The same callback data which was passed to the * isolate group when it was created. * \param isolate_data The same callback data which was passed to the isolate * when it was created. */ typedef void (*Dart_IsolateShutdownCallback)(void* isolate_group_data, void* isolate_data); /** * An isolate cleanup callback function. * * This callback, provided by the embedder, is called after the vm * shuts down an isolate. There will be no current isolate and it is *not* * safe to run Dart code. * * This function should be used to dispose of native resources that * are allocated to an isolate in order to avoid leaks. * * \param isolate_group_data The same callback data which was passed to the * isolate group when it was created. * \param isolate_data The same callback data which was passed to the isolate * when it was created. */ typedef void (*Dart_IsolateCleanupCallback)(void* isolate_group_data, void* isolate_data); /** * An isolate group cleanup callback function. * * This callback, provided by the embedder, is called after the vm * shuts down an isolate group. * * This function should be used to dispose of native resources that * are allocated to an isolate in order to avoid leaks. * * \param isolate_group_data The same callback data which was passed to the * isolate group when it was created. * */ typedef void (*Dart_IsolateGroupCleanupCallback)(void* isolate_group_data); /** * A thread death callback function. * This callback, provided by the embedder, is called before a thread in the * vm thread pool exits. * This function could be used to dispose of native resources that * are associated and attached to the thread, in order to avoid leaks. */ typedef void (*Dart_ThreadExitCallback)(); /** * Callbacks provided by the embedder for file operations. If the * embedder does not allow file operations these callbacks can be * NULL. * * Dart_FileOpenCallback - opens a file for reading or writing. * \param name The name of the file to open. * \param write A boolean variable which indicates if the file is to * opened for writing. If there is an existing file it needs to truncated. * * Dart_FileReadCallback - Read contents of file. * \param data Buffer allocated in the callback into which the contents * of the file are read into. It is the responsibility of the caller to * free this buffer. * \param file_length A variable into which the length of the file is returned. * In the case of an error this value would be -1. * \param stream Handle to the opened file. * * Dart_FileWriteCallback - Write data into file. * \param data Buffer which needs to be written into the file. * \param length Length of the buffer. * \param stream Handle to the opened file. * * Dart_FileCloseCallback - Closes the opened file. * \param stream Handle to the opened file. * */ typedef void* (*Dart_FileOpenCallback)(const char* name, bool write); typedef void (*Dart_FileReadCallback)(uint8_t** data, intptr_t* file_length, void* stream); typedef void (*Dart_FileWriteCallback)(const void* data, intptr_t length, void* stream); typedef void (*Dart_FileCloseCallback)(void* stream); typedef bool (*Dart_EntropySource)(uint8_t* buffer, intptr_t length); /** * Callback provided by the embedder that is used by the vmservice isolate * to request the asset archive. The asset archive must be an uncompressed tar * archive that is stored in a Uint8List. * * If the embedder has no vmservice isolate assets, the callback can be NULL. * * \return The embedder must return a handle to a Uint8List containing an * uncompressed tar archive or null. */ typedef Dart_Handle (*Dart_GetVMServiceAssetsArchive)(); /** * The current version of the Dart_InitializeFlags. Should be incremented every * time Dart_InitializeFlags changes in a binary incompatible way. */ #define DART_INITIALIZE_PARAMS_CURRENT_VERSION (0x00000004) /** Forward declaration */ struct Dart_CodeObserver; /** * Callback provided by the embedder that is used by the VM to notify on code * object creation, *before* it is invoked the first time. * This is useful for embedders wanting to e.g. keep track of PCs beyond * the lifetime of the garbage collected code objects. * Note that an address range may be used by more than one code object over the * lifecycle of a process. Clients of this function should record timestamps for * these compilation events and when collecting PCs to disambiguate reused * address ranges. */ typedef void (*Dart_OnNewCodeCallback)(struct Dart_CodeObserver* observer, const char* name, uintptr_t base, uintptr_t size); typedef struct Dart_CodeObserver { void* data; Dart_OnNewCodeCallback on_new_code; } Dart_CodeObserver; /** * Describes how to initialize the VM. Used with Dart_Initialize. * * \param version Identifies the version of the struct used by the client. * should be initialized to DART_INITIALIZE_PARAMS_CURRENT_VERSION. * \param vm_isolate_snapshot A buffer containing a snapshot of the VM isolate * or NULL if no snapshot is provided. If provided, the buffer must remain * valid until Dart_Cleanup returns. * \param instructions_snapshot A buffer containing a snapshot of precompiled * instructions, or NULL if no snapshot is provided. If provided, the buffer * must remain valid until Dart_Cleanup returns. * \param initialize_isolate A function to be called during isolate * initialization inside an existing isolate group. * See Dart_InitializeIsolateCallback. * \param create_group A function to be called during isolate group creation. * See Dart_IsolateGroupCreateCallback. * \param shutdown A function to be called right before an isolate is shutdown. * See Dart_IsolateShutdownCallback. * \param cleanup A function to be called after an isolate was shutdown. * See Dart_IsolateCleanupCallback. * \param cleanup_group A function to be called after an isolate group is shutdown. * See Dart_IsolateGroupCleanupCallback. * \param get_service_assets A function to be called by the service isolate when * it requires the vmservice assets archive. * See Dart_GetVMServiceAssetsArchive. * \param code_observer An external code observer callback function. * The observer can be invoked as early as during the Dart_Initialize() call. */ typedef struct { int32_t version; const uint8_t* vm_snapshot_data; const uint8_t* vm_snapshot_instructions; Dart_IsolateGroupCreateCallback create_group; Dart_InitializeIsolateCallback initialize_isolate; Dart_IsolateShutdownCallback shutdown_isolate; Dart_IsolateCleanupCallback cleanup_isolate; Dart_IsolateGroupCleanupCallback cleanup_group; Dart_ThreadExitCallback thread_exit; Dart_FileOpenCallback file_open; Dart_FileReadCallback file_read; Dart_FileWriteCallback file_write; Dart_FileCloseCallback file_close; Dart_EntropySource entropy_source; Dart_GetVMServiceAssetsArchive get_service_assets; bool start_kernel_isolate; Dart_CodeObserver* code_observer; } Dart_InitializeParams; /** * Initializes the VM. * * \param params A struct containing initialization information. The version * field of the struct must be DART_INITIALIZE_PARAMS_CURRENT_VERSION. * * \return NULL if initialization is successful. Returns an error message * otherwise. The caller is responsible for freeing the error message. */ DART_EXPORT DART_WARN_UNUSED_RESULT char* Dart_Initialize( Dart_InitializeParams* params); /** * Cleanup state in the VM before process termination. * * \return NULL if cleanup is successful. Returns an error message otherwise. * The caller is responsible for freeing the error message. * * NOTE: This function must not be called on a thread that was created by the VM * itself. */ DART_EXPORT DART_WARN_UNUSED_RESULT char* Dart_Cleanup(); /** * Sets command line flags. Should be called before Dart_Initialize. * * \param argc The length of the arguments array. * \param argv An array of arguments. * * \return NULL if successful. Returns an error message otherwise. * The caller is responsible for freeing the error message. * * NOTE: This call does not store references to the passed in c-strings. */ DART_EXPORT DART_WARN_UNUSED_RESULT char* Dart_SetVMFlags(int argc, const char** argv); /** * Returns true if the named VM flag is of boolean type, specified, and set to * true. * * \param flag_name The name of the flag without leading punctuation * (example: "enable_asserts"). */ DART_EXPORT bool Dart_IsVMFlagSet(const char* flag_name); /* * ======== * Isolates * ======== */ /** * Creates a new isolate. The new isolate becomes the current isolate. * * A snapshot can be used to restore the VM quickly to a saved state * and is useful for fast startup. If snapshot data is provided, the * isolate will be started using that snapshot data. Requires a core snapshot or * an app snapshot created by Dart_CreateSnapshot or * Dart_CreatePrecompiledSnapshot* from a VM with the same version. * * Requires there to be no current isolate. * * \param script_uri The main source file or snapshot this isolate will load. * The VM will provide this URI to the Dart_IsolateGroupCreateCallback when a child * isolate is created by Isolate.spawn. The embedder should use a URI that * allows it to load the same program into such a child isolate. * \param name A short name for the isolate to improve debugging messages. * Typically of the format 'foo.dart:main()'. * \param isolate_snapshot_data * \param isolate_snapshot_instructions Buffers containing a snapshot of the * isolate or NULL if no snapshot is provided. If provided, the buffers must * remain valid until the isolate shuts down. * \param flags Pointer to VM specific flags or NULL for default flags. * \param isolate_group_data Embedder group data. This data can be obtained * by calling Dart_IsolateGroupData and will be passed to the * Dart_IsolateShutdownCallback, Dart_IsolateCleanupCallback, and * Dart_IsolateGroupCleanupCallback. * \param isolate_data Embedder data. This data will be passed to * the Dart_IsolateGroupCreateCallback when new isolates are spawned from * this parent isolate. * \param error Returns NULL if creation is successful, an error message * otherwise. The caller is responsible for calling free() on the error * message. * * \return The new isolate on success, or NULL if isolate creation failed. */ DART_EXPORT Dart_Isolate Dart_CreateIsolateGroup(const char* script_uri, const char* name, const uint8_t* isolate_snapshot_data, const uint8_t* isolate_snapshot_instructions, Dart_IsolateFlags* flags, void* isolate_group_data, void* isolate_data, char** error); /** * Creates a new isolate inside the isolate group of [group_member]. * * Requires there to be no current isolate. * * \param group_member An isolate from the same group into which the newly created * isolate should be born into. Other threads may not have entered / enter this * member isolate. * \param name A short name for the isolate for debugging purposes. * \param shutdown_callback A callback to be called when the isolate is being * shutdown (may be NULL). * \param cleanup_callback A callback to be called when the isolate is being * cleaned up (may be NULL). * \param isolate_data The embedder-specific data associated with this isolate. * \param error Set to NULL if creation is successful, set to an error * message otherwise. The caller is responsible for calling free() on the * error message. * * \return The newly created isolate on success, or NULL if isolate creation * failed. * * If successful, the newly created isolate will become the current isolate. */ DART_EXPORT Dart_Isolate Dart_CreateIsolateInGroup(Dart_Isolate group_member, const char* name, Dart_IsolateShutdownCallback shutdown_callback, Dart_IsolateCleanupCallback cleanup_callback, void* child_isolate_data, char** error); /* TODO(turnidge): Document behavior when there is already a current * isolate. */ /** * Creates a new isolate from a Dart Kernel file. The new isolate * becomes the current isolate. * * Requires there to be no current isolate. * * \param script_uri The main source file or snapshot this isolate will load. * The VM will provide this URI to the Dart_IsolateGroupCreateCallback when a child * isolate is created by Isolate.spawn. The embedder should use a URI that * allows it to load the same program into such a child isolate. * \param name A short name for the isolate to improve debugging messages. * Typically of the format 'foo.dart:main()'. * \param kernel_buffer * \param kernel_buffer_size A buffer which contains a kernel/DIL program. Must * remain valid until isolate shutdown. * \param flags Pointer to VM specific flags or NULL for default flags. * \param isolate_group_data Embedder group data. This data can be obtained * by calling Dart_IsolateGroupData and will be passed to the * Dart_IsolateShutdownCallback, Dart_IsolateCleanupCallback, and * Dart_IsolateGroupCleanupCallback. * \param isolate_data Embedder data. This data will be passed to * the Dart_IsolateGroupCreateCallback when new isolates are spawned from * this parent isolate. * \param error Returns NULL if creation is successful, an error message * otherwise. The caller is responsible for calling free() on the error * message. * * \return The new isolate on success, or NULL if isolate creation failed. */ DART_EXPORT Dart_Isolate Dart_CreateIsolateGroupFromKernel(const char* script_uri, const char* name, const uint8_t* kernel_buffer, intptr_t kernel_buffer_size, Dart_IsolateFlags* flags, void* isolate_group_data, void* isolate_data, char** error); /** * Shuts down the current isolate. After this call, the current isolate is NULL. * Any current scopes created by Dart_EnterScope will be exited. Invokes the * shutdown callback and any callbacks of remaining weak persistent handles. * * Requires there to be a current isolate. */ DART_EXPORT void Dart_ShutdownIsolate(); /* TODO(turnidge): Document behavior when there is no current isolate. */ /** * Returns the current isolate. Will return NULL if there is no * current isolate. */ DART_EXPORT Dart_Isolate Dart_CurrentIsolate(); /** * Returns the callback data associated with the current isolate. This * data was set when the isolate got created or initialized. */ DART_EXPORT void* Dart_CurrentIsolateData(); /** * Returns the callback data associated with the given isolate. This * data was set when the isolate got created or initialized. */ DART_EXPORT void* Dart_IsolateData(Dart_Isolate isolate); /** * Returns the current isolate group. Will return NULL if there is no * current isolate group. */ DART_EXPORT Dart_IsolateGroup Dart_CurrentIsolateGroup(); /** * Returns the callback data associated with the current isolate group. This * data was passed to the isolate group when it was created. */ DART_EXPORT void* Dart_CurrentIsolateGroupData(); /** * Returns the callback data associated with the specified isolate group. This * data was passed to the isolate when it was created. * The embedder is responsible for ensuring the consistency of this data * with respect to the lifecycle of an isolate group. */ DART_EXPORT void* Dart_IsolateGroupData(Dart_Isolate isolate); /** * Returns the debugging name for the current isolate. * * This name is unique to each isolate and should only be used to make * debugging messages more comprehensible. */ DART_EXPORT Dart_Handle Dart_DebugName(); /** * Returns the ID for an isolate which is used to query the service protocol. * * It is the responsibility of the caller to free the returned ID. */ DART_EXPORT const char* Dart_IsolateServiceId(Dart_Isolate isolate); /** * Enters an isolate. After calling this function, * the current isolate will be set to the provided isolate. * * Requires there to be no current isolate. Multiple threads may not be in * the same isolate at once. */ DART_EXPORT void Dart_EnterIsolate(Dart_Isolate isolate); /** * Kills the given isolate. * * This function has the same effect as dart:isolate's * Isolate.kill(priority:immediate). * It can interrupt ordinary Dart code but not native code. If the isolate is * in the middle of a long running native function, the isolate will not be * killed until control returns to Dart. * * Does not require a current isolate. It is safe to kill the current isolate if * there is one. */ DART_EXPORT void Dart_KillIsolate(Dart_Isolate isolate); /** * Notifies the VM that the embedder expects |size| bytes of memory have become * unreachable. The VM may use this hint to adjust the garbage collector's * growth policy. * * Multiple calls are interpreted as increasing, not replacing, the estimate of * unreachable memory. * * Requires there to be a current isolate. */ DART_EXPORT void Dart_HintFreed(intptr_t size); /** * Notifies the VM that the embedder expects to be idle until |deadline|. The VM * may use this time to perform garbage collection or other tasks to avoid * delays during execution of Dart code in the future. * * |deadline| is measured in microseconds against the system's monotonic time. * This clock can be accessed via Dart_TimelineGetMicros(). * * Requires there to be a current isolate. */ DART_EXPORT void Dart_NotifyIdle(int64_t deadline); /** * Notifies the VM that the system is running low on memory. * * Does not require a current isolate. Only valid after calling Dart_Initialize. */ DART_EXPORT void Dart_NotifyLowMemory(); /** * Starts the CPU sampling profiler. */ DART_EXPORT void Dart_StartProfiling(); /** * Stops the CPU sampling profiler. * * Note that some profile samples might still be taken after this fucntion * returns due to the asynchronous nature of the implementation on some * platforms. */ DART_EXPORT void Dart_StopProfiling(); /** * Notifies the VM that the current thread should not be profiled until a * matching call to Dart_ThreadEnableProfiling is made. * * NOTE: By default, if a thread has entered an isolate it will be profiled. * This function should be used when an embedder knows a thread is about * to make a blocking call and wants to avoid unnecessary interrupts by * the profiler. */ DART_EXPORT void Dart_ThreadDisableProfiling(); /** * Notifies the VM that the current thread should be profiled. * * NOTE: It is only legal to call this function *after* calling * Dart_ThreadDisableProfiling. * * NOTE: By default, if a thread has entered an isolate it will be profiled. */ DART_EXPORT void Dart_ThreadEnableProfiling(); /** * Register symbol information for the Dart VM's profiler and crash dumps. * * This consumes the output of //topaz/runtime/dart/profiler_symbols, which * should be treated as opaque. */ DART_EXPORT void Dart_AddSymbols(const char* dso_name, void* buffer, intptr_t buffer_size); /** * Exits an isolate. After this call, Dart_CurrentIsolate will * return NULL. * * Requires there to be a current isolate. */ DART_EXPORT void Dart_ExitIsolate(); /* TODO(turnidge): We don't want users of the api to be able to exit a * "pure" dart isolate. Implement and document. */ /** * Creates a full snapshot of the current isolate heap. * * A full snapshot is a compact representation of the dart vm isolate heap * and dart isolate heap states. These snapshots are used to initialize * the vm isolate on startup and fast initialization of an isolate. * A Snapshot of the heap is created before any dart code has executed. * * Requires there to be a current isolate. Not available in the precompiled * runtime (check Dart_IsPrecompiledRuntime). * * \param buffer Returns a pointer to a buffer containing the * snapshot. This buffer is scope allocated and is only valid * until the next call to Dart_ExitScope. * \param size Returns the size of the buffer. * \param is_core Create a snapshot containing core libraries. * Such snapshot should be agnostic to null safety mode. * * \return A valid handle if no error occurs during the operation. */ DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle Dart_CreateSnapshot(uint8_t** vm_snapshot_data_buffer, intptr_t* vm_snapshot_data_size, uint8_t** isolate_snapshot_data_buffer, intptr_t* isolate_snapshot_data_size, bool is_core); /** * Returns whether the buffer contains a kernel file. * * \param buffer Pointer to a buffer that might contain a kernel binary. * \param buffer_size Size of the buffer. * * \return Whether the buffer contains a kernel binary (full or partial). */ DART_EXPORT bool Dart_IsKernel(const uint8_t* buffer, intptr_t buffer_size); /** * Make isolate runnable. * * When isolates are spawned, this function is used to indicate that * the creation and initialization (including script loading) of the * isolate is complete and the isolate can start. * This function expects there to be no current isolate. * * \param isolate The isolate to be made runnable. * * \return NULL if successful. Returns an error message otherwise. The caller * is responsible for freeing the error message. */ DART_EXPORT DART_WARN_UNUSED_RESULT char* Dart_IsolateMakeRunnable( Dart_Isolate isolate); /* * ================== * Messages and Ports * ================== */ /** * A port is used to send or receive inter-isolate messages */ typedef int64_t Dart_Port; /** * ILLEGAL_PORT is a port number guaranteed never to be associated with a valid * port. */ #define ILLEGAL_PORT ((Dart_Port)0) /** * A message notification callback. * * This callback allows the embedder to provide an alternate wakeup * mechanism for the delivery of inter-isolate messages. It is the * responsibility of the embedder to call Dart_HandleMessage to * process the message. */ typedef void (*Dart_MessageNotifyCallback)(Dart_Isolate dest_isolate); /** * Allows embedders to provide an alternative wakeup mechanism for the * delivery of inter-isolate messages. This setting only applies to * the current isolate. * * Most embedders will only call this function once, before isolate * execution begins. If this function is called after isolate * execution begins, the embedder is responsible for threading issues. */ DART_EXPORT void Dart_SetMessageNotifyCallback( Dart_MessageNotifyCallback message_notify_callback); /* TODO(turnidge): Consider moving this to isolate creation so that it * is impossible to mess up. */ /** * Query the current message notify callback for the isolate. * * \return The current message notify callback for the isolate. */ DART_EXPORT Dart_MessageNotifyCallback Dart_GetMessageNotifyCallback(); /** * The VM's default message handler supports pausing an isolate before it * processes the first message and right after the it processes the isolate's * final message. This can be controlled for all isolates by two VM flags: * * `--pause-isolates-on-start` * `--pause-isolates-on-exit` * * Additionally, Dart_SetShouldPauseOnStart and Dart_SetShouldPauseOnExit can be * used to control this behaviour on a per-isolate basis. * * When an embedder is using a Dart_MessageNotifyCallback the embedder * needs to cooperate with the VM so that the service protocol can report * accurate information about isolates and so that tools such as debuggers * work reliably. * * The following functions can be used to implement pausing on start and exit. */ /** * If the VM flag `--pause-isolates-on-start` was passed this will be true. * * \return A boolean value indicating if pause on start was requested. */ DART_EXPORT bool Dart_ShouldPauseOnStart(); /** * Override the VM flag `--pause-isolates-on-start` for the current isolate. * * \param should_pause Should the isolate be paused on start? * * NOTE: This must be called before Dart_IsolateMakeRunnable. */ DART_EXPORT void Dart_SetShouldPauseOnStart(bool should_pause); /** * Is the current isolate paused on start? * * \return A boolean value indicating if the isolate is paused on start. */ DART_EXPORT bool Dart_IsPausedOnStart(); /** * Called when the embedder has paused the current isolate on start and when * the embedder has resumed the isolate. * * \param paused Is the isolate paused on start? */ DART_EXPORT void Dart_SetPausedOnStart(bool paused); /** * If the VM flag `--pause-isolates-on-exit` was passed this will be true. * * \return A boolean value indicating if pause on exit was requested. */ DART_EXPORT bool Dart_ShouldPauseOnExit(); /** * Override the VM flag `--pause-isolates-on-exit` for the current isolate. * * \param should_pause Should the isolate be paused on exit? * */ DART_EXPORT void Dart_SetShouldPauseOnExit(bool should_pause); /** * Is the current isolate paused on exit? * * \return A boolean value indicating if the isolate is paused on exit. */ DART_EXPORT bool Dart_IsPausedOnExit(); /** * Called when the embedder has paused the current isolate on exit and when * the embedder has resumed the isolate. * * \param paused Is the isolate paused on exit? */ DART_EXPORT void Dart_SetPausedOnExit(bool paused); /** * Called when the embedder has caught a top level unhandled exception error * in the current isolate. * * NOTE: It is illegal to call this twice on the same isolate without first * clearing the sticky error to null. * * \param error The unhandled exception error. */ DART_EXPORT void Dart_SetStickyError(Dart_Handle error); /** * Does the current isolate have a sticky error? */ DART_EXPORT bool Dart_HasStickyError(); /** * Gets the sticky error for the current isolate. * * \return A handle to the sticky error object or null. */ DART_EXPORT Dart_Handle Dart_GetStickyError(); /** * Handles the next pending message for the current isolate. * * May generate an unhandled exception error. * * \return A valid handle if no error occurs during the operation. */ DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle Dart_HandleMessage(); /** * Drains the microtask queue, then blocks the calling thread until the current * isolate recieves a message, then handles all messages. * * \param timeout_millis When non-zero, the call returns after the indicated number of milliseconds even if no message was received. * \return A valid handle if no error occurs, otherwise an error handle. */ DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle Dart_WaitForEvent(int64_t timeout_millis); /** * Handles any pending messages for the vm service for the current * isolate. * * This function may be used by an embedder at a breakpoint to avoid * pausing the vm service. * * This function can indirectly cause the message notify callback to * be called. * * \return true if the vm service requests the program resume * execution, false otherwise */ DART_EXPORT bool Dart_HandleServiceMessages(); /** * Does the current isolate have pending service messages? * * \return true if the isolate has pending service messages, false otherwise. */ DART_EXPORT bool Dart_HasServiceMessages(); /** * Processes any incoming messages for the current isolate. * * This function may only be used when the embedder has not provided * an alternate message delivery mechanism with * Dart_SetMessageCallbacks. It is provided for convenience. * * This function waits for incoming messages for the current * isolate. As new messages arrive, they are handled using * Dart_HandleMessage. The routine exits when all ports to the * current isolate are closed. * * \return A valid handle if the run loop exited successfully. If an * exception or other error occurs while processing messages, an * error handle is returned. */ DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle Dart_RunLoop(); /** * Lets the VM run message processing for the isolate. * * This function expects there to a current isolate and the current isolate * must not have an active api scope. The VM will take care of making the * isolate runnable (if not already), handles its message loop and will take * care of shutting the isolate down once it's done. * * \param errors_are_fatal Whether uncaught errors should be fatal. * \param on_error_port A port to notify on uncaught errors (or ILLEGAL_PORT). * \param on_exit_port A port to notify on exit (or ILLEGAL_PORT). * \param error A non-NULL pointer which will hold an error message if the call * fails. The error has to be free()ed by the caller. * * \return If successfull the VM takes owernship of the isolate and takes care * of its message loop. If not successful the caller retains owernship of the * isolate. */ DART_EXPORT DART_WARN_UNUSED_RESULT bool Dart_RunLoopAsync( bool errors_are_fatal, Dart_Port on_error_port, Dart_Port on_exit_port, char** error); /* TODO(turnidge): Should this be removed from the public api? */ /** * Gets the main port id for the current isolate. */ DART_EXPORT Dart_Port Dart_GetMainPortId(); /** * Does the current isolate have live ReceivePorts? * * A ReceivePort is live when it has not been closed. */ DART_EXPORT bool Dart_HasLivePorts(); /** * Posts a message for some isolate. The message is a serialized * object. * * Requires there to be a current isolate. * * \param port The destination port. * \param object An object from the current isolate. * * \return True if the message was posted. */ DART_EXPORT bool Dart_Post(Dart_Port port_id, Dart_Handle object); /** * Returns a new SendPort with the provided port id. * * \param port_id The destination port. * * \return A new SendPort if no errors occurs. Otherwise returns * an error handle. */ DART_EXPORT Dart_Handle Dart_NewSendPort(Dart_Port port_id); /** * Gets the SendPort id for the provided SendPort. * \param port A SendPort object whose id is desired. * \param port_id Returns the id of the SendPort. * \return Success if no error occurs. Otherwise returns * an error handle. */ DART_EXPORT Dart_Handle Dart_SendPortGetId(Dart_Handle port, Dart_Port* port_id); /* * ====== * Scopes * ====== */ /** * Enters a new scope. * * All new local handles will be created in this scope. Additionally, * some functions may return "scope allocated" memory which is only * valid within this scope. * * Requires there to be a current isolate. */ DART_EXPORT void Dart_EnterScope(); /** * Exits a scope. * * The previous scope (if any) becomes the current scope. * * Requires there to be a current isolate. */ DART_EXPORT void Dart_ExitScope(); /** * The Dart VM uses "zone allocation" for temporary structures. Zones * support very fast allocation of small chunks of memory. The chunks * cannot be deallocated individually, but instead zones support * deallocating all chunks in one fast operation. * * This function makes it possible for the embedder to allocate * temporary data in the VMs zone allocator. * * Zone allocation is possible: * 1. when inside a scope where local handles can be allocated * 2. when processing a message from a native port in a native port * handler * * All the memory allocated this way will be reclaimed either on the * next call to Dart_ExitScope or when the native port handler exits. * * \param size Size of the memory to allocate. * * \return A pointer to the allocated memory. NULL if allocation * failed. Failure might due to is no current VM zone. */ DART_EXPORT uint8_t* Dart_ScopeAllocate(intptr_t size); /* * ======= * Objects * ======= */ /** * Returns the null object. * * \return A handle to the null object. */ DART_EXPORT Dart_Handle Dart_Null(); /** * Is this object null? */ DART_EXPORT bool Dart_IsNull(Dart_Handle object); /** * Returns the empty string object. * * \return A handle to the empty string object. */ DART_EXPORT Dart_Handle Dart_EmptyString(); /** * Returns types that are not classes, and which therefore cannot be looked up * as library members by Dart_GetType. * * \return A handle to the dynamic, void or Never type. */ DART_EXPORT Dart_Handle Dart_TypeDynamic(); DART_EXPORT Dart_Handle Dart_TypeVoid(); DART_EXPORT Dart_Handle Dart_TypeNever(); /** * Checks if the two objects are equal. * * The result of the comparison is returned through the 'equal' * parameter. The return value itself is used to indicate success or * failure, not equality. * * May generate an unhandled exception error. * * \param obj1 An object to be compared. * \param obj2 An object to be compared. * \param equal Returns the result of the equality comparison. * * \return A valid handle if no error occurs during the comparison. */ DART_EXPORT Dart_Handle Dart_ObjectEquals(Dart_Handle obj1, Dart_Handle obj2, bool* equal); /** * Is this object an instance of some type? * * The result of the test is returned through the 'instanceof' parameter. * The return value itself is used to indicate success or failure. * * \param object An object. * \param type A type. * \param instanceof Return true if 'object' is an instance of type 'type'. * * \return A valid handle if no error occurs during the operation. */ DART_EXPORT Dart_Handle Dart_ObjectIsType(Dart_Handle object, Dart_Handle type, bool* instanceof); /** * Query object type. * * \param object Some Object. * * \return true if Object is of the specified type. */ DART_EXPORT bool Dart_IsInstance(Dart_Handle object); DART_EXPORT bool Dart_IsNumber(Dart_Handle object); DART_EXPORT bool Dart_IsInteger(Dart_Handle object); DART_EXPORT bool Dart_IsDouble(Dart_Handle object); DART_EXPORT bool Dart_IsBoolean(Dart_Handle object); DART_EXPORT bool Dart_IsString(Dart_Handle object); DART_EXPORT bool Dart_IsStringLatin1(Dart_Handle object); /* (ISO-8859-1) */ DART_EXPORT bool Dart_IsExternalString(Dart_Handle object); DART_EXPORT bool Dart_IsList(Dart_Handle object); DART_EXPORT bool Dart_IsMap(Dart_Handle object); DART_EXPORT bool Dart_IsLibrary(Dart_Handle object); DART_EXPORT bool Dart_IsType(Dart_Handle handle); DART_EXPORT bool Dart_IsFunction(Dart_Handle handle); DART_EXPORT bool Dart_IsVariable(Dart_Handle handle); DART_EXPORT bool Dart_IsTypeVariable(Dart_Handle handle); DART_EXPORT bool Dart_IsClosure(Dart_Handle object); DART_EXPORT bool Dart_IsTypedData(Dart_Handle object); DART_EXPORT bool Dart_IsByteBuffer(Dart_Handle object); DART_EXPORT bool Dart_IsFuture(Dart_Handle object); /* * ========= * Instances * ========= */ /* * For the purposes of the embedding api, not all objects returned are * Dart language objects. Within the api, we use the term 'Instance' * to indicate handles which refer to true Dart language objects. * * TODO(turnidge): Reorganize the "Object" section above, pulling down * any functions that more properly belong here. */ /** * Gets the type of a Dart language object. * * \param instance Some Dart object. * * \return If no error occurs, the type is returned. Otherwise an * error handle is returned. */ DART_EXPORT Dart_Handle Dart_InstanceGetType(Dart_Handle instance); /** * Returns the name for the provided class type. * * \return A valid string handle if no error occurs during the * operation. */ DART_EXPORT Dart_Handle Dart_ClassName(Dart_Handle cls_type); /** * Returns the name for the provided function or method. * * \return A valid string handle if no error occurs during the * operation. */ DART_EXPORT Dart_Handle Dart_FunctionName(Dart_Handle function); /** * Returns a handle to the owner of a function. * * The owner of an instance method or a static method is its defining * class. The owner of a top-level function is its defining * library. The owner of the function of a non-implicit closure is the * function of the method or closure that defines the non-implicit * closure. * * \return A valid handle to the owner of the function, or an error * handle if the argument is not a valid handle to a function. */ DART_EXPORT Dart_Handle Dart_FunctionOwner(Dart_Handle function); /** * Determines whether a function handle referes to a static function * of method. * * For the purposes of the embedding API, a top-level function is * implicitly declared static. * * \param function A handle to a function or method declaration. * \param is_static Returns whether the function or method is declared static. * * \return A valid handle if no error occurs during the operation. */ DART_EXPORT Dart_Handle Dart_FunctionIsStatic(Dart_Handle function, bool* is_static); /** * Is this object a closure resulting from a tear-off (closurized method)? * * Returns true for closures produced when an ordinary method is accessed * through a getter call. Returns false otherwise, in particular for closures * produced from local function declarations. * * \param object Some Object. * * \return true if Object is a tear-off. */ DART_EXPORT bool Dart_IsTearOff(Dart_Handle object); /** * Retrieves the function of a closure. * * \return A handle to the function of the closure, or an error handle if the * argument is not a closure. */ DART_EXPORT Dart_Handle Dart_ClosureFunction(Dart_Handle closure); /** * Returns a handle to the library which contains class. * * \return A valid handle to the library with owns class, null if the class * has no library or an error handle if the argument is not a valid handle * to a class type. */ DART_EXPORT Dart_Handle Dart_ClassLibrary(Dart_Handle cls_type); /* * ============================= * Numbers, Integers and Doubles * ============================= */ /** * Does this Integer fit into a 64-bit signed integer? * * \param integer An integer. * \param fits Returns true if the integer fits into a 64-bit signed integer. * * \return A valid handle if no error occurs during the operation. */ DART_EXPORT Dart_Handle Dart_IntegerFitsIntoInt64(Dart_Handle integer, bool* fits); /** * Does this Integer fit into a 64-bit unsigned integer? * * \param integer An integer. * \param fits Returns true if the integer fits into a 64-bit unsigned integer. * * \return A valid handle if no error occurs during the operation. */ DART_EXPORT Dart_Handle Dart_IntegerFitsIntoUint64(Dart_Handle integer, bool* fits); /** * Returns an Integer with the provided value. * * \param value The value of the integer. * * \return The Integer object if no error occurs. Otherwise returns * an error handle. */ DART_EXPORT Dart_Handle Dart_NewInteger(int64_t value); /** * Returns an Integer with the provided value. * * \param value The unsigned value of the integer. * * \return The Integer object if no error occurs. Otherwise returns * an error handle. */ DART_EXPORT Dart_Handle Dart_NewIntegerFromUint64(uint64_t value); /** * Returns an Integer with the provided value. * * \param value The value of the integer represented as a C string * containing a hexadecimal number. * * \return The Integer object if no error occurs. Otherwise returns * an error handle. */ DART_EXPORT Dart_Handle Dart_NewIntegerFromHexCString(const char* value); /** * Gets the value of an Integer. * * The integer must fit into a 64-bit signed integer, otherwise an error occurs. * * \param integer An Integer. * \param value Returns the value of the Integer. * * \return A valid handle if no error occurs during the operation. */ DART_EXPORT Dart_Handle Dart_IntegerToInt64(Dart_Handle integer, int64_t* value); /** * Gets the value of an Integer. * * The integer must fit into a 64-bit unsigned integer, otherwise an * error occurs. * * \param integer An Integer. * \param value Returns the value of the Integer. * * \return A valid handle if no error occurs during the operation. */ DART_EXPORT Dart_Handle Dart_IntegerToUint64(Dart_Handle integer, uint64_t* value); /** * Gets the value of an integer as a hexadecimal C string. * * \param integer An Integer. * \param value Returns the value of the Integer as a hexadecimal C * string. This C string is scope allocated and is only valid until * the next call to Dart_ExitScope. * * \return A valid handle if no error occurs during the operation. */ DART_EXPORT Dart_Handle Dart_IntegerToHexCString(Dart_Handle integer, const char** value); /** * Returns a Double with the provided value. * * \param value A double. * * \return The Double object if no error occurs. Otherwise returns * an error handle. */ DART_EXPORT Dart_Handle Dart_NewDouble(double value); /** * Gets the value of a Double * * \param double_obj A Double * \param value Returns the value of the Double. * * \return A valid handle if no error occurs during the operation. */ DART_EXPORT Dart_Handle Dart_DoubleValue(Dart_Handle double_obj, double* value); /** * Returns a closure of static function 'function_name' in the class 'class_name' * in the exported namespace of specified 'library'. * * \param library Library object * \param cls_type Type object representing a Class * \param function_name Name of the static function in the class * * \return A valid Dart instance if no error occurs during the operation. */ DART_EXPORT Dart_Handle Dart_GetStaticMethodClosure(Dart_Handle library, Dart_Handle cls_type, Dart_Handle function_name); /* * ======== * Booleans * ======== */ /** * Returns the True object. * * Requires there to be a current isolate. * * \return A handle to the True object. */ DART_EXPORT Dart_Handle Dart_True(); /** * Returns the False object. * * Requires there to be a current isolate. * * \return A handle to the False object. */ DART_EXPORT Dart_Handle Dart_False(); /** * Returns a Boolean with the provided value. * * \param value true or false. * * \return The Boolean object if no error occurs. Otherwise returns * an error handle. */ DART_EXPORT Dart_Handle Dart_NewBoolean(bool value); /** * Gets the value of a Boolean * * \param boolean_obj A Boolean * \param value Returns the value of the Boolean. * * \return A valid handle if no error occurs during the operation. */ DART_EXPORT Dart_Handle Dart_BooleanValue(Dart_Handle boolean_obj, bool* value); /* * ======= * Strings * ======= */ /** * Gets the length of a String. * * \param str A String. * \param length Returns the length of the String. * * \return A valid handle if no error occurs during the operation. */ DART_EXPORT Dart_Handle Dart_StringLength(Dart_Handle str, intptr_t* length); /** * Returns a String built from the provided C string * (There is an implicit assumption that the C string passed in contains * UTF-8 encoded characters and '\0' is considered as a termination * character). * * \param value A C String * * \return The String object if no error occurs. Otherwise returns * an error handle. */ DART_EXPORT Dart_Handle Dart_NewStringFromCString(const char* str); /* TODO(turnidge): Document what happens when we run out of memory * during this call. */ /** * Returns a String built from an array of UTF-8 encoded characters. * * \param utf8_array An array of UTF-8 encoded characters. * \param length The length of the codepoints array. * * \return The String object if no error occurs. Otherwise returns * an error handle. */ DART_EXPORT Dart_Handle Dart_NewStringFromUTF8(const uint8_t* utf8_array, intptr_t length); /** * Returns a String built from an array of UTF-16 encoded characters. * * \param utf16_array An array of UTF-16 encoded characters. * \param length The length of the codepoints array. * * \return The String object if no error occurs. Otherwise returns * an error handle. */ DART_EXPORT Dart_Handle Dart_NewStringFromUTF16(const uint16_t* utf16_array, intptr_t length); /** * Returns a String built from an array of UTF-32 encoded characters. * * \param utf32_array An array of UTF-32 encoded characters. * \param length The length of the codepoints array. * * \return The String object if no error occurs. Otherwise returns * an error handle. */ DART_EXPORT Dart_Handle Dart_NewStringFromUTF32(const int32_t* utf32_array, intptr_t length); /** * Returns a String which references an external array of * Latin-1 (ISO-8859-1) encoded characters. * * \param latin1_array Array of Latin-1 encoded characters. This must not move. * \param length The length of the characters array. * \param peer An external pointer to associate with this string. * \param external_allocation_size The number of externally allocated * bytes for peer. Used to inform the garbage collector. * \param callback A callback to be called when this string is finalized. * * \return The String object if no error occurs. Otherwise returns * an error handle. */ DART_EXPORT Dart_Handle Dart_NewExternalLatin1String(const uint8_t* latin1_array, intptr_t length, void* peer, intptr_t external_allocation_size, Dart_HandleFinalizer callback); /** * Returns a String which references an external array of UTF-16 encoded * characters. * * \param utf16_array An array of UTF-16 encoded characters. This must not move. * \param length The length of the characters array. * \param peer An external pointer to associate with this string. * \param external_allocation_size The number of externally allocated * bytes for peer. Used to inform the garbage collector. * \param callback A callback to be called when this string is finalized. * * \return The String object if no error occurs. Otherwise returns * an error handle. */ DART_EXPORT Dart_Handle Dart_NewExternalUTF16String(const uint16_t* utf16_array, intptr_t length, void* peer, intptr_t external_allocation_size, Dart_HandleFinalizer callback); /** * Gets the C string representation of a String. * (It is a sequence of UTF-8 encoded values with a '\0' termination.) * * \param str A string. * \param cstr Returns the String represented as a C string. * This C string is scope allocated and is only valid until * the next call to Dart_ExitScope. * * \return A valid handle if no error occurs during the operation. */ DART_EXPORT Dart_Handle Dart_StringToCString(Dart_Handle str, const char** cstr); /** * Gets a UTF-8 encoded representation of a String. * * Any unpaired surrogate code points in the string will be converted as * replacement characters (U+FFFD, 0xEF 0xBF 0xBD in UTF-8). If you need * to preserve unpaired surrogates, use the Dart_StringToUTF16 function. * * \param str A string. * \param utf8_array Returns the String represented as UTF-8 code * units. This UTF-8 array is scope allocated and is only valid * until the next call to Dart_ExitScope. * \param length Used to return the length of the array which was * actually used. * * \return A valid handle if no error occurs during the operation. */ DART_EXPORT Dart_Handle Dart_StringToUTF8(Dart_Handle str, uint8_t** utf8_array, intptr_t* length); /** * Gets the data corresponding to the string object. This function returns * the data only for Latin-1 (ISO-8859-1) string objects. For all other * string objects it returns an error. * * \param str A string. * \param latin1_array An array allocated by the caller, used to return * the string data. * \param length Used to pass in the length of the provided array. * Used to return the length of the array which was actually used. * * \return A valid handle if no error occurs during the operation. */ DART_EXPORT Dart_Handle Dart_StringToLatin1(Dart_Handle str, uint8_t* latin1_array, intptr_t* length); /** * Gets the UTF-16 encoded representation of a string. * * \param str A string. * \param utf16_array An array allocated by the caller, used to return * the array of UTF-16 encoded characters. * \param length Used to pass in the length of the provided array. * Used to return the length of the array which was actually used. * * \return A valid handle if no error occurs during the operation. */ DART_EXPORT Dart_Handle Dart_StringToUTF16(Dart_Handle str, uint16_t* utf16_array, intptr_t* length); /** * Gets the storage size in bytes of a String. * * \param str A String. * \param length Returns the storage size in bytes of the String. * This is the size in bytes needed to store the String. * * \return A valid handle if no error occurs during the operation. */ DART_EXPORT Dart_Handle Dart_StringStorageSize(Dart_Handle str, intptr_t* size); /** * Retrieves some properties associated with a String. * Properties retrieved are: * - character size of the string (one or two byte) * - length of the string * - peer pointer of string if it is an external string. * \param str A String. * \param char_size Returns the character size of the String. * \param str_len Returns the length of the String. * \param peer Returns the peer pointer associated with the String or 0 if * there is no peer pointer for it. * \return Success if no error occurs. Otherwise returns * an error handle. */ DART_EXPORT Dart_Handle Dart_StringGetProperties(Dart_Handle str, intptr_t* char_size, intptr_t* str_len, void** peer); /* * ===== * Lists * ===== */ /** * Returns a List<dynamic> of the desired length. * * \param length The length of the list. * * \return The List object if no error occurs. Otherwise returns * an error handle. */ DART_EXPORT Dart_Handle Dart_NewList(intptr_t length); typedef enum { Dart_CoreType_Dynamic, Dart_CoreType_Int, Dart_CoreType_String, } Dart_CoreType_Id; // TODO(bkonyi): convert this to use nullable types once NNBD is enabled. /** * Returns a List of the desired length with the desired legacy element type. * * \param element_type_id The type of elements of the list. * \param length The length of the list. * * \return The List object if no error occurs. Otherwise returns an error * handle. */ DART_EXPORT Dart_Handle Dart_NewListOf(Dart_CoreType_Id element_type_id, intptr_t length); /** * Returns a List of the desired length with the desired element type. * * \param element_type Handle to a nullable type object. E.g., from * Dart_GetType or Dart_GetNullableType. * * \param length The length of the list. * * \return The List object if no error occurs. Otherwise returns * an error handle. */ DART_EXPORT Dart_Handle Dart_NewListOfType(Dart_Handle element_type, intptr_t length); /** * Returns a List of the desired length with the desired element type, filled * with the provided object. * * \param element_type Handle to a type object. E.g., from Dart_GetType. * * \param fill_object Handle to an object of type 'element_type' that will be * used to populate the list. This parameter can only be Dart_Null() if the * length of the list is 0 or 'element_type' is a nullable type. * * \param length The length of the list. * * \return The List object if no error occurs. Otherwise returns * an error handle. */ DART_EXPORT Dart_Handle Dart_NewListOfTypeFilled(Dart_Handle element_type, Dart_Handle fill_object, intptr_t length); /** * Gets the length of a List. * * May generate an unhandled exception error. * * \param list A List. * \param length Returns the length of the List. * * \return A valid handle if no error occurs during the operation. */ DART_EXPORT Dart_Handle Dart_ListLength(Dart_Handle list, intptr_t* length); /** * Gets the Object at some index of a List. * * If the index is out of bounds, an error occurs. * * May generate an unhandled exception error. * * \param list A List. * \param index A valid index into the List. * * \return The Object in the List at the specified index if no error * occurs. Otherwise returns an error handle. */ DART_EXPORT Dart_Handle Dart_ListGetAt(Dart_Handle list, intptr_t index); /** * Gets a range of Objects from a List. * * If any of the requested index values are out of bounds, an error occurs. * * May generate an unhandled exception error. * * \param list A List. * \param offset The offset of the first item to get. * \param length The number of items to get. * \param result A pointer to fill with the objects. * * \return Success if no error occurs during the operation. */ DART_EXPORT Dart_Handle Dart_ListGetRange(Dart_Handle list, intptr_t offset, intptr_t length, Dart_Handle* result); /** * Sets the Object at some index of a List. * * If the index is out of bounds, an error occurs. * * May generate an unhandled exception error. * * \param array A List. * \param index A valid index into the List. * \param value The Object to put in the List. * * \return A valid handle if no error occurs during the operation. */ DART_EXPORT Dart_Handle Dart_ListSetAt(Dart_Handle list, intptr_t index, Dart_Handle value); /** * May generate an unhandled exception error. */ DART_EXPORT Dart_Handle Dart_ListGetAsBytes(Dart_Handle list, intptr_t offset, uint8_t* native_array, intptr_t length); /** * May generate an unhandled exception error. */ DART_EXPORT Dart_Handle Dart_ListSetAsBytes(Dart_Handle list, intptr_t offset, const uint8_t* native_array, intptr_t length); /* * ==== * Maps * ==== */ /** * Gets the Object at some key of a Map. * * May generate an unhandled exception error. * * \param map A Map. * \param key An Object. * * \return The value in the map at the specified key, null if the map does not * contain the key, or an error handle. */ DART_EXPORT Dart_Handle Dart_MapGetAt(Dart_Handle map, Dart_Handle key); /** * Returns whether the Map contains a given key. * * May generate an unhandled exception error. * * \param map A Map. * * \return A handle on a boolean indicating whether map contains the key. * Otherwise returns an error handle. */ DART_EXPORT Dart_Handle Dart_MapContainsKey(Dart_Handle map, Dart_Handle key); /** * Gets the list of keys of a Map. * * May generate an unhandled exception error. * * \param map A Map. * * \return The list of key Objects if no error occurs. Otherwise returns an * error handle. */ DART_EXPORT Dart_Handle Dart_MapKeys(Dart_Handle map); /* * ========== * Typed Data * ========== */ typedef enum { Dart_TypedData_kByteData = 0, Dart_TypedData_kInt8, Dart_TypedData_kUint8, Dart_TypedData_kUint8Clamped, Dart_TypedData_kInt16, Dart_TypedData_kUint16, Dart_TypedData_kInt32, Dart_TypedData_kUint32, Dart_TypedData_kInt64, Dart_TypedData_kUint64, Dart_TypedData_kFloat32, Dart_TypedData_kFloat64, Dart_TypedData_kInt32x4, Dart_TypedData_kFloat32x4, Dart_TypedData_kFloat64x2, Dart_TypedData_kInvalid } Dart_TypedData_Type; /** * Return type if this object is a TypedData object. * * \return kInvalid if the object is not a TypedData object or the appropriate * Dart_TypedData_Type. */ DART_EXPORT Dart_TypedData_Type Dart_GetTypeOfTypedData(Dart_Handle object); /** * Return type if this object is an external TypedData object. * * \return kInvalid if the object is not an external TypedData object or * the appropriate Dart_TypedData_Type. */ DART_EXPORT Dart_TypedData_Type Dart_GetTypeOfExternalTypedData(Dart_Handle object); /** * Returns a TypedData object of the desired length and type. * * \param type The type of the TypedData object. * \param length The length of the TypedData object (length in type units). * * \return The TypedData object if no error occurs. Otherwise returns * an error handle. */ DART_EXPORT Dart_Handle Dart_NewTypedData(Dart_TypedData_Type type, intptr_t length); /** * Returns a TypedData object which references an external data array. * * \param type The type of the data array. * \param data A data array. This array must not move. * \param length The length of the data array (length in type units). * * \return The TypedData object if no error occurs. Otherwise returns * an error handle. */ DART_EXPORT Dart_Handle Dart_NewExternalTypedData(Dart_TypedData_Type type, void* data, intptr_t length); /** * Returns a TypedData object which references an external data array. * * \param type The type of the data array. * \param data A data array. This array must not move. * \param length The length of the data array (length in type units). * \param peer A pointer to a native object or NULL. This value is * provided to callback when it is invoked. * \param external_allocation_size The number of externally allocated * bytes for peer. Used to inform the garbage collector. * \param callback A function pointer that will be invoked sometime * after the object is garbage collected, unless the handle has been deleted. * A valid callback needs to be specified it cannot be NULL. * * \return The TypedData object if no error occurs. Otherwise returns * an error handle. */ DART_EXPORT Dart_Handle Dart_NewExternalTypedDataWithFinalizer(Dart_TypedData_Type type, void* data, intptr_t length, void* peer, intptr_t external_allocation_size, Dart_HandleFinalizer callback); /** * Returns a ByteBuffer object for the typed data. * * \param type_data The TypedData object. * * \return The ByteBuffer object if no error occurs. Otherwise returns * an error handle. */ DART_EXPORT Dart_Handle Dart_NewByteBuffer(Dart_Handle typed_data); /** * Acquires access to the internal data address of a TypedData object. * * \param object The typed data object whose internal data address is to * be accessed. * \param type The type of the object is returned here. * \param data The internal data address is returned here. * \param len Size of the typed array is returned here. * * Notes: * When the internal address of the object is acquired any calls to a * Dart API function that could potentially allocate an object or run * any Dart code will return an error. * * Any Dart API functions for accessing the data should not be called * before the corresponding release. In particular, the object should * not be acquired again before its release. This leads to undefined * behavior. * * \return Success if the internal data address is acquired successfully. * Otherwise, returns an error handle. */ DART_EXPORT Dart_Handle Dart_TypedDataAcquireData(Dart_Handle object, Dart_TypedData_Type* type, void** data, intptr_t* len); /** * Releases access to the internal data address that was acquired earlier using * Dart_TypedDataAcquireData. * * \param object The typed data object whose internal data address is to be * released. * * \return Success if the internal data address is released successfully. * Otherwise, returns an error handle. */ DART_EXPORT Dart_Handle Dart_TypedDataReleaseData(Dart_Handle object); /** * Returns the TypedData object associated with the ByteBuffer object. * * \param byte_buffer The ByteBuffer object. * * \return The TypedData object if no error occurs. Otherwise returns * an error handle. */ DART_EXPORT Dart_Handle Dart_GetDataFromByteBuffer(Dart_Handle byte_buffer); /* * ============================================================ * Invoking Constructors, Methods, Closures and Field accessors * ============================================================ */ /** * Invokes a constructor, creating a new object. * * This function allows hidden constructors (constructors with leading * underscores) to be called. * * \param type Type of object to be constructed. * \param constructor_name The name of the constructor to invoke. Use * Dart_Null() or Dart_EmptyString() to invoke the unnamed constructor. * This name should not include the name of the class. * \param number_of_arguments Size of the arguments array. * \param arguments An array of arguments to the constructor. * * \return If the constructor is called and completes successfully, * then the new object. If an error occurs during execution, then an * error handle is returned. */ DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle Dart_New(Dart_Handle type, Dart_Handle constructor_name, int number_of_arguments, Dart_Handle* arguments); /** * Allocate a new object without invoking a constructor. * * \param type The type of an object to be allocated. * * \return The new object. If an error occurs during execution, then an * error handle is returned. */ DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle Dart_Allocate(Dart_Handle type); /** * Allocate a new object without invoking a constructor, and sets specified * native fields. * * \param type The type of an object to be allocated. * \param num_native_fields The number of native fields to set. * \param native_fields An array containing the value of native fields. * * \return The new object. If an error occurs during execution, then an * error handle is returned. */ DART_EXPORT Dart_Handle Dart_AllocateWithNativeFields(Dart_Handle type, intptr_t num_native_fields, const intptr_t* native_fields); /** * Invokes a method or function. * * The 'target' parameter may be an object, type, or library. If * 'target' is an object, then this function will invoke an instance * method. If 'target' is a type, then this function will invoke a * static method. If 'target' is a library, then this function will * invoke a top-level function from that library. * NOTE: This API call cannot be used to invoke methods of a type object. * * This function ignores visibility (leading underscores in names). * * May generate an unhandled exception error. * * \param target An object, type, or library. * \param name The name of the function or method to invoke. * \param number_of_arguments Size of the arguments array. * \param arguments An array of arguments to the function. * * \return If the function or method is called and completes * successfully, then the return value is returned. If an error * occurs during execution, then an error handle is returned. */ DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle Dart_Invoke(Dart_Handle target, Dart_Handle name, int number_of_arguments, Dart_Handle* arguments); /* TODO(turnidge): Document how to invoke operators. */ /** * Invokes a Closure with the given arguments. * * May generate an unhandled exception error. * * \return If no error occurs during execution, then the result of * invoking the closure is returned. If an error occurs during * execution, then an error handle is returned. */ DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle Dart_InvokeClosure(Dart_Handle closure, int number_of_arguments, Dart_Handle* arguments); /** * Invokes a Generative Constructor on an object that was previously * allocated using Dart_Allocate/Dart_AllocateWithNativeFields. * * The 'target' parameter must be an object. * * This function ignores visibility (leading underscores in names). * * May generate an unhandled exception error. * * \param target An object. * \param name The name of the constructor to invoke. * Use Dart_Null() or Dart_EmptyString() to invoke the unnamed constructor. * \param number_of_arguments Size of the arguments array. * \param arguments An array of arguments to the function. * * \return If the constructor is called and completes * successfully, then the object is returned. If an error * occurs during execution, then an error handle is returned. */ DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle Dart_InvokeConstructor(Dart_Handle object, Dart_Handle name, int number_of_arguments, Dart_Handle* arguments); /** * Gets the value of a field. * * The 'container' parameter may be an object, type, or library. If * 'container' is an object, then this function will access an * instance field. If 'container' is a type, then this function will * access a static field. If 'container' is a library, then this * function will access a top-level variable. * NOTE: This API call cannot be used to access fields of a type object. * * This function ignores field visibility (leading underscores in names). * * May generate an unhandled exception error. * * \param container An object, type, or library. * \param name A field name. * * \return If no error occurs, then the value of the field is * returned. Otherwise an error handle is returned. */ DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle Dart_GetField(Dart_Handle container, Dart_Handle name); /** * Sets the value of a field. * * The 'container' parameter may actually be an object, type, or * library. If 'container' is an object, then this function will * access an instance field. If 'container' is a type, then this * function will access a static field. If 'container' is a library, * then this function will access a top-level variable. * NOTE: This API call cannot be used to access fields of a type object. * * This function ignores field visibility (leading underscores in names). * * May generate an unhandled exception error. * * \param container An object, type, or library. * \param name A field name. * \param value The new field value. * * \return A valid handle if no error occurs. */ DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle Dart_SetField(Dart_Handle container, Dart_Handle name, Dart_Handle value); /* * ========== * Exceptions * ========== */ /* * TODO(turnidge): Remove these functions from the api and replace all * uses with Dart_NewUnhandledExceptionError. */ /** * Throws an exception. * * This function causes a Dart language exception to be thrown. This * will proceed in the standard way, walking up Dart frames until an * appropriate 'catch' block is found, executing 'finally' blocks, * etc. * * If an error handle is passed into this function, the error is * propagated immediately. See Dart_PropagateError for a discussion * of error propagation. * * If successful, this function does not return. Note that this means * that the destructors of any stack-allocated C++ objects will not be * called. If there are no Dart frames on the stack, an error occurs. * * \return An error handle if the exception was not thrown. * Otherwise the function does not return. */ DART_EXPORT Dart_Handle Dart_ThrowException(Dart_Handle exception); /** * Rethrows an exception. * * Rethrows an exception, unwinding all dart frames on the stack. If * successful, this function does not return. Note that this means * that the destructors of any stack-allocated C++ objects will not be * called. If there are no Dart frames on the stack, an error occurs. * * \return An error handle if the exception was not thrown. * Otherwise the function does not return. */ DART_EXPORT Dart_Handle Dart_ReThrowException(Dart_Handle exception, Dart_Handle stacktrace); /* * =========================== * Native fields and functions * =========================== */ /** * Gets the number of native instance fields in an object. */ DART_EXPORT Dart_Handle Dart_GetNativeInstanceFieldCount(Dart_Handle obj, int* count); /** * Gets the value of a native field. * * TODO(turnidge): Document. */ DART_EXPORT Dart_Handle Dart_GetNativeInstanceField(Dart_Handle obj, int index, intptr_t* value); /** * Sets the value of a native field. * * TODO(turnidge): Document. */ DART_EXPORT Dart_Handle Dart_SetNativeInstanceField(Dart_Handle obj, int index, intptr_t value); /** * The arguments to a native function. * * This object is passed to a native function to represent its * arguments and return value. It allows access to the arguments to a * native function by index. It also allows the return value of a * native function to be set. */ typedef struct _Dart_NativeArguments* Dart_NativeArguments; /** * Extracts current isolate group data from the native arguments structure. */ DART_EXPORT void* Dart_GetNativeIsolateGroupData(Dart_NativeArguments args); typedef enum { Dart_NativeArgument_kBool = 0, Dart_NativeArgument_kInt32, Dart_NativeArgument_kUint32, Dart_NativeArgument_kInt64, Dart_NativeArgument_kUint64, Dart_NativeArgument_kDouble, Dart_NativeArgument_kString, Dart_NativeArgument_kInstance, Dart_NativeArgument_kNativeFields, } Dart_NativeArgument_Type; typedef struct _Dart_NativeArgument_Descriptor { uint8_t type; uint8_t index; } Dart_NativeArgument_Descriptor; typedef union _Dart_NativeArgument_Value { bool as_bool; int32_t as_int32; uint32_t as_uint32; int64_t as_int64; uint64_t as_uint64; double as_double; struct { Dart_Handle dart_str; void* peer; } as_string; struct { intptr_t num_fields; intptr_t* values; } as_native_fields; Dart_Handle as_instance; } Dart_NativeArgument_Value; enum { kNativeArgNumberPos = 0, kNativeArgNumberSize = 8, kNativeArgTypePos = kNativeArgNumberPos + kNativeArgNumberSize, kNativeArgTypeSize = 8, }; #define BITMASK(size) ((1 << size) - 1) #define DART_NATIVE_ARG_DESCRIPTOR(type, position) \ (((type & BITMASK(kNativeArgTypeSize)) << kNativeArgTypePos) | \ (position & BITMASK(kNativeArgNumberSize))) /** * Gets the native arguments based on the types passed in and populates * the passed arguments buffer with appropriate native values. * * \param args the Native arguments block passed into the native call. * \param num_arguments length of argument descriptor array and argument * values array passed in. * \param arg_descriptors an array that describes the arguments that * need to be retrieved. For each argument to be retrieved the descriptor * contains the argument number (0, 1 etc.) and the argument type * described using Dart_NativeArgument_Type, e.g: * DART_NATIVE_ARG_DESCRIPTOR(Dart_NativeArgument_kBool, 1) indicates * that the first argument is to be retrieved and it should be a boolean. * \param arg_values array into which the native arguments need to be * extracted into, the array is allocated by the caller (it could be * stack allocated to avoid the malloc/free performance overhead). * * \return Success if all the arguments could be extracted correctly, * returns an error handle if there were any errors while extracting the * arguments (mismatched number of arguments, incorrect types, etc.). */ DART_EXPORT Dart_Handle Dart_GetNativeArguments(Dart_NativeArguments args, int num_arguments, const Dart_NativeArgument_Descriptor* arg_descriptors, Dart_NativeArgument_Value* arg_values); /** * Gets the native argument at some index. */ DART_EXPORT Dart_Handle Dart_GetNativeArgument(Dart_NativeArguments args, int index); /* TODO(turnidge): Specify the behavior of an out-of-bounds access. */ /** * Gets the number of native arguments. */ DART_EXPORT int Dart_GetNativeArgumentCount(Dart_NativeArguments args); /** * Gets all the native fields of the native argument at some index. * \param args Native arguments structure. * \param arg_index Index of the desired argument in the structure above. * \param num_fields size of the intptr_t array 'field_values' passed in. * \param field_values intptr_t array in which native field values are returned. * \return Success if the native fields where copied in successfully. Otherwise * returns an error handle. On success the native field values are copied * into the 'field_values' array, if the argument at 'arg_index' is a * null object then 0 is copied as the native field values into the * 'field_values' array. */ DART_EXPORT Dart_Handle Dart_GetNativeFieldsOfArgument(Dart_NativeArguments args, int arg_index, int num_fields, intptr_t* field_values); /** * Gets the native field of the receiver. */ DART_EXPORT Dart_Handle Dart_GetNativeReceiver(Dart_NativeArguments args, intptr_t* value); /** * Gets a string native argument at some index. * \param args Native arguments structure. * \param arg_index Index of the desired argument in the structure above. * \param peer Returns the peer pointer if the string argument has one. * \return Success if the string argument has a peer, if it does not * have a peer then the String object is returned. Otherwise returns * an error handle (argument is not a String object). */ DART_EXPORT Dart_Handle Dart_GetNativeStringArgument(Dart_NativeArguments args, int arg_index, void** peer); /** * Gets an integer native argument at some index. * \param args Native arguments structure. * \param arg_index Index of the desired argument in the structure above. * \param value Returns the integer value if the argument is an Integer. * \return Success if no error occurs. Otherwise returns an error handle. */ DART_EXPORT Dart_Handle Dart_GetNativeIntegerArgument(Dart_NativeArguments args, int index, int64_t* value); /** * Gets a boolean native argument at some index. * \param args Native arguments structure. * \param arg_index Index of the desired argument in the structure above. * \param value Returns the boolean value if the argument is a Boolean. * \return Success if no error occurs. Otherwise returns an error handle. */ DART_EXPORT Dart_Handle Dart_GetNativeBooleanArgument(Dart_NativeArguments args, int index, bool* value); /** * Gets a double native argument at some index. * \param args Native arguments structure. * \param arg_index Index of the desired argument in the structure above. * \param value Returns the double value if the argument is a double. * \return Success if no error occurs. Otherwise returns an error handle. */ DART_EXPORT Dart_Handle Dart_GetNativeDoubleArgument(Dart_NativeArguments args, int index, double* value); /** * Sets the return value for a native function. * * If retval is an Error handle, then error will be propagated once * the native functions exits. See Dart_PropagateError for a * discussion of how different types of errors are propagated. */ DART_EXPORT void Dart_SetReturnValue(Dart_NativeArguments args, Dart_Handle retval); DART_EXPORT void Dart_SetWeakHandleReturnValue(Dart_NativeArguments args, Dart_WeakPersistentHandle rval); DART_EXPORT void Dart_SetBooleanReturnValue(Dart_NativeArguments args, bool retval); DART_EXPORT void Dart_SetIntegerReturnValue(Dart_NativeArguments args, int64_t retval); DART_EXPORT void Dart_SetDoubleReturnValue(Dart_NativeArguments args, double retval); /** * A native function. */ typedef void (*Dart_NativeFunction)(Dart_NativeArguments arguments); /** * Native entry resolution callback. * * For libraries and scripts which have native functions, the embedder * can provide a native entry resolver. This callback is used to map a * name/arity to a Dart_NativeFunction. If no function is found, the * callback should return NULL. * * The parameters to the native resolver function are: * \param name a Dart string which is the name of the native function. * \param num_of_arguments is the number of arguments expected by the * native function. * \param auto_setup_scope is a boolean flag that can be set by the resolver * to indicate if this function needs a Dart API scope (see Dart_EnterScope/ * Dart_ExitScope) to be setup automatically by the VM before calling into * the native function. By default most native functions would require this * to be true but some light weight native functions which do not call back * into the VM through the Dart API may not require a Dart scope to be * setup automatically. * * \return A valid Dart_NativeFunction which resolves to a native entry point * for the native function. * * See Dart_SetNativeResolver. */ typedef Dart_NativeFunction (*Dart_NativeEntryResolver)(Dart_Handle name, int num_of_arguments, bool* auto_setup_scope); /* TODO(turnidge): Consider renaming to NativeFunctionResolver or * NativeResolver. */ /** * Native entry symbol lookup callback. * * For libraries and scripts which have native functions, the embedder * can provide a callback for mapping a native entry to a symbol. This callback * maps a native function entry PC to the native function name. If no native * entry symbol can be found, the callback should return NULL. * * The parameters to the native reverse resolver function are: * \param nf A Dart_NativeFunction. * * \return A const UTF-8 string containing the symbol name or NULL. * * See Dart_SetNativeResolver. */ typedef const uint8_t* (*Dart_NativeEntrySymbol)(Dart_NativeFunction nf); /** * FFI Native C function pointer resolver callback. * * See Dart_SetFfiNativeResolver. */ typedef void* (*Dart_FfiNativeResolver)(const char* name, uintptr_t args_n); /* * =========== * Environment * =========== */ /** * An environment lookup callback function. * * \param name The name of the value to lookup in the environment. * * \return A valid handle to a string if the name exists in the * current environment or Dart_Null() if not. */ typedef Dart_Handle (*Dart_EnvironmentCallback)(Dart_Handle name); /** * Sets the environment callback for the current isolate. This * callback is used to lookup environment values by name in the * current environment. This enables the embedder to supply values for * the const constructors bool.fromEnvironment, int.fromEnvironment * and String.fromEnvironment. */ DART_EXPORT Dart_Handle Dart_SetEnvironmentCallback(Dart_EnvironmentCallback callback); /** * Sets the callback used to resolve native functions for a library. * * \param library A library. * \param resolver A native entry resolver. * * \return A valid handle if the native resolver was set successfully. */ DART_EXPORT Dart_Handle Dart_SetNativeResolver(Dart_Handle library, Dart_NativeEntryResolver resolver, Dart_NativeEntrySymbol symbol); /* TODO(turnidge): Rename to Dart_LibrarySetNativeResolver? */ /** * Returns the callback used to resolve native functions for a library. * * \param library A library. * \param resolver a pointer to a Dart_NativeEntryResolver * * \return A valid handle if the library was found. */ DART_EXPORT Dart_Handle Dart_GetNativeResolver(Dart_Handle library, Dart_NativeEntryResolver* resolver); /** * Returns the callback used to resolve native function symbols for a library. * * \param library A library. * \param resolver a pointer to a Dart_NativeEntrySymbol. * * \return A valid handle if the library was found. */ DART_EXPORT Dart_Handle Dart_GetNativeSymbol(Dart_Handle library, Dart_NativeEntrySymbol* resolver); /** * Sets the callback used to resolve FFI native functions for a library. * The resolved functions are expected to be a C function pointer of the * correct signature (as specified in the `@FfiNative<NFT>()` function * annotation in Dart code). * * NOTE: This is an experimental feature and might change in the future. * * \param library A library. * \param resolver A native function resolver. * * \return A valid handle if the native resolver was set successfully. */ DART_EXPORT Dart_Handle Dart_SetFfiNativeResolver(Dart_Handle library, Dart_FfiNativeResolver resolver); /* * ===================== * Scripts and Libraries * ===================== */ typedef enum { Dart_kCanonicalizeUrl = 0, Dart_kImportTag, Dart_kKernelTag, } Dart_LibraryTag; /** * The library tag handler is a multi-purpose callback provided by the * embedder to the Dart VM. The embedder implements the tag handler to * provide the ability to load Dart scripts and imports. * * -- TAGS -- * * Dart_kCanonicalizeUrl * * This tag indicates that the embedder should canonicalize 'url' with * respect to 'library'. For most embedders, the * Dart_DefaultCanonicalizeUrl function is a sufficient implementation * of this tag. The return value should be a string holding the * canonicalized url. * * Dart_kImportTag * * This tag is used to load a library from IsolateMirror.loadUri. The embedder * should call Dart_LoadLibraryFromKernel to provide the library to the VM. The * return value should be an error or library (the result from * Dart_LoadLibraryFromKernel). * * Dart_kKernelTag * * This tag is used to load the intermediate file (kernel) generated by * the Dart front end. This tag is typically used when a 'hot-reload' * of an application is needed and the VM is 'use dart front end' mode. * The dart front end typically compiles all the scripts, imports and part * files into one intermediate file hence we don't use the source/import or * script tags. The return value should be an error or a TypedData containing * the kernel bytes. * */ typedef Dart_Handle (*Dart_LibraryTagHandler)( Dart_LibraryTag tag, Dart_Handle library_or_package_map_url, Dart_Handle url); /** * Sets library tag handler for the current isolate. This handler is * used to handle the various tags encountered while loading libraries * or scripts in the isolate. * * \param handler Handler code to be used for handling the various tags * encountered while loading libraries or scripts in the isolate. * * \return If no error occurs, the handler is set for the isolate. * Otherwise an error handle is returned. * * TODO(turnidge): Document. */ DART_EXPORT Dart_Handle Dart_SetLibraryTagHandler(Dart_LibraryTagHandler handler); /** * Handles deferred loading requests. When this handler is invoked, it should * eventually load the deferred loading unit with the given id and call * Dart_DeferredLoadComplete or Dart_DeferredLoadCompleteError. It is * recommended that the loading occur asynchronously, but it is permitted to * call Dart_DeferredLoadComplete or Dart_DeferredLoadCompleteError before the * handler returns. * * If an error is returned, it will be propogated through * `prefix.loadLibrary()`. This is useful for synchronous * implementations, which must propogate any unwind errors from * Dart_DeferredLoadComplete or Dart_DeferredLoadComplete. Otherwise the handler * should return a non-error such as `Dart_Null()`. */ typedef Dart_Handle (*Dart_DeferredLoadHandler)(intptr_t loading_unit_id); /** * Sets the deferred load handler for the current isolate. This handler is * used to handle loading deferred imports in an AppJIT or AppAOT program. */ DART_EXPORT Dart_Handle Dart_SetDeferredLoadHandler(Dart_DeferredLoadHandler handler); /** * Notifies the VM that a deferred load completed successfully. This function * will eventually cause the corresponding `prefix.loadLibrary()` futures to * complete. * * Requires the current isolate to be the same current isolate during the * invocation of the Dart_DeferredLoadHandler. */ DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle Dart_DeferredLoadComplete(intptr_t loading_unit_id, const uint8_t* snapshot_data, const uint8_t* snapshot_instructions); /** * Notifies the VM that a deferred load failed. This function * will eventually cause the corresponding `prefix.loadLibrary()` futures to * complete with an error. * * If `transient` is true, future invocations of `prefix.loadLibrary()` will * trigger new load requests. If false, futures invocation will complete with * the same error. * * Requires the current isolate to be the same current isolate during the * invocation of the Dart_DeferredLoadHandler. */ DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle Dart_DeferredLoadCompleteError(intptr_t loading_unit_id, const char* error_message, bool transient); /** * Canonicalizes a url with respect to some library. * * The url is resolved with respect to the library's url and some url * normalizations are performed. * * This canonicalization function should be sufficient for most * embedders to implement the Dart_kCanonicalizeUrl tag. * * \param base_url The base url relative to which the url is * being resolved. * \param url The url being resolved and canonicalized. This * parameter is a string handle. * * \return If no error occurs, a String object is returned. Otherwise * an error handle is returned. */ DART_EXPORT Dart_Handle Dart_DefaultCanonicalizeUrl(Dart_Handle base_url, Dart_Handle url); /** * Loads the root library for the current isolate. * * Requires there to be no current root library. * * \param buffer A buffer which contains a kernel binary (see * pkg/kernel/binary.md). Must remain valid until isolate group shutdown. * \param buffer_size Length of the passed in buffer. * * \return A handle to the root library, or an error. */ DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle Dart_LoadScriptFromKernel(const uint8_t* kernel_buffer, intptr_t kernel_size); /** * Gets the library for the root script for the current isolate. * * If the root script has not yet been set for the current isolate, * this function returns Dart_Null(). This function never returns an * error handle. * * \return Returns the root Library for the current isolate or Dart_Null(). */ DART_EXPORT Dart_Handle Dart_RootLibrary(); /** * Sets the root library for the current isolate. * * \return Returns an error handle if `library` is not a library handle. */ DART_EXPORT Dart_Handle Dart_SetRootLibrary(Dart_Handle library); /** * Lookup or instantiate a legacy type by name and type arguments from a * Library. * * \param library The library containing the class or interface. * \param class_name The class name for the type. * \param number_of_type_arguments Number of type arguments. * For non parametric types the number of type arguments would be 0. * \param type_arguments Pointer to an array of type arguments. * For non parameteric types a NULL would be passed in for this argument. * * \return If no error occurs, the type is returned. * Otherwise an error handle is returned. */ DART_EXPORT Dart_Handle Dart_GetType(Dart_Handle library, Dart_Handle class_name, intptr_t number_of_type_arguments, Dart_Handle* type_arguments); /** * Lookup or instantiate a nullable type by name and type arguments from * Library. * * \param library The library containing the class or interface. * \param class_name The class name for the type. * \param number_of_type_arguments Number of type arguments. * For non parametric types the number of type arguments would be 0. * \param type_arguments Pointer to an array of type arguments. * For non parameteric types a NULL would be passed in for this argument. * * \return If no error occurs, the type is returned. * Otherwise an error handle is returned. */ DART_EXPORT Dart_Handle Dart_GetNullableType(Dart_Handle library, Dart_Handle class_name, intptr_t number_of_type_arguments, Dart_Handle* type_arguments); /** * Lookup or instantiate a non-nullable type by name and type arguments from * Library. * * \param library The library containing the class or interface. * \param class_name The class name for the type. * \param number_of_type_arguments Number of type arguments. * For non parametric types the number of type arguments would be 0. * \param type_arguments Pointer to an array of type arguments. * For non parameteric types a NULL would be passed in for this argument. * * \return If no error occurs, the type is returned. * Otherwise an error handle is returned. */ DART_EXPORT Dart_Handle Dart_GetNonNullableType(Dart_Handle library, Dart_Handle class_name, intptr_t number_of_type_arguments, Dart_Handle* type_arguments); /** * Creates a nullable version of the provided type. * * \param type The type to be converted to a nullable type. * * \return If no error occurs, a nullable type is returned. * Otherwise an error handle is returned. */ DART_EXPORT Dart_Handle Dart_TypeToNullableType(Dart_Handle type); /** * Creates a non-nullable version of the provided type. * * \param type The type to be converted to a non-nullable type. * * \return If no error occurs, a non-nullable type is returned. * Otherwise an error handle is returned. */ DART_EXPORT Dart_Handle Dart_TypeToNonNullableType(Dart_Handle type); /** * A type's nullability. * * \param type A Dart type. * \param result An out parameter containing the result of the check. True if * the type is of the specified nullability, false otherwise. * * \return Returns an error handle if type is not of type Type. */ DART_EXPORT Dart_Handle Dart_IsNullableType(Dart_Handle type, bool* result); DART_EXPORT Dart_Handle Dart_IsNonNullableType(Dart_Handle type, bool* result); DART_EXPORT Dart_Handle Dart_IsLegacyType(Dart_Handle type, bool* result); /** * Lookup a class or interface by name from a Library. * * \param library The library containing the class or interface. * \param class_name The name of the class or interface. * * \return If no error occurs, the class or interface is * returned. Otherwise an error handle is returned. */ DART_EXPORT Dart_Handle Dart_GetClass(Dart_Handle library, Dart_Handle class_name); /* TODO(asiva): The above method needs to be removed once all uses * of it are removed from the embedder code. */ /** * Returns an import path to a Library, such as "file:///test.dart" or * "dart:core". */ DART_EXPORT Dart_Handle Dart_LibraryUrl(Dart_Handle library); /** * Returns a URL from which a Library was loaded. */ DART_EXPORT Dart_Handle Dart_LibraryResolvedUrl(Dart_Handle library); /** * \return An array of libraries. */ DART_EXPORT Dart_Handle Dart_GetLoadedLibraries(); DART_EXPORT Dart_Handle Dart_LookupLibrary(Dart_Handle url); /* TODO(turnidge): Consider returning Dart_Null() when the library is * not found to distinguish that from a true error case. */ /** * Report an loading error for the library. * * \param library The library that failed to load. * \param error The Dart error instance containing the load error. * * \return If the VM handles the error, the return value is * a null handle. If it doesn't handle the error, the error * object is returned. */ DART_EXPORT Dart_Handle Dart_LibraryHandleError(Dart_Handle library, Dart_Handle error); /** * Called by the embedder to load a partial program. Does not set the root * library. * * \param buffer A buffer which contains a kernel binary (see * pkg/kernel/binary.md). Must remain valid until isolate shutdown. * \param buffer_size Length of the passed in buffer. * * \return A handle to the main library of the compilation unit, or an error. */ DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle Dart_LoadLibraryFromKernel(const uint8_t* kernel_buffer, intptr_t kernel_buffer_size); /** * Indicates that all outstanding load requests have been satisfied. * This finalizes all the new classes loaded and optionally completes * deferred library futures. * * Requires there to be a current isolate. * * \param complete_futures Specify true if all deferred library * futures should be completed, false otherwise. * * \return Success if all classes have been finalized and deferred library * futures are completed. Otherwise, returns an error. */ DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle Dart_FinalizeLoading(bool complete_futures); /* * ===== * Peers * ===== */ /** * The peer field is a lazily allocated field intended for storage of * an uncommonly used values. Most instances types can have a peer * field allocated. The exceptions are subtypes of Null, num, and * bool. */ /** * Returns the value of peer field of 'object' in 'peer'. * * \param object An object. * \param peer An out parameter that returns the value of the peer * field. * * \return Returns an error if 'object' is a subtype of Null, num, or * bool. */ DART_EXPORT Dart_Handle Dart_GetPeer(Dart_Handle object, void** peer); /** * Sets the value of the peer field of 'object' to the value of * 'peer'. * * \param object An object. * \param peer A value to store in the peer field. * * \return Returns an error if 'object' is a subtype of Null, num, or * bool. */ DART_EXPORT Dart_Handle Dart_SetPeer(Dart_Handle object, void* peer); /* * ====== * Kernel * ====== */ /** * Experimental support for Dart to Kernel parser isolate. * * TODO(hausner): Document finalized interface. * */ // TODO(33433): Remove kernel service from the embedding API. typedef enum { Dart_KernelCompilationStatus_Unknown = -1, Dart_KernelCompilationStatus_Ok = 0, Dart_KernelCompilationStatus_Error = 1, Dart_KernelCompilationStatus_Crash = 2, Dart_KernelCompilationStatus_MsgFailed = 3, } Dart_KernelCompilationStatus; typedef struct { Dart_KernelCompilationStatus status; bool null_safety; char* error; uint8_t* kernel; intptr_t kernel_size; } Dart_KernelCompilationResult; typedef enum { Dart_KernelCompilationVerbosityLevel_Error = 0, Dart_KernelCompilationVerbosityLevel_Warning, Dart_KernelCompilationVerbosityLevel_Info, Dart_KernelCompilationVerbosityLevel_All, } Dart_KernelCompilationVerbosityLevel; DART_EXPORT bool Dart_IsKernelIsolate(Dart_Isolate isolate); DART_EXPORT bool Dart_KernelIsolateIsRunning(); DART_EXPORT Dart_Port Dart_KernelPort(); /** * Compiles the given `script_uri` to a kernel file. * * \param platform_kernel A buffer containing the kernel of the platform (e.g. * `vm_platform_strong.dill`). The VM does not take ownership of this memory. * * \param platform_kernel_size The length of the platform_kernel buffer. * * \param snapshot_compile Set to `true` when the compilation is for a snapshot. * This is used by the frontend to determine if compilation related information * should be printed to console (e.g., null safety mode). * * \param verbosity Specifies the logging behavior of the kernel compilation * service. * * \return Returns the result of the compilation. * * On a successful compilation the returned [Dart_KernelCompilationResult] has * a status of [Dart_KernelCompilationStatus_Ok] and the `kernel`/`kernel_size` * fields are set. The caller takes ownership of the malloc()ed buffer. * * On a failed compilation the `error` might be set describing the reason for * the failed compilation. The caller takes ownership of the malloc()ed * error. * * Requires there to be a current isolate. */ DART_EXPORT Dart_KernelCompilationResult Dart_CompileToKernel(const char* script_uri, const uint8_t* platform_kernel, const intptr_t platform_kernel_size, bool incremental_compile, bool snapshot_compile, const char* package_config, Dart_KernelCompilationVerbosityLevel verbosity); typedef struct { const char* uri; const char* source; } Dart_SourceFile; DART_EXPORT Dart_KernelCompilationResult Dart_KernelListDependencies(); /** * Sets the kernel buffer which will be used to load Dart SDK sources * dynamically at runtime. * * \param platform_kernel A buffer containing kernel which has sources for the * Dart SDK populated. Note: The VM does not take ownership of this memory. * * \param platform_kernel_size The length of the platform_kernel buffer. */ DART_EXPORT void Dart_SetDartLibrarySourcesKernel( const uint8_t* platform_kernel, const intptr_t platform_kernel_size); /** * Detect the null safety opt-in status. * * When running from source, it is based on the opt-in status of `script_uri`. * When running from a kernel buffer, it is based on the mode used when * generating `kernel_buffer`. * When running from an appJIT or AOT snapshot, it is based on the mode used * when generating `snapshot_data`. * * \param script_uri Uri of the script that contains the source code * * \param package_config Uri of the package configuration file (either in format * of .packages or .dart_tool/package_config.json) for the null safety * detection to resolve package imports against. If this parameter is not * passed the package resolution of the parent isolate should be used. * * \param original_working_directory current working directory when the VM * process was launched, this is used to correctly resolve the path specified * for package_config. * * \param snapshot_data * * \param snapshot_instructions Buffers containing a snapshot of the * isolate or NULL if no snapshot is provided. If provided, the buffers must * remain valid until the isolate shuts down. * * \param kernel_buffer * * \param kernel_buffer_size A buffer which contains a kernel/DIL program. Must * remain valid until isolate shutdown. * * \return Returns true if the null safety is opted in by the input being * run `script_uri`, `snapshot_data` or `kernel_buffer`. * */ DART_EXPORT bool Dart_DetectNullSafety(const char* script_uri, const char* package_config, const char* original_working_directory, const uint8_t* snapshot_data, const uint8_t* snapshot_instructions, const uint8_t* kernel_buffer, intptr_t kernel_buffer_size); #define DART_KERNEL_ISOLATE_NAME "kernel-service" /* * ======= * Service * ======= */ #define DART_VM_SERVICE_ISOLATE_NAME "vm-service" /** * Returns true if isolate is the service isolate. * * \param isolate An isolate * * \return Returns true if 'isolate' is the service isolate. */ DART_EXPORT bool Dart_IsServiceIsolate(Dart_Isolate isolate); /** * Writes the CPU profile to the timeline as a series of 'instant' events. * * Note that this is an expensive operation. * * \param main_port The main port of the Isolate whose profile samples to write. * \param error An optional error, must be free()ed by caller. * * \return Returns true if the profile is successfully written and false * otherwise. */ DART_EXPORT bool Dart_WriteProfileToTimeline(Dart_Port main_port, char** error); /* * ============== * Precompilation * ============== */ /** * Compiles all functions reachable from entry points and marks * the isolate to disallow future compilation. * * Entry points should be specified using `@pragma("vm:entry-point")` * annotation. * * \return An error handle if a compilation error or runtime error running const * constructors was encountered. */ DART_EXPORT Dart_Handle Dart_Precompile(); typedef void (*Dart_CreateLoadingUnitCallback)( void* callback_data, intptr_t loading_unit_id, void** write_callback_data, void** write_debug_callback_data); typedef void (*Dart_StreamingWriteCallback)(void* callback_data, const uint8_t* buffer, intptr_t size); typedef void (*Dart_StreamingCloseCallback)(void* callback_data); DART_EXPORT Dart_Handle Dart_LoadingUnitLibraryUris(intptr_t loading_unit_id); // On Darwin systems, 'dlsym' adds an '_' to the beginning of the symbol name. // Use the '...CSymbol' definitions for resolving through 'dlsym'. The actual // symbol names in the objects are given by the '...AsmSymbol' definitions. #if defined(__APPLE__) #define kSnapshotBuildIdCSymbol "kDartSnapshotBuildId" #define kVmSnapshotDataCSymbol "kDartVmSnapshotData" #define kVmSnapshotInstructionsCSymbol "kDartVmSnapshotInstructions" #define kVmSnapshotBssCSymbol "kDartVmSnapshotBss" #define kIsolateSnapshotDataCSymbol "kDartIsolateSnapshotData" #define kIsolateSnapshotInstructionsCSymbol "kDartIsolateSnapshotInstructions" #define kIsolateSnapshotBssCSymbol "kDartIsolateSnapshotBss" #else #define kSnapshotBuildIdCSymbol "_kDartSnapshotBuildId" #define kVmSnapshotDataCSymbol "_kDartVmSnapshotData" #define kVmSnapshotInstructionsCSymbol "_kDartVmSnapshotInstructions" #define kVmSnapshotBssCSymbol "_kDartVmSnapshotBss" #define kIsolateSnapshotDataCSymbol "_kDartIsolateSnapshotData" #define kIsolateSnapshotInstructionsCSymbol "_kDartIsolateSnapshotInstructions" #define kIsolateSnapshotBssCSymbol "_kDartIsolateSnapshotBss" #endif #define kSnapshotBuildIdAsmSymbol "_kDartSnapshotBuildId" #define kVmSnapshotDataAsmSymbol "_kDartVmSnapshotData" #define kVmSnapshotInstructionsAsmSymbol "_kDartVmSnapshotInstructions" #define kVmSnapshotBssAsmSymbol "_kDartVmSnapshotBss" #define kIsolateSnapshotDataAsmSymbol "_kDartIsolateSnapshotData" #define kIsolateSnapshotInstructionsAsmSymbol \ "_kDartIsolateSnapshotInstructions" #define kIsolateSnapshotBssAsmSymbol "_kDartIsolateSnapshotBss" /** * Creates a precompiled snapshot. * - A root library must have been loaded. * - Dart_Precompile must have been called. * * Outputs an assembly file defining the symbols listed in the definitions * above. * * The assembly should be compiled as a static or shared library and linked or * loaded by the embedder. Running this snapshot requires a VM compiled with * DART_PRECOMPILED_SNAPSHOT. The kDartVmSnapshotData and * kDartVmSnapshotInstructions should be passed to Dart_Initialize. The * kDartIsolateSnapshotData and kDartIsolateSnapshotInstructions should be * passed to Dart_CreateIsolateGroup. * * The callback will be invoked one or more times to provide the assembly code. * * If stripped is true, then the assembly code will not include DWARF * debugging sections. * * If debug_callback_data is provided, debug_callback_data will be used with * the callback to provide separate debugging information. * * \return A valid handle if no error occurs during the operation. */ DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle Dart_CreateAppAOTSnapshotAsAssembly(Dart_StreamingWriteCallback callback, void* callback_data, bool stripped, void* debug_callback_data); DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle Dart_CreateAppAOTSnapshotAsAssemblies( Dart_CreateLoadingUnitCallback next_callback, void* next_callback_data, bool stripped, Dart_StreamingWriteCallback write_callback, Dart_StreamingCloseCallback close_callback); /** * Creates a precompiled snapshot. * - A root library must have been loaded. * - Dart_Precompile must have been called. * * Outputs an ELF shared library defining the symbols * - _kDartVmSnapshotData * - _kDartVmSnapshotInstructions * - _kDartIsolateSnapshotData * - _kDartIsolateSnapshotInstructions * * The shared library should be dynamically loaded by the embedder. * Running this snapshot requires a VM compiled with DART_PRECOMPILED_SNAPSHOT. * The kDartVmSnapshotData and kDartVmSnapshotInstructions should be passed to * Dart_Initialize. The kDartIsolateSnapshotData and * kDartIsolateSnapshotInstructions should be passed to Dart_CreateIsolate. * * The callback will be invoked one or more times to provide the binary output. * * If stripped is true, then the binary output will not include DWARF * debugging sections. * * If debug_callback_data is provided, debug_callback_data will be used with * the callback to provide separate debugging information. * * \return A valid handle if no error occurs during the operation. */ DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle Dart_CreateAppAOTSnapshotAsElf(Dart_StreamingWriteCallback callback, void* callback_data, bool stripped, void* debug_callback_data); DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle Dart_CreateAppAOTSnapshotAsElfs(Dart_CreateLoadingUnitCallback next_callback, void* next_callback_data, bool stripped, Dart_StreamingWriteCallback write_callback, Dart_StreamingCloseCallback close_callback); /** * Like Dart_CreateAppAOTSnapshotAsAssembly, but only includes * kDartVmSnapshotData and kDartVmSnapshotInstructions. It also does * not strip DWARF information from the generated assembly or allow for * separate debug information. */ DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle Dart_CreateVMAOTSnapshotAsAssembly(Dart_StreamingWriteCallback callback, void* callback_data); /** * Sorts the class-ids in depth first traversal order of the inheritance * tree. This is a costly operation, but it can make method dispatch * more efficient and is done before writing snapshots. * * \return A valid handle if no error occurs during the operation. */ DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle Dart_SortClasses(); /** * Creates a snapshot that caches compiled code and type feedback for faster * startup and quicker warmup in a subsequent process. * * Outputs a snapshot in two pieces. The pieces should be passed to * Dart_CreateIsolateGroup in a VM using the same VM snapshot pieces used in the * current VM. The instructions piece must be loaded with read and execute * permissions; the data piece may be loaded as read-only. * * - Requires the VM to have not been started with --precompilation. * - Not supported when targeting IA32. * - The VM writing the snapshot and the VM reading the snapshot must be the * same version, must be built in the same DEBUG/RELEASE/PRODUCT mode, must * be targeting the same architecture, and must both be in checked mode or * both in unchecked mode. * * The buffers are scope allocated and are only valid until the next call to * Dart_ExitScope. * * \return A valid handle if no error occurs during the operation. */ DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle Dart_CreateAppJITSnapshotAsBlobs(uint8_t** isolate_snapshot_data_buffer, intptr_t* isolate_snapshot_data_size, uint8_t** isolate_snapshot_instructions_buffer, intptr_t* isolate_snapshot_instructions_size); /** * Like Dart_CreateAppJITSnapshotAsBlobs, but also creates a new VM snapshot. */ DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle Dart_CreateCoreJITSnapshotAsBlobs( uint8_t** vm_snapshot_data_buffer, intptr_t* vm_snapshot_data_size, uint8_t** vm_snapshot_instructions_buffer, intptr_t* vm_snapshot_instructions_size, uint8_t** isolate_snapshot_data_buffer, intptr_t* isolate_snapshot_data_size, uint8_t** isolate_snapshot_instructions_buffer, intptr_t* isolate_snapshot_instructions_size); /** * Get obfuscation map for precompiled code. * * Obfuscation map is encoded as a JSON array of pairs (original name, * obfuscated name). * * \return Returns an error handler if the VM was built in a mode that does not * support obfuscation. */ DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle Dart_GetObfuscationMap(uint8_t** buffer, intptr_t* buffer_length); /** * Returns whether the VM only supports running from precompiled snapshots and * not from any other kind of snapshot or from source (that is, the VM was * compiled with DART_PRECOMPILED_RUNTIME). */ DART_EXPORT bool Dart_IsPrecompiledRuntime(); /** * Print a native stack trace. Used for crash handling. * * If context is NULL, prints the current stack trace. Otherwise, context * should be a CONTEXT* (Windows) or ucontext_t* (POSIX) from a signal handler * running on the current thread. */ DART_EXPORT void Dart_DumpNativeStackTrace(void* context); /** * Indicate that the process is about to abort, and the Dart VM should not * attempt to cleanup resources. */ DART_EXPORT void Dart_PrepareToAbort(); #endif /* INCLUDE_DART_API_H_ */ /* NOLINT */
samples/experimental/pedometer/src/dart-sdk/include/dart_api.h/0
{ "file_path": "samples/experimental/pedometer/src/dart-sdk/include/dart_api.h", "repo_id": "samples", "token_count": 44738 }
1,386
include: package:analysis_defaults/flutter.yaml
samples/experimental/varfont_shader_puzzle/analysis_options.yaml/0
{ "file_path": "samples/experimental/varfont_shader_puzzle/analysis_options.yaml", "repo_id": "samples", "token_count": 15 }
1,387
// Copyright 2023 The Flutter team. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import '../components/components.dart'; import '../page_content/pages_flow.dart'; import '../styles.dart'; class PageNarrativePre extends NarrativePage { const PageNarrativePre({ super.key, required super.pageConfig, }); @override State<NarrativePage> createState() => _PageNarrativePreState(); } class _PageNarrativePreState extends NarrativePageState { @override void initState() { panels = [ LightboxedPanel( key: UniqueKey(), pageConfig: widget.pageConfig, fadeOnDismiss: false, onDismiss: super.handleIntroDismiss, content: [ Text( 'Welcome to your first day on the FontCo team! Are you ready to help us publish our newest font, Designer Pro?', style: TextStyles.bodyStyle(), textAlign: TextAlign.left, ), const SizedBox( height: 8, ), const Image( image: AssetImage('assets/images/specimen-1.png'), ), ], ), LightboxedPanel( key: UniqueKey(), pageConfig: widget.pageConfig, fadeOnDismiss: false, onDismiss: super.handleIntroDismiss, autoDismissAfter: 100, buildButton: false, lightBoxBgColor: Colors.black, cardBgColor: Colors.black, content: [ Transform.scale( scaleX: -1, child: Text( 'Welcome to your first day on the FontCo team! Are you ready to help us publish our newest font, Designer Pro?', style: TextStyles.bodyStyle().copyWith(color: Colors.white), textAlign: TextAlign.left, ), ), const SizedBox( height: 8, ), Transform.scale( scaleX: -1, child: const Image( image: AssetImage('assets/images/specimen-1-glitch.png'), ), ), const SizedBox( height: 56, ), ], ), LightboxedPanel( key: UniqueKey(), pageConfig: widget.pageConfig, fadeOnDismiss: false, onDismiss: super.handleIntroDismiss, autoDismissAfter: 100, buildButton: false, lightBoxBgColor: Colors.black, cardBgColor: Colors.black, content: [ Transform.scale( scaleX: -1, child: Transform.translate( offset: const Offset(20.0, 0.0), child: Text( 'Welcome to your first day on the FontCo team! Are you ready to help us publish our newest font, Designer Pro?', style: TextStyles.bodyStyle().copyWith(color: Colors.white), textAlign: TextAlign.left, ), ), ), const SizedBox( height: 8, ), Transform.scale( scaleX: -1, child: Transform.translate( offset: const Offset(-20.0, 0.0), child: const Image( image: AssetImage('assets/images/specimen-1-glitch.png'), ), ), ), const SizedBox( height: 56, ), ], ), LightboxedPanel( key: UniqueKey(), pageConfig: widget.pageConfig, fadeOnDismiss: false, onDismiss: super.handleIntroDismiss, autoDismissAfter: 100, buildButton: false, lightBoxBgColor: Colors.black, cardBgColor: Colors.black, content: [ Transform.scale( scaleX: -1, child: Text( 'Welcome to your first day on the FontCo team! Are you ready to help us publish our newest font, Designer Pro?', style: TextStyles.bodyStyle().copyWith(color: Colors.white), textAlign: TextAlign.left, ), ), const SizedBox( height: 8, ), Transform.scale( scaleX: -1, child: const Image( image: AssetImage('assets/images/specimen-1-glitch.png'), ), ), const SizedBox( height: 56, ), ], ), LightboxedPanel( key: UniqueKey(), pageConfig: widget.pageConfig, fadeOnDismiss: false, onDismiss: super.handleIntroDismiss, content: [ Text( 'Oh no, you clicked the button too hard! Now the font file is glitched. Help us put the letters back together so we can launch!', style: TextStyles.bodyStyle(), textAlign: TextAlign.left, ), const SizedBox( height: 8, ), const Image( image: AssetImage('assets/images/specimen-2.png'), ), ], ), ]; super.initState(); } @override Widget build(BuildContext context) { return panels[panelIndex]; } }
samples/experimental/varfont_shader_puzzle/lib/page_content/page_narrative_pre.dart/0
{ "file_path": "samples/experimental/varfont_shader_puzzle/lib/page_content/page_narrative_pre.dart", "repo_id": "samples", "token_count": 2575 }
1,388
// Copyright 2023 The Flutter team. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #define PI 3.1415926538 uniform float uTime; uniform vec2 uSize; uniform float uDampener; out vec4 fragColor; uniform sampler2D uTexture; void main() { float piTime = uTime * PI * 2; vec2 texCoord = gl_FragCoord.xy / uSize.xy; float offset = 15; vec4 thisCol = texture(uTexture, texCoord.xy); vec4 rSrc = texture(uTexture, vec2(texCoord.x + offset / uSize.x * sin(piTime), texCoord.y)); float r = rSrc.a; vec4 gSrc = texture(uTexture, vec2(texCoord.x + offset / uSize.x * sin(piTime + PI), texCoord.y)); float g = gSrc.a; vec4 bSrc = texture(uTexture, vec2(texCoord.x, texCoord.y + offset / uSize.y * sin(piTime + PI * 0.66))); float b = bSrc.a; fragColor = vec4(r, g, b, clamp(r+g+b, 0.0, 1.0)); }
samples/experimental/varfont_shader_puzzle/shaders/color_split.frag/0
{ "file_path": "samples/experimental/varfont_shader_puzzle/shaders/color_split.frag", "repo_id": "samples", "token_count": 361 }
1,389
// Copyright 2020, the Flutter project authors. Please see the AUTHORS file // for details. 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:cloud_firestore/cloud_firestore.dart'; import 'package:json_annotation/json_annotation.dart'; part 'api.g.dart'; /// Manipulates app data, abstract class DashboardApi { CategoryApi get categories; EntryApi get entries; } /// Manipulates [Category] data. abstract class CategoryApi { Future<Category?> delete(String id); Future<Category?> get(String id); Future<Category> insert(Category category); Future<List<Category>> list(); Future<Category> update(Category category, String id); Stream<List<Category>> subscribe(); } /// Manipulates [Entry] data. abstract class EntryApi { Future<Entry?> delete(String categoryId, String id); Future<Entry?> get(String categoryId, String id); Future<Entry> insert(String categoryId, Entry entry); Future<List<Entry>> list(String categoryId); Future<Entry> update(String categoryId, String id, Entry entry); Stream<List<Entry>> subscribe(String categoryId); } /// Something that's being tracked, e.g. Hours Slept, Cups of water, etc. @JsonSerializable() class Category { String name; @JsonKey(includeFromJson: false) String? id; Category(this.name); factory Category.fromJson(Map<String, dynamic> json) => _$CategoryFromJson(json); Map<String, dynamic> toJson() => _$CategoryToJson(this); @override operator ==(Object other) => other is Category && other.id == id; @override int get hashCode => id.hashCode; @override String toString() { return '<Category id=$id>'; } } /// A number tracked at a point in time. @JsonSerializable() class Entry { int value; @JsonKey(fromJson: _timestampToDateTime, toJson: _dateTimeToTimestamp) DateTime time; @JsonKey(includeFromJson: false) String? id; Entry(this.value, this.time); factory Entry.fromJson(Map<String, dynamic> json) => _$EntryFromJson(json); Map<String, dynamic> toJson() => _$EntryToJson(this); static DateTime _timestampToDateTime(Timestamp timestamp) { return DateTime.fromMillisecondsSinceEpoch( timestamp.millisecondsSinceEpoch); } static Timestamp _dateTimeToTimestamp(DateTime dateTime) { return Timestamp.fromMillisecondsSinceEpoch( dateTime.millisecondsSinceEpoch); } @override operator ==(Object other) => other is Entry && other.id == id; @override int get hashCode => id.hashCode; @override String toString() { return '<Entry id=$id>'; } }
samples/experimental/web_dashboard/lib/src/api/api.dart/0
{ "file_path": "samples/experimental/web_dashboard/lib/src/api/api.dart", "repo_id": "samples", "token_count": 853 }
1,390
// Copyright 2020, the Flutter project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:web_dashboard/src/api/api.dart'; import 'package:web_dashboard/src/app.dart'; class NewCategoryForm extends StatefulWidget { const NewCategoryForm({super.key}); @override State<NewCategoryForm> createState() => _NewCategoryFormState(); } class _NewCategoryFormState extends State<NewCategoryForm> { final Category _category = Category(''); @override Widget build(BuildContext context) { var api = Provider.of<AppState>(context).api; return EditCategoryForm( category: _category, onDone: (shouldInsert) { if (shouldInsert) { api!.categories.insert(_category); } Navigator.of(context).pop(); }, ); } } class EditCategoryForm extends StatefulWidget { final Category category; final ValueChanged<bool> onDone; const EditCategoryForm({ required this.category, required this.onDone, super.key, }); @override State<EditCategoryForm> createState() => _EditCategoryFormState(); } class _EditCategoryFormState extends State<EditCategoryForm> { final _formKey = GlobalKey<FormState>(); @override Widget build(BuildContext context) { return Form( key: _formKey, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: const EdgeInsets.all(8.0), child: TextFormField( initialValue: widget.category.name, decoration: const InputDecoration( labelText: 'Name', ), onChanged: (newValue) { widget.category.name = newValue; }, validator: (value) { if (value!.isEmpty) { return 'Please enter a name'; } return null; }, ), ), Row( mainAxisAlignment: MainAxisAlignment.end, children: [ Padding( padding: const EdgeInsets.only(left: 8.0, right: 8.0), child: FilledButton( child: const Text('Cancel'), onPressed: () { widget.onDone(false); }, ), ), Padding( padding: const EdgeInsets.only(left: 8.0, right: 8.0), child: FilledButton( child: const Text('OK'), onPressed: () { if (_formKey.currentState!.validate()) { widget.onDone(true); } }, ), ), ], ), ], ), ); } }
samples/experimental/web_dashboard/lib/src/widgets/category_forms.dart/0
{ "file_path": "samples/experimental/web_dashboard/lib/src/widgets/category_forms.dart", "repo_id": "samples", "token_count": 1441 }
1,391
include: package:analysis_defaults/flutter.yaml
samples/flutter_maps_firestore/analysis_options.yaml/0
{ "file_path": "samples/flutter_maps_firestore/analysis_options.yaml", "repo_id": "samples", "token_count": 15 }
1,392
// Copyright 2020, the Flutter project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:io' show Platform; import 'package:flutter/foundation.dart' show kIsWeb; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'package:window_size/window_size.dart'; import 'src/autofill.dart'; import 'src/form_widgets.dart'; import 'src/http/mock_client.dart'; import 'src/sign_in_http.dart'; import 'src/validation.dart'; void main() { setupWindow(); runApp(const FormApp()); } const double windowWidth = 480; const double windowHeight = 854; void setupWindow() { if (!kIsWeb && (Platform.isWindows || Platform.isLinux || Platform.isMacOS)) { WidgetsFlutterBinding.ensureInitialized(); setWindowTitle('Form Samples'); setWindowMinSize(const Size(windowWidth, windowHeight)); setWindowMaxSize(const Size(windowWidth, windowHeight)); getCurrentScreen().then((screen) { setWindowFrame(Rect.fromCenter( center: screen!.frame.center, width: windowWidth, height: windowHeight, )); }); } } final demos = [ Demo( name: 'Sign in with HTTP', route: 'signin_http', builder: (context) => SignInHttpDemo( // This sample uses a mock HTTP client. httpClient: mockClient, ), ), Demo( name: 'Autofill', route: 'autofill', builder: (context) => const AutofillDemo(), ), Demo( name: 'Form widgets', route: 'form_widgets', builder: (context) => const FormWidgetsDemo(), ), Demo( name: 'Validation', route: 'validation', builder: (context) => const FormValidationDemo(), ), ]; final router = GoRouter( routes: [ GoRoute( path: '/', builder: (context, state) => const HomePage(), routes: [ for (final demo in demos) GoRoute( path: demo.route, builder: (context, state) => demo.builder(context), ), ], ), ], ); class FormApp extends StatelessWidget { const FormApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp.router( title: 'Form Samples', theme: ThemeData( colorSchemeSeed: Colors.teal, ), routerConfig: router, ); } } class HomePage extends StatelessWidget { const HomePage({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Form Samples'), ), body: ListView( children: [...demos.map((d) => DemoTile(demo: d))], ), ); } } class DemoTile extends StatelessWidget { final Demo? demo; const DemoTile({this.demo, super.key}); @override Widget build(BuildContext context) { return ListTile( title: Text(demo!.name), onTap: () { context.go('/${demo!.route}'); }, ); } } class Demo { final String name; final String route; final WidgetBuilder builder; const Demo({required this.name, required this.route, required this.builder}); }
samples/form_app/lib/main.dart/0
{ "file_path": "samples/form_app/lib/main.dart", "repo_id": "samples", "token_count": 1223 }
1,393
package com.example.game_template import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
samples/game_template/android/app/src/main/kotlin/com/example/game_template/MainActivity.kt/0
{ "file_path": "samples/game_template/android/app/src/main/kotlin/com/example/game_template/MainActivity.kt", "repo_id": "samples", "token_count": 38 }
1,394
// Copyright 2022, the Flutter project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. List<String> soundTypeToFilename(SfxType type) { switch (type) { case SfxType.huhsh: return const [ 'hash1.mp3', 'hash2.mp3', 'hash3.mp3', ]; case SfxType.wssh: return const [ 'wssh1.mp3', 'wssh2.mp3', 'dsht1.mp3', 'ws1.mp3', 'spsh1.mp3', 'hh1.mp3', 'hh2.mp3', 'kss1.mp3', ]; case SfxType.buttonTap: return const [ 'k1.mp3', 'k2.mp3', 'p1.mp3', 'p2.mp3', ]; case SfxType.congrats: return const [ 'yay1.mp3', 'wehee1.mp3', 'oo1.mp3', ]; case SfxType.erase: return const [ 'fwfwfwfwfw1.mp3', 'fwfwfwfw1.mp3', ]; case SfxType.swishSwish: return const [ 'swishswish1.mp3', ]; } } /// Allows control over loudness of different SFX types. double soundTypeToVolume(SfxType type) { switch (type) { case SfxType.huhsh: return 0.4; case SfxType.wssh: return 0.2; case SfxType.buttonTap: case SfxType.congrats: case SfxType.erase: case SfxType.swishSwish: return 1.0; } } enum SfxType { huhsh, wssh, buttonTap, congrats, erase, swishSwish, }
samples/game_template/lib/src/audio/sounds.dart/0
{ "file_path": "samples/game_template/lib/src/audio/sounds.dart", "repo_id": "samples", "token_count": 773 }
1,395
// Copyright 2022, the Flutter project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'settings_persistence.dart'; /// An in-memory implementation of [SettingsPersistence]. /// Useful for testing. class MemoryOnlySettingsPersistence implements SettingsPersistence { bool musicOn = true; bool soundsOn = true; bool muted = false; String playerName = 'Player'; @override Future<bool> getMusicOn() async => musicOn; @override Future<bool> getMuted({required bool defaultValue}) async => muted; @override Future<String> getPlayerName() async => playerName; @override Future<bool> getSoundsOn() async => soundsOn; @override Future<void> saveMusicOn(bool value) async => musicOn = value; @override Future<void> saveMuted(bool value) async => muted = value; @override Future<void> savePlayerName(String value) async => playerName = value; @override Future<void> saveSoundsOn(bool value) async => soundsOn = value; }
samples/game_template/lib/src/settings/persistence/memory_settings_persistence.dart/0
{ "file_path": "samples/game_template/lib/src/settings/persistence/memory_settings_persistence.dart", "repo_id": "samples", "token_count": 313 }
1,396
name: game_template description: A mobile game built in Flutter. # Prevent accidental publishing to pub.dev. publish_to: 'none' version: 0.0.1+1 environment: sdk: ^3.2.0 dependencies: flutter: sdk: flutter audioplayers: ^6.0.0 cupertino_icons: ^1.0.2 go_router: ^13.0.0 logging: ^1.1.0 provider: ^6.0.2 shared_preferences: ^2.0.13 # If you don't need one of the following dependencies, # delete the relevant line below, and get rid of any Dart code # that references the dependency. firebase_core: ^2.1.1 # Needed for Crashlytics below firebase_crashlytics: ^3.4.16 # Error reporting games_services: ^4.0.0 # Achievements and leaderboards google_mobile_ads: ^4.0.0 # Ads in_app_purchase: ^3.0.1 # In-app purchases dev_dependencies: flutter_lints: ^3.0.0 flutter_test: sdk: flutter flutter_launcher_icons: ^0.13.0 test: ^1.19.0 flutter: uses-material-design: true assets: - assets/images/ - assets/music/ - assets/sfx/ fonts: - family: Permanent Marker fonts: - asset: assets/Permanent_Marker/PermanentMarker-Regular.ttf flutter_icons: android: true ios: true image_path: "assets/icon.png" adaptive_icon_background: "#FFFFFF" adaptive_icon_foreground: "assets/icon-adaptive-foreground.png"
samples/game_template/pubspec.yaml/0
{ "file_path": "samples/game_template/pubspec.yaml", "repo_id": "samples", "token_count": 516 }
1,397
import UIKit import Flutter import GoogleMaps @UIApplicationMain @objc class AppDelegate: FlutterAppDelegate { override func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { GeneratedPluginRegistrant.register(with: self) // TODO: Add your Google Maps API key GMSServices.provideAPIKey("YOUR-API-KEY") return super.application(application, didFinishLaunchingWithOptions: launchOptions) } }
samples/google_maps/ios/Runner/AppDelegate.swift/0
{ "file_path": "samples/google_maps/ios/Runner/AppDelegate.swift", "repo_id": "samples", "token_count": 164 }
1,398
# ios_app_clip A sample project demonstrating integration with iOS App Clip. The App Clip target is rendered by Flutter and uses a plugin. ## Intent 1. Demonstrate it's possible to produce iOS App Clip targets rendered in Flutter. 2. Serve as a canonical example to test the App Clip scenario. 3. Let users validate their integration steps when following the guide at [flutter.dev/docs/development/platform-integration/ios-app-clip](https://flutter.dev/docs/development/platform-integration/ios-app-clip) ## To run In order to run. 1. `flutter build ios --config-only` 1. `open Runner.xcworkspace` 1. Inside Xcode, select the `AppClip` target from the scheme dropdown 1. Select an iOS 16 or higher device 1. Select a development team as needed 1. Press run in Xcode to run ## Questions/issues If you have a general question about iOS App Clips in Flutter, the best places to go are: * [The FlutterDev Google Group](https://groups.google.com/forum/#!forum/flutter-dev) * [The Flutter Gitter channel](https://gitter.im/flutter/flutter) * [StackOverflow](https://stackoverflow.com/questions/tagged/flutter) If you run into an issue with the sample itself, please file an issue in the [main Flutter repo](https://github.com/flutter/flutter/issues).
samples/ios_app_clip/README.md/0
{ "file_path": "samples/ios_app_clip/README.md", "repo_id": "samples", "token_count": 368 }
1,399
// Copyright 2019-present the Flutter authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:isolate'; import 'dart:math'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; class InfiniteProcessPageStarter extends StatelessWidget { const InfiniteProcessPageStarter({super.key}); @override Widget build(context) { return ChangeNotifierProvider( create: (context) => InfiniteProcessIsolateController(), child: const InfiniteProcessPage(), ); } } class InfiniteProcessPage extends StatelessWidget { const InfiniteProcessPage({super.key}); @override Widget build(context) { final controller = Provider.of<InfiniteProcessIsolateController>(context); return SafeArea( child: Column( mainAxisSize: MainAxisSize.min, children: [ Padding( padding: const EdgeInsets.all(16.0), child: Text( 'Summation Results', style: Theme.of(context).textTheme.titleLarge, ), ), const Expanded( child: RunningList(), ), Column( mainAxisSize: MainAxisSize.min, children: [ Padding( padding: const EdgeInsets.all(8.0), child: OverflowBar( spacing: 8.0, alignment: MainAxisAlignment.center, children: [ ElevatedButton( style: ElevatedButton.styleFrom(elevation: 8.0), onPressed: () => controller.start(), child: const Text('Start'), ), ElevatedButton( style: ElevatedButton.styleFrom(elevation: 8.0), onPressed: () => controller.terminate(), child: const Text('Terminate'), ), ], ), ), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Switch( value: !controller.paused, onChanged: (_) => controller.pausedSwitch(), activeTrackColor: Colors.lightGreenAccent, activeColor: Colors.black, inactiveTrackColor: Colors.deepOrangeAccent, inactiveThumbColor: Colors.black, ), const Text('Pause/Resume'), ], ), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ for (int i = 1; i <= 3; i++) ...[ Radio<int>( value: i, groupValue: controller.currentMultiplier, onChanged: (val) => controller.setMultiplier(val!), ), Text('${i}x') ], ], ), ], ), ], ), ); } } class InfiniteProcessIsolateController extends ChangeNotifier { Isolate? newIsolate; late ReceivePort receivePort; late SendPort newIceSP; Capability? capability; int _currentMultiplier = 1; final List<int> _currentResults = []; bool _created = false; bool _paused = false; int get currentMultiplier => _currentMultiplier; bool get paused => _paused; bool get created => _created; List<int> get currentResults => _currentResults; Future<void> createIsolate() async { receivePort = ReceivePort(); newIsolate = await Isolate.spawn(_secondIsolateEntryPoint, receivePort.sendPort); } void listen() { receivePort.listen((dynamic message) { switch (message) { case SendPort(): newIceSP = message; newIceSP.send(_currentMultiplier); case int(): setCurrentResults(message); } }); } Future<void> start() async { if (_created == false && _paused == false) { await createIsolate(); listen(); _created = true; notifyListeners(); } } void terminate() { newIsolate?.kill(); _created = false; _currentResults.clear(); notifyListeners(); } void pausedSwitch() { if (_paused && capability != null) { newIsolate?.resume(capability!); } else { capability = newIsolate?.pause(); } _paused = !_paused; notifyListeners(); } void setMultiplier(int newMultiplier) { _currentMultiplier = newMultiplier; newIceSP.send(_currentMultiplier); notifyListeners(); } void setCurrentResults(int newNum) { _currentResults.insert(0, newNum); notifyListeners(); } @override void dispose() { newIsolate?.kill(priority: Isolate.immediate); newIsolate = null; super.dispose(); } } class RunningList extends StatelessWidget { const RunningList({super.key}); @override Widget build(context) { final controller = Provider.of<InfiniteProcessIsolateController>(context); var sums = controller.currentResults; return DecoratedBox( decoration: BoxDecoration( color: Colors.grey[200], ), child: ListView.builder( itemCount: sums.length, itemBuilder: (context, index) { return Column( children: [ Card( color: (controller.created && !controller.paused) ? Colors.lightGreenAccent : Colors.deepOrangeAccent, child: ListTile( leading: Text('${sums.length - index}.'), title: Text('${sums[index]}.'), ), ), const Divider( color: Colors.blue, height: 3, ), ], ); }, ), ); } } Future<void> _secondIsolateEntryPoint(SendPort callerSP) async { var multiplyValue = 1; var newIceRP = ReceivePort(); callerSP.send(newIceRP.sendPort); newIceRP.listen((dynamic message) { if (message is int) { multiplyValue = message; } }); // This runs until the isolate is terminated. while (true) { var sum = 0; for (var i = 0; i < 10000; i++) { sum += await doSomeWork(); } callerSP.send(sum * multiplyValue); } } Future<int> doSomeWork() { var rng = Random(); return Future(() { var sum = 0; for (var i = 0; i < 1000; i++) { sum += rng.nextInt(100); } return sum; }); }
samples/isolate_example/lib/infinite_process_page.dart/0
{ "file_path": "samples/isolate_example/lib/infinite_process_page.dart", "repo_id": "samples", "token_count": 3272 }
1,400
# Material 3 Demo This sample Flutter app showcases Material 3 features in the Flutter Material library. These features include updated components, typography, color system and elevation support. The app supports light and dark themes, different color palettes, as well as the ability to switch between Material 2 and Material 3. For more information about Material 3, the guidance is now live at https://m3.material.io/. This app also includes new M3 components such as IconButtons, Chips, TextFields, Switches, Checkboxes, Radio buttons and ProgressIndicators. # Preview <img width="400" alt="Screen Shot 2022-08-12 at 12 00 28 PM" src="https://user-images.githubusercontent.com/36861262/184426137-47b550e1-5c6e-4bb7-b647-b1741f96d42b.png"><img width="400" alt="Screen Shot 2022-08-12 at 12 00 38 PM" src="https://user-images.githubusercontent.com/36861262/184426154-063a39e8-24bd-40be-90cd-984bf81c0fdf.png"> # Features ## Icon Buttons on the Top App Bar <img src="https://user-images.githubusercontent.com/36861262/166506048-125caeb3-5d5c-4489-9029-1cb74202dd37.png" width="25"/> Users can switch between a light or dark theme with this button. <img src="https://user-images.githubusercontent.com/36861262/166508002-90fce980-d228-4312-a95f-a1919bb79ccc.png" width="25" /> Users can switch between Material 2 and Material 3 for the displayed components with this button. <img src="https://user-images.githubusercontent.com/36861262/166511137-85dea8df-0017-4649-b913-14d4b7a17c2f.png" width="25" /> This button will bring up a pop-up menu that allows the user to change the base color used for the light and dark themes. This uses a new color seed feature to generate entire color schemes from a single color. ## Component Screen The default screen displays all the updated components in Material 3: AppBar, common Buttons, Floating Action Button(FAB), Chips, Card, Checkbox, Dialog, NavigationBar, NavigationRail, ProgressIndicators, Radio buttons, TextFields and Switch. ### Adaptive Layout Based on the fact that NavigationRail is not recommended on a small screen, the app changes its layout based on the screen width. If it's played on iOS or Android devices which have a narrow screen, a Navigation Bar will show at the bottom and will be used to navigate. But if it's played as a desktop or a web app, a Navigation Rail will show on the left side and at the same time, a Navigation Bar will show as an example but will not have any functionality. Users can see both layouts on one device by running a desktop app and adjusting the screen width. ## Color Screen With Material 3, we have added support for generating a full color scheme from a single seed color. The Color Screen shows users all of the colors in light and dark color palettes that are generated from the currently selected color. ## Typography Screen The Typography Screen displays the text styles used in for the default TextTheme. ## Elevation Screen The Elevation screen shows different ways of elevation with a new supported feature "surfaceTintColor" in the Material library.
samples/material_3_demo/README.md/0
{ "file_path": "samples/material_3_demo/README.md", "repo_id": "samples", "token_count": 829 }
1,401
// Copyright 2021 The Flutter team. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; // NavigationRail shows if the screen width is greater or equal to // narrowScreenWidthThreshold; otherwise, NavigationBar is used for navigation. const double narrowScreenWidthThreshold = 450; const double mediumWidthBreakpoint = 1000; const double largeWidthBreakpoint = 1500; const double transitionLength = 500; // Whether the user has chosen a theme color via a direct [ColorSeed] selection, // or an image [ColorImageProvider]. enum ColorSelectionMethod { colorSeed, image, } enum ColorSeed { baseColor('M3 Baseline', Color(0xff6750a4)), indigo('Indigo', Colors.indigo), blue('Blue', Colors.blue), teal('Teal', Colors.teal), green('Green', Colors.green), yellow('Yellow', Colors.yellow), orange('Orange', Colors.orange), deepOrange('Deep Orange', Colors.deepOrange), pink('Pink', Colors.pink); const ColorSeed(this.label, this.color); final String label; final Color color; } enum ColorImageProvider { leaves('Leaves', 'https://flutter.github.io/assets-for-api-docs/assets/material/content_based_color_scheme_1.png'), peonies('Peonies', 'https://flutter.github.io/assets-for-api-docs/assets/material/content_based_color_scheme_2.png'), bubbles('Bubbles', 'https://flutter.github.io/assets-for-api-docs/assets/material/content_based_color_scheme_3.png'), seaweed('Seaweed', 'https://flutter.github.io/assets-for-api-docs/assets/material/content_based_color_scheme_4.png'), seagrapes('Sea Grapes', 'https://flutter.github.io/assets-for-api-docs/assets/material/content_based_color_scheme_5.png'), petals('Petals', 'https://flutter.github.io/assets-for-api-docs/assets/material/content_based_color_scheme_6.png'); const ColorImageProvider(this.label, this.url); final String label; final String url; } enum ScreenSelected { component(0), color(1), typography(2), elevation(3); const ScreenSelected(this.value); final int value; }
samples/material_3_demo/lib/constants.dart/0
{ "file_path": "samples/material_3_demo/lib/constants.dart", "repo_id": "samples", "token_count": 708 }
1,402
# Run with tooling from https://github.com/flutter/codelabs/tree/main/tooling/codelab_rebuild name: Navigation and Routing rebuild script steps: - name: Remove runners rmdirs: - android - ios - linux - macos - web - windows - name: Flutter recreate flutter: create --org dev.flutter . - name: Patch web/index.html path: web/index.html patch-u: | --- b/navigation_and_routing/web/index.html +++ a/navigation_and_routing/web/index.html @@ -18,7 +18,7 @@ <meta charset="UTF-8"> <meta content="IE=Edge" http-equiv="X-UA-Compatible"> - <meta name="description" content="A new Flutter project."> + <meta name="description" content="Navigation and routing sample app"> <!-- iOS meta tags & icons --> <meta name="apple-mobile-web-app-capable" content="yes"> - name: Patch web/manifest.json path: web/manifest.json patch-u: | --- b/navigation_and_routing/web/manifest.json +++ a/navigation_and_routing/web/manifest.json @@ -5,7 +5,7 @@ "display": "standalone", "background_color": "#0175C2", "theme_color": "#0175C2", - "description": "A new Flutter project.", + "description": "Navigation and routing sample app", "orientation": "portrait-primary", "prefer_related_applications": false, "icons": [ - name: Update dependencies flutter: pub upgrade --major-versions
samples/navigation_and_routing/codelab_rebuild.yaml/0
{ "file_path": "samples/navigation_and_routing/codelab_rebuild.yaml", "repo_id": "samples", "token_count": 655 }
1,403
// Copyright 2021, the Flutter project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:flutter/material.dart'; import '../data.dart'; import '../widgets/book_list.dart'; class AuthorDetailsScreen extends StatelessWidget { final Author author; final ValueChanged<Book> onBookTapped; const AuthorDetailsScreen({ super.key, required this.author, required this.onBookTapped, }); @override Widget build(BuildContext context) => Scaffold( appBar: AppBar( title: Text(author.name), ), body: Center( child: Column( children: [ Expanded( child: BookList( books: author.books, onTap: (book) { onBookTapped(book); }, ), ), ], ), ), ); }
samples/navigation_and_routing/lib/src/screens/author_details.dart/0
{ "file_path": "samples/navigation_and_routing/lib/src/screens/author_details.dart", "repo_id": "samples", "token_count": 468 }
1,404
name: bookstore description: Navigation and routing sample app publish_to: "none" # Remove this line if you wish to publish to pub.dev version: 1.0.0+1 environment: sdk: ^3.2.0 dependencies: adaptive_navigation: ^0.0.3 collection: ^1.17.0 cupertino_icons: ^1.0.2 flutter: sdk: flutter go_router: ^13.0.0 path_to_regexp: ^0.4.0 quiver: ^3.1.0 url_launcher: ^6.1.1 url_strategy: ^0.2.0 window_size: git: url: https://github.com/google/flutter-desktop-embedding.git path: plugins/window_size dev_dependencies: analysis_defaults: path: ../analysis_defaults flutter_test: sdk: flutter test: ^1.24.0 flutter: uses-material-design: true
samples/navigation_and_routing/pubspec.yaml/0
{ "file_path": "samples/navigation_and_routing/pubspec.yaml", "repo_id": "samples", "token_count": 297 }
1,405
org.gradle.jvmargs=-Xmx4G android.useAndroidX=true android.enableJetifier=true
samples/place_tracker/android/gradle.properties/0
{ "file_path": "samples/place_tracker/android/gradle.properties", "repo_id": "samples", "token_count": 30 }
1,406
name: platform_channels description: A new Flutter project. version: 1.0.0+1 environment: sdk: ^3.2.0 dependencies: flutter: sdk: flutter cupertino_icons: ^1.0.3 go_router: ">=10.1.0 <14.0.0" dev_dependencies: analysis_defaults: path: ../analysis_defaults flutter_test: sdk: flutter flutter: uses-material-design: true assets: - assets/
samples/platform_channels/pubspec.yaml/0
{ "file_path": "samples/platform_channels/pubspec.yaml", "repo_id": "samples", "token_count": 164 }
1,407
package dev.flutter.platform_design import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
samples/platform_design/android/app/src/main/kotlin/dev/flutter/platform_design/MainActivity.kt/0
{ "file_path": "samples/platform_design/android/app/src/main/kotlin/dev/flutter/platform_design/MainActivity.kt", "repo_id": "samples", "token_count": 39 }
1,408
// Copyright 2020 The Flutter team. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:platform_design/main.dart'; void main() { group('Platform tests', () { testWidgets('Builds for Android correctly', (tester) async { debugDefaultTargetPlatformOverride = TargetPlatform.android; await tester.pumpWidget(const MyAdaptingApp()); // The test should be able to find the drawer button. expect(find.byIcon(Icons.menu), findsOneWidget); // There should be a refresh button. expect(find.byIcon(Icons.refresh), findsOneWidget); // Since this is a static, undo any change made in the test. debugDefaultTargetPlatformOverride = null; }); testWidgets('Builds for iOS correctly', (tester) async { debugDefaultTargetPlatformOverride = TargetPlatform.iOS; await tester.pumpWidget(const MyAdaptingApp()); // There should now be a large title style nav bar. expect(find.byType(CupertinoSliverNavigationBar), findsOneWidget); // There's a tab button for the first tab. expect(find.byIcon(CupertinoIcons.music_note), findsOneWidget); // The hamburger button isn't there anymore. expect(find.byIcon(Icons.menu), findsNothing); // Since this is a static, undo any change made in the test. debugDefaultTargetPlatformOverride = null; }); }); }
samples/platform_design/test/widget_test.dart/0
{ "file_path": "samples/platform_design/test/widget_test.dart", "repo_id": "samples", "token_count": 534 }
1,409
#import "GeneratedPluginRegistrant.h"
samples/platform_view_swift/ios/Runner/Runner-Bridging-Header.h/0
{ "file_path": "samples/platform_view_swift/ios/Runner/Runner-Bridging-Header.h", "repo_id": "samples", "token_count": 13 }
1,410
import 'dart:ui' as ui; import 'package:flutter/material.dart'; import 'package:flutter_shaders/flutter_shaders.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Simple Shader Demo', theme: ThemeData( colorSchemeSeed: Colors.blue, ), home: const MyHomePage(), ); } } class MyHomePage extends StatelessWidget { const MyHomePage({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Simple Shader Demo'), ), body: ShaderBuilder( assetKey: 'shaders/simple.frag', (context, shader, child) => CustomPaint( size: MediaQuery.of(context).size, painter: ShaderPainter( shader: shader, ), ), child: const Center( child: CircularProgressIndicator(), ), ), ); } } class ShaderPainter extends CustomPainter { ShaderPainter({required this.shader}); ui.FragmentShader shader; @override void paint(Canvas canvas, Size size) { shader.setFloat(0, size.width); shader.setFloat(1, size.height); final paint = Paint()..shader = shader; canvas.drawRect( Rect.fromLTWH(0, 0, size.width, size.height), paint, ); } @override bool shouldRepaint(covariant CustomPainter oldDelegate) { return false; } }
samples/simple_shader/lib/main.dart/0
{ "file_path": "samples/simple_shader/lib/main.dart", "repo_id": "samples", "token_count": 631 }
1,411
#import "GeneratedPluginRegistrant.h"
samples/simplistic_calculator/ios/Runner/Runner-Bridging-Header.h/0
{ "file_path": "samples/simplistic_calculator/ios/Runner/Runner-Bridging-Header.h", "repo_id": "samples", "token_count": 13 }
1,412
#import "GeneratedPluginRegistrant.h"
samples/simplistic_editor/ios/Runner/Runner-Bridging-Header.h/0
{ "file_path": "samples/simplistic_editor/ios/Runner/Runner-Bridging-Header.h", "repo_id": "samples", "token_count": 13 }
1,413
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility in the flutter_test package. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:simplistic_editor/basic_text_input_client.dart'; import 'package:simplistic_editor/main.dart'; import 'package:simplistic_editor/text_editing_delta_history_view.dart'; void main() { testWidgets('Default main page shows all components', (tester) async { await tester.pumpWidget(const MyApp()); // Elements on Style ToggleButton Toolbar. expect( find.widgetWithIcon(ToggleButtons, Icons.format_bold), findsOneWidget); expect(find.widgetWithIcon(ToggleButtons, Icons.format_italic), findsOneWidget); expect(find.widgetWithIcon(ToggleButtons, Icons.format_underline), findsOneWidget); // Elements on the main screen // Delta labels. expect(find.widgetWithText(Tooltip, "Delta Type"), findsOneWidget); expect(find.widgetWithText(Tooltip, "Delta Text"), findsOneWidget); expect(find.widgetWithText(Tooltip, "Delta Offset"), findsOneWidget); expect(find.widgetWithText(Tooltip, "New Selection"), findsOneWidget); expect(find.widgetWithText(Tooltip, "New Composing"), findsOneWidget); // Selection delta is generated and delta history is visible. await tester.tap(find.byType(BasicTextInputClient)); await tester.pumpAndSettle(); expect(find.widgetWithText(TextEditingDeltaView, "NonTextUpdate"), findsOneWidget); // Find tooltips. expect(find.byTooltip('The text that is being inserted or deleted'), findsOneWidget); expect( find.byTooltip( 'The type of text input that is occurring. Check out the documentation for TextEditingDelta for more information.'), findsOneWidget); expect( find.byTooltip( 'The offset in the text where the text input is occurring.'), findsOneWidget); expect( find.byTooltip( 'The new text selection range after the text input has occurred.'), findsOneWidget); // About Dialog expect(find.widgetWithIcon(IconButton, Icons.info_outline), findsOneWidget); await tester.tap(find.widgetWithIcon(IconButton, Icons.info_outline)); await tester.pumpAndSettle(); expect(find.widgetWithText(Center, 'About'), findsOneWidget); }); }
samples/simplistic_editor/test/main_screen_test.dart/0
{ "file_path": "samples/simplistic_editor/test/main_screen_test.dart", "repo_id": "samples", "token_count": 898 }
1,414
// Copyright 2020 The Flutter team. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:testing_app/models/favorites.dart'; class FavoritesPage extends StatelessWidget { static const routeName = 'favorites_page'; static const fullPath = '/$routeName'; const FavoritesPage({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Favorites'), ), body: Consumer<Favorites>( builder: (context, value, child) => value.items.isNotEmpty ? ListView.builder( itemCount: value.items.length, padding: const EdgeInsets.symmetric(vertical: 16), itemBuilder: (context, index) => FavoriteItemTile(value.items[index]), ) : const Center( child: Text('No favorites added.'), ), ), ); } } class FavoriteItemTile extends StatelessWidget { final int itemNo; const FavoriteItemTile(this.itemNo, {super.key}); @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.all(8.0), child: ListTile( leading: CircleAvatar( backgroundColor: Colors.primaries[itemNo % Colors.primaries.length], ), title: Text( 'Item $itemNo', key: Key('favorites_text_$itemNo'), ), trailing: IconButton( key: Key('remove_icon_$itemNo'), icon: const Icon(Icons.close), onPressed: () { context.read<Favorites>().remove(itemNo); ScaffoldMessenger.of(context).showSnackBar( const SnackBar( content: Text('Removed from favorites.'), duration: Duration(seconds: 1), ), ); }, ), ), ); } }
samples/testing_app/lib/screens/favorites.dart/0
{ "file_path": "samples/testing_app/lib/screens/favorites.dart", "repo_id": "samples", "token_count": 911 }
1,415
#include "../../Flutter/Flutter-Debug.xcconfig" #include "Warnings.xcconfig"
samples/testing_app/macos/Runner/Configs/Debug.xcconfig/0
{ "file_path": "samples/testing_app/macos/Runner/Configs/Debug.xcconfig", "repo_id": "samples", "token_count": 32 }
1,416
// Copyright 2018 The Flutter team. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/cupertino.dart'; import 'package:flutter/services.dart'; import 'package:provider/provider.dart'; import 'package:veggieseasons/data/app_state.dart'; import 'package:veggieseasons/data/veggie.dart'; import 'package:veggieseasons/widgets/veggie_headline.dart'; class SearchScreen extends StatefulWidget { const SearchScreen({this.restorationId, super.key}); final String? restorationId; @override State<SearchScreen> createState() => _SearchScreenState(); } class _SearchScreenState extends State<SearchScreen> with RestorationMixin { final controller = RestorableTextEditingController(); final focusNode = FocusNode(); String? terms; @override String? get restorationId => widget.restorationId; @override void restoreState(RestorationBucket? oldBucket, bool initialRestore) { registerForRestoration(controller, 'text'); controller.addListener(_onTextChanged); terms = controller.value.text; } @override void dispose() { focusNode.dispose(); controller.dispose(); super.dispose(); } void _onTextChanged() { setState(() => terms = controller.value.text); } Widget _createSearchBox({bool focus = true}) { return Padding( padding: const EdgeInsets.all(8), child: CupertinoSearchTextField( controller: controller.value, focusNode: focus ? focusNode : null, ), ); } Widget _buildSearchResults(List<Veggie> veggies) { if (veggies.isEmpty) { return Center( child: Padding( padding: const EdgeInsets.symmetric(horizontal: 24), child: Text( 'No veggies matching your search terms were found.', style: CupertinoTheme.of(context).textTheme.textStyle, ), ), ); } return ListView.builder( restorationId: 'list', itemCount: veggies.length + 1, itemBuilder: (context, i) { if (i == 0) { return Visibility( // This invisible and otherwise unnecessary search box is used to // pad the list entries downward, so none will be underneath the // real search box when the list is at its top scroll position. visible: false, maintainSize: true, maintainAnimation: true, maintainState: true, // This invisible and otherwise unnecessary search box is used to // pad the list entries downward, so none will be underneath the // real search box when the list is at its top scroll position. child: _createSearchBox(focus: false), ); } else { return Padding( padding: const EdgeInsets.only(left: 16, right: 16, bottom: 24), child: VeggieHeadline(veggies[i - 1]), ); } }, ); } @override Widget build(BuildContext context) { final model = Provider.of<AppState>(context); return UnmanagedRestorationScope( bucket: bucket, child: CupertinoTabView( restorationScopeId: 'tabview', builder: (context) { return AnnotatedRegion<SystemUiOverlayStyle>( value: SystemUiOverlayStyle( statusBarBrightness: MediaQuery.platformBrightnessOf(context), ), child: SafeArea( bottom: false, child: Stack( children: [ _buildSearchResults(model.searchVeggies(terms)), _createSearchBox(), ], ), ), ); }, ), ); } }
samples/veggieseasons/lib/screens/search.dart/0
{ "file_path": "samples/veggieseasons/lib/screens/search.dart", "repo_id": "samples", "token_count": 1521 }
1,417
#include "../../Flutter/Flutter-Debug.xcconfig" #include "Warnings.xcconfig"
samples/veggieseasons/macos/Runner/Configs/Debug.xcconfig/0
{ "file_path": "samples/veggieseasons/macos/Runner/Configs/Debug.xcconfig", "repo_id": "samples", "token_count": 32 }
1,418
// Copyright 2021 The Flutter team. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:js_interop'; import 'dart:js_interop_unsafe'; import 'package:flutter/widgets.dart'; import 'package:web_startup_analyzer/src/web_startup_analyzer_base.dart'; import 'frame_analyzer.dart'; import 'startup_analyzer.dart'; class WebStartupAnalyzer extends WebStartupAnalyzerBase { final WidgetsBinding _widgetsBinding; late final FrameAnalyzer _frameAnalyzer; List<int>? _additionalFrames; @override Map<String, dynamic> startupTiming = {}; @override double get domContentLoaded => (flutterWebStartupAnalyzer.timings['domContentLoaded'] as JSNumber) .toDartDouble; @override double get loadEntrypoint => (flutterWebStartupAnalyzer.timings['loadEntrypoint'] as JSNumber) .toDartDouble; @override double get initializeEngine => (flutterWebStartupAnalyzer.timings['initializeEngine'] as JSNumber) .toDartDouble; @override double get appRunnerRunApp => (flutterWebStartupAnalyzer.timings['appRunnerRunApp'] as JSNumber) .toDartDouble; @override double? get firstFrame => (flutterWebStartupAnalyzer.timings['firstFrame'] as JSNumber?) ?.toDartDouble; @override double? get firstPaint => (flutterWebStartupAnalyzer.timings['first-paint'] as JSNumber?) ?.toDartDouble; @override double? get firstContentfulPaint => (flutterWebStartupAnalyzer.timings['first-contentful-paint'] as JSNumber?) ?.toDartDouble; @override List<int>? get additionalFrames => _additionalFrames; WebStartupAnalyzer({int additionalFrameCount = 5}) : _widgetsBinding = WidgetsFlutterBinding.ensureInitialized() { _frameAnalyzer = FrameAnalyzer(_widgetsBinding, additionalFrames: additionalFrameCount); _captureStartupMetrics(); startupTiming = { 'domContentLoaded': domContentLoaded, 'loadEntrypoint': loadEntrypoint, 'initializeEngine': initializeEngine, 'appRunnerRunApp': appRunnerRunApp, }; _captureFirstFrame().then((value) { flutterWebStartupAnalyzer.captureAll(); onFirstFrame.value = firstFrame; // Capture first-paint and first-contentful-paint Future.delayed(const Duration(milliseconds: 200)).then((_) { flutterWebStartupAnalyzer.capturePaint(); onFirstPaint.value = (firstPaint!, firstContentfulPaint!); }); }); captureFlutterFrameData().then((value) { _additionalFrames = value; onAdditionalFrames.value = value; }); onChange = Listenable.merge([onFirstFrame, onFirstPaint, onAdditionalFrames]); } _captureStartupMetrics() { flutterWebStartupAnalyzer.markFinished('appRunnerRunApp'); flutterWebStartupAnalyzer.captureAll(); } Future<void> _captureFirstFrame() { final completer = Completer(); flutterWebStartupAnalyzer.markStart('firstFrame'); _widgetsBinding.addPostFrameCallback((timeStamp) { flutterWebStartupAnalyzer.markFinished('firstFrame'); flutterWebStartupAnalyzer.capture('firstFrame'); completer.complete(); }); return completer.future; } Future<List<int>> captureFlutterFrameData() async { await _frameAnalyzer.captureAdditionalFrames(); return _frameAnalyzer.additionalFrameTimes; } }
samples/web/_packages/web_startup_analyzer/lib/src/web_startup_analyzer.dart/0
{ "file_path": "samples/web/_packages/web_startup_analyzer/lib/src/web_startup_analyzer.dart", "repo_id": "samples", "token_count": 1269 }
1,419
// Copyright 2020 The Flutter team. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file bool matchesQuery(String query, String sampleAttributes) { if (query.isEmpty) { return true; } var queryWords = query.toLowerCase().split(' ') ..removeWhere((s) => s.isEmpty); var attributes = sampleAttributes.toLowerCase().split(' ') ..removeWhere((s) => s.isEmpty); // Test for type filter // This will check whether a type parameter is present in the // search query, and return false if the self type mismatches // the query type for (final word in queryWords) { if ((word.contains('type:') && !attributes.contains(word)) || (word.contains('platform:') && !attributes.contains('type:demo'))) { return false; } } // Test for exact matches if (attributes.contains(query)) { return true; } // Test for exact matches for keywords var matches = 0; for (final word in queryWords) { if (attributes.contains(word)) { matches++; } if (matches == queryWords.length) { return true; } } // Test for queries whose keywords are a substring of any attribute // e.g. searching "kitten tag:cats" is a match for a sample with the // attributes "kittens tag:cats" matches = 0; for (final attribute in attributes) { for (final queryWord in queryWords) { if (attribute.startsWith(queryWord)) { matches++; } } // Only return true if each search term was matched if (matches == queryWords.length) { return true; } } return false; } Map<String, String> parseHash(String hash) => Uri.parse(hash.substring(hash.indexOf('#') + 1)).queryParameters; String formatHash(Map<String, String> parameters) => Uri().replace(queryParameters: parameters).toString(); String searchQueryFromParams(Map<String, String> params) { var buf = StringBuffer(); if (params.containsKey('search')) { buf.write(params['search']); } if (params.containsKey('type')) { if (buf.isNotEmpty) buf.write(' '); var value = params['type']; if (value != null) buf.write('type:$value'); } if (params.containsKey('platform')) { if (buf.isNotEmpty) buf.write(' '); var value = params['platform']; if (value != null) buf.write('platform:$value'); } return buf.toString(); }
samples/web/samples_index/lib/src/search.dart/0
{ "file_path": "samples/web/samples_index/lib/src/search.dart", "repo_id": "samples", "token_count": 824 }
1,420
// ignore_for_file: avoid_web_libraries_in_flutter import 'package:flutter/material.dart'; import 'pages/counter.dart'; import 'pages/dash.dart'; import 'pages/text.dart'; import 'src/js_interop.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatefulWidget { const MyApp({super.key}); @override State<MyApp> createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { final ValueNotifier<DemoScreen> _screen = ValueNotifier<DemoScreen>(DemoScreen.counter); final ValueNotifier<int> _counter = ValueNotifier<int>(0); final ValueNotifier<String> _text = ValueNotifier<String>(''); late final DemoAppStateManager _state; @override void initState() { super.initState(); _state = DemoAppStateManager( screen: _screen, counter: _counter, text: _text, ); final export = createJSInteropWrapper(_state); // Emit this through the root object of the flutter app :) broadcastAppEvent('flutter-initialized', export); } @override void dispose() { super.dispose(); } @override Widget build(BuildContext context) { return MaterialApp( title: 'Element embedding', theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue), ), home: ValueListenableBuilder<DemoScreen>( valueListenable: _screen, builder: (context, value, child) => demoScreenRouter(value), ), ); } Widget demoScreenRouter(DemoScreen which) { switch (which) { case DemoScreen.counter: return CounterDemo(counter: _counter); case DemoScreen.text: return TextFieldDemo(text: _text); case DemoScreen.dash: return DashDemo(text: _text); } } }
samples/web_embedding/ng-flutter/flutter/lib/main.dart/0
{ "file_path": "samples/web_embedding/ng-flutter/flutter/lib/main.dart", "repo_id": "samples", "token_count": 662 }
1,421