code
stringlengths
8
3.25M
repository
stringlengths
15
175
metadata
stringlengths
66
249
// Copyright 2019 Google LLC // // 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 // // https://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. // @dart=2.12 import 'dart:async' show Future; import 'package:shelf/shelf.dart'; import 'package:shelf_router/shelf_router.dart'; part 'api.g.dart'; class Api { @Route.get('/time') Response _time(Request request) => Response.ok('it is about now'); @Route.get('/to-uppercase/<word|.*>') Future<Response> _toUpperCase(Request request, String word) async => Response.ok(word.toUpperCase()); @Route.get(r'/$string-escape') Response _stringEscapingWorks(Request request) => Response.ok('Just testing string escaping'); Router get router => _$ApiRouter(this); }
dart-neats/shelf_router_generator/test/server/api.dart/0
{'file_path': 'dart-neats/shelf_router_generator/test/server/api.dart', 'repo_id': 'dart-neats', 'token_count': 367}
// Copyright 2019 Google LLC // // 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 // // https://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 'package:test/test.dart'; import 'package:slugid/slugid.dart'; void testSlugid(String name, Slugid Function() create) { group(name, () { late final Slugid s; test('create', () { s = create(); }); test('uuid()', () { final uuid = s.uuid(); expect(Slugid(uuid), equals(s)); expect(Slugid(uuid).uuid(), equals(uuid)); expect(Slugid(uuid).toString(), equals(s.toString())); }); test('bytes()', () { final b = s.bytes(); expect(b.length, equals(16)); }); test('toString()', () { expect(s.toString().length, equals(22)); expect(s.toString().contains('='), isFalse); }); }); } void main() { group('from slugid', () { testSlugid( 'aiJh4a8FRYSKaNeVTt4Euw', () => Slugid('aiJh4a8FRYSKaNeVTt4Euw')); testSlugid( 'L_YriPk0RLuLyU8zb638oA', () => Slugid('L_YriPk0RLuLyU8zb638oA')); testSlugid( '-8prq-8rTGqKl2W9SSfyDQ', () => Slugid('-8prq-8rTGqKl2W9SSfyDQ')); testSlugid( 'ZCHCGNvUTqq1Qr-TXMz5mw', () => Slugid('ZCHCGNvUTqq1Qr-TXMz5mw')); }); group('from uuid', () { testSlugid('23416fac-a6d3-497f-98bb-1d0a3b7b0c13', () => Slugid('23416fac-a6d3-497f-98bb-1d0a3b7b0c13')); testSlugid('b7d2b815-d5be-43cb-829f-d66e6facb61a', () => Slugid('b7d2b815-d5be-43cb-829f-d66e6facb61a')); testSlugid('636d1113-0528-4777-aca9-23b204505beb', () => Slugid('636d1113-0528-4777-aca9-23b204505beb')); testSlugid('29fd0bdd-1d5d-4cee-afd4-901474e5e9b0', () => Slugid('29fd0bdd-1d5d-4cee-afd4-901474e5e9b0')); }); group('v4()', () { for (var i = 0; i < 50; i++) { testSlugid('v4() ($i)', () => Slugid.v4()); } }); group('nice()', () { for (var i = 0; i < 50; i++) { testSlugid('nice() ($i)', () => Slugid.nice()); } test('nice() format', () { for (var i = 0; i < 500; i++) { expect(Slugid.nice().toString()[0], isNot(equals('-'))); } }); }); }
dart-neats/slugid/test/slugid_test.dart/0
{'file_path': 'dart-neats/slugid/test/slugid_test.dart', 'repo_id': 'dart-neats', 'token_count': 1217}
// Copyright 2022 Google LLC // // 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 // // https://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:io' show File, Directory, FileSystemException, IOException; import 'package:glob/glob.dart' show Glob; import 'package:glob/list_local_fs.dart' show ListLocalFileSystem; import 'package:async/async.dart' show StreamGroup; import 'package:analyzer/dart/ast/ast.dart' show ExportDirective, ImportDirective, StringLiteral, SingleStringLiteral; import 'package:analyzer/dart/ast/visitor.dart' show RecursiveAstVisitor; import 'package:meta/meta.dart' show sealed; import 'package:vendor/src/action/action.dart' show Action, Context; import 'package:vendor/src/exceptions.dart' show VendorFailure, ExitCode; import 'package:path/path.dart' as p; import 'package:vendor/src/utils/iterable_ext.dart' show IterableExt; import 'package:yaml_edit/yaml_edit.dart' show SourceEdit; import 'package:analyzer/dart/analysis/results.dart' show ParsedUnitResult; import 'package:analyzer/dart/analysis/analysis_context_collection.dart' show AnalysisContextCollection; @sealed class ImportRewriteAction extends Action { /// Folder within which to make the rewrite final Uri folder; final Uri from; final Uri to; ImportRewriteAction({ required this.folder, required this.from, required this.to, }); @override String get summary => 'rewrite import "$from" -> "$to" in $folder'; @override Future<void> apply(Context ctx) async { final rootPath = p.canonicalize(ctx.rootPackageFolder.toFilePath()); final analysisContextCollection = AnalysisContextCollection( includedPaths: [rootPath], ); final context = analysisContextCollection.contextFor(rootPath); final session = context.currentSession; final absoluteFolder = ctx.rootPackageFolder.resolveUri(folder); final files = _findDartFiles( absoluteFolder, excludeVendorFolder: absoluteFolder == ctx.rootPackageFolder, ); ctx.log('# Apply: $summary'); await for (final f in files) { ctx.log('- rewriting "$f"'); final u = session.getParsedUnit(absoluteFolder.resolve(f).toFilePath()); if (u is ParsedUnitResult) { if (u.isPart) { continue; // Skip parts, they can't have imports } if (u.errors.isNotEmpty) { ctx.warning(' Failed to parse: ${u.errors.first.toString()}'); continue; } // Run rewrite visitor final rewriter = _ImportRewriteVisitor(from, to, ctx); u.unit.accept(rewriter); // Rebase all edits on top of eachother var delta = 0; final edits = <SourceEdit>[]; for (final edit in rewriter.edits) { edits.add(SourceEdit( edit.offset + delta, edit.length, edit.replacement, )); delta += edit.replacement.length - edit.length; } // Apply edits updating the result final result = SourceEdit.applyAll(u.content, edits); // Update file // Note: we could probably make vendoring faster by collecting all edits // from various rewrite actions and applying them all at once. try { await File.fromUri(absoluteFolder.resolve(f)).writeAsString(result); } on IOException catch (e) { throw VendorFailure( ExitCode.ioError, 'unable to save "$f", failure: $e', ); } } } } } extension on Uri { /// [pathSegments] without the last entry, if it's empty. The last entry is /// an empty string when we have trailing a slash (e.g. `package:foo/`). Iterable<String> get pathSegmentsNoTrailingSlash { if (pathSegments.isEmpty) { return pathSegments; } if (pathSegments.last.isNotEmpty) { return pathSegments; } return pathSegments.take(pathSegments.length - 1); } } class _ImportRewriteVisitor extends RecursiveAstVisitor<void> { final Uri _from; final Uri _to; final Context _ctx; final List<SourceEdit> edits = []; _ImportRewriteVisitor(this._from, this._to, this._ctx); @override void visitExportDirective(ExportDirective n) { _rewriteUri(n.uri); for (final c in n.configurations) { _rewriteUri(c.uri); } } @override void visitImportDirective(ImportDirective n) { _rewriteUri(n.uri); for (final c in n.configurations) { _rewriteUri(c.uri); } } void _rewriteUri(StringLiteral s) { final u = Uri.tryParse(s.stringValue!); if (u == null) { // TODO: Print source location here. _ctx.warning(' Unable to parse: "${s.stringValue}"'); return; // ignore URIs we can't parse } if (!_matchesFrom(u)) { return; } // Construct new URI final relativePath = u.pathSegments.skip( _from.pathSegmentsNoTrailingSlash.length, ); final newUri = _to.replace( pathSegments: _to.pathSegmentsNoTrailingSlash.followedBy(relativePath), ); // We prefer single quote, but if it's a SingleStringLiteral, which it // almost always is, we quickly check to see if it's single or double. // If it's not a SingleStringLiteral and double quoted, we use single quote. final quote = (s is SingleStringLiteral && !s.isSingleQuoted) ? '"' : "'"; edits.add(SourceEdit(s.offset, s.length, '$quote$newUri$quote')); } bool _matchesFrom(Uri u) { u = u.normalizePath(); return u.scheme == _from.scheme && u.pathSegments.startsWith(_from.pathSegmentsNoTrailingSlash) && u.pathSegments.length > _from.pathSegmentsNoTrailingSlash.length; } } const _sourceFoldersInPackage = ['lib/', 'test/', 'bin/', 'benchmark/']; Stream<String> _findDartFiles(Uri folder, {bool excludeVendorFolder = false}) => StreamGroup.merge(_sourceFoldersInPackage.map( (path) => Glob('**.dart') .list( root: folder.resolve(path).toFilePath(), followLinks: false, ) .handleError( (e) {/* ignore folder doesn't exist */}, test: (e) => e is FileSystemException && (e.osError?.errorCode == 2 || !Directory.fromUri(folder.resolve(path)).existsSync()), ), )) .where((entity) => entity is File) .map((entity) => p.relative(entity.path, from: folder.toFilePath())) .where((path) => !excludeVendorFolder || !p.isWithin('lib/src/third_party/', path));
dart-neats/vendor/lib/src/action/import_rewrite.dart/0
{'file_path': 'dart-neats/vendor/lib/src/action/import_rewrite.dart', 'repo_id': 'dart-neats', 'token_count': 2663}
// Copyright 2022 Google LLC // // 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 // // https://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 'package:test/test.dart'; import 'package:vendor/src/action/action.dart' show Action; import 'package:test_descriptor/test_descriptor.dart' as d; import 'package:pub_semver/pub_semver.dart' show Version; import '../test_context.dart' show testWithContext; void main() { testWithContext('fetch mypkg 3.0.1', (ctx) async { ctx.server.add(d.dir('mypkg', [ d.file('pubspec.yaml', '''{ "name": "mypkg", "version": "3.0.1", "environment": {"sdk": ">2.12.0 <=3.0.0"} }'''), d.file('README.md', '# mypkg for dart'), d.file('test/exclude.dart', '// Excluded file'), ])); await d.file('pubspec.yaml', 'name: mypkg').create(); await d.dir('lib', []).create(); await Action.fetchPackage( Uri.directory(d.path('lib/src/third_party/mypkg-3')), 'mypkg', Version.parse('3.0.1'), ctx.context.defaultHostedUrl, { 'README.md', }, ).apply(ctx.context); await d.file('pubspec.yaml', 'name: mypkg').validate(); await d .file( 'lib/src/third_party/mypkg-3/README.md', contains('mypkg for dart'), ) .validate(); await d.nothing('lib/src/third_party/mypkg-3/test/exclude.dart').validate(); }); }
dart-neats/vendor/test/action/fetch_package_test.dart/0
{'file_path': 'dart-neats/vendor/test/action/fetch_package_test.dart', 'repo_id': 'dart-neats', 'token_count': 733}
// Copyright (c) 2014, 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. library context; import 'dart:async'; import 'services/dartservices.dart'; abstract class Context { List<AnalysisIssue> issues = []; String get focusedEditor; String name; String description; String dartSource; String htmlSource; String cssSource; String get activeMode; Stream<String> get onModeChange; void switchTo(String name); } abstract class ContextProvider { Context get context; } class BaseContextProvider extends ContextProvider { @override final Context context; BaseContextProvider(this.context); }
dart-pad/lib/context.dart/0
{'file_path': 'dart-pad/lib/context.dart', 'repo_id': 'dart-pad', 'token_count': 214}
// Copyright (c) 2019, 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. import 'dart:async'; import 'dart:html'; import 'package:dart_pad/src/util.dart'; import 'package:mdc_web/mdc_web.dart'; enum DialogResult { yes, no, ok, cancel, } class Dialog { final MDCDialog _mdcDialog; final Element _leftButton; final Element _rightButton; final Element _title; final Element _content; Dialog() : assert(querySelector('.mdc-dialog') != null), assert(querySelector('#dialog-left-button') != null), assert(querySelector('#dialog-right-button') != null), assert(querySelector('#my-dialog-title') != null), assert(querySelector('#my-dialog-content') != null), _mdcDialog = MDCDialog(querySelector('.mdc-dialog')), _leftButton = querySelector('#dialog-left-button'), _rightButton = querySelector('#dialog-right-button'), _title = querySelector('#my-dialog-title'), _content = querySelector('#my-dialog-content'); Future<DialogResult> showYesNo(String title, String htmlMessage, {String yesText = 'Yes', String noText = 'No'}) { return _setUpAndDisplay( title, htmlMessage, noText, yesText, DialogResult.no, DialogResult.yes, ); } Future<DialogResult> showOk(String title, String htmlMessage) { return _setUpAndDisplay( title, htmlMessage, '', 'OK', DialogResult.cancel, DialogResult.ok, false, ); } Future<DialogResult> showOkCancel(String title, String htmlMessage) { return _setUpAndDisplay( title, htmlMessage, 'Cancel', 'OK', DialogResult.cancel, DialogResult.ok, ); } Future<DialogResult> _setUpAndDisplay( String title, String htmlMessage, String leftButtonText, String rightButtonText, DialogResult leftButtonResult, DialogResult rightButtonResult, [bool showLeftButton = true]) { _title.text = title; _content.setInnerHtml(htmlMessage, validator: PermissiveNodeValidator()); _rightButton.text = rightButtonText; final completer = Completer<DialogResult>(); StreamSubscription leftSub; if (showLeftButton) { _leftButton.text = leftButtonText; _leftButton.removeAttribute('hidden'); leftSub = _leftButton.onClick.listen((_) { completer.complete(leftButtonResult); }); } else { _leftButton.setAttribute('hidden', 'true'); } final rightSub = _rightButton.onClick.listen((_) { completer.complete(rightButtonResult); }); _mdcDialog.open(); return completer.future.then((v) { leftSub?.cancel(); rightSub.cancel(); _mdcDialog.close(); return v; }); } }
dart-pad/lib/elements/dialog.dart/0
{'file_path': 'dart-pad/lib/elements/dialog.dart', 'repo_id': 'dart-pad', 'token_count': 1170}
// Copyright (c) 2019, 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. import 'dart:async'; import 'context.dart'; import 'editing/editor.dart'; class PlaygroundContext extends Context { final Editor editor; final _modeController = StreamController<String>.broadcast(); Document _dartDoc; Document _htmlDoc; Document _cssDoc; final _cssDirtyController = StreamController.broadcast(); final _dartDirtyController = StreamController.broadcast(); final _htmlDirtyController = StreamController.broadcast(); final _cssReconcileController = StreamController.broadcast(); final _dartReconcileController = StreamController.broadcast(); final _htmlReconcileController = StreamController.broadcast(); PlaygroundContext(this.editor) { editor.mode = 'dart'; _dartDoc = editor.document; _htmlDoc = editor.createDocument(content: '', mode: 'html'); _cssDoc = editor.createDocument(content: '', mode: 'css'); _dartDoc.onChange.listen((_) => _dartDirtyController.add(null)); _htmlDoc.onChange.listen((_) => _htmlDirtyController.add(null)); _cssDoc.onChange.listen((_) => _cssDirtyController.add(null)); _createReconciler(_cssDoc, _cssReconcileController, 250); _createReconciler(_dartDoc, _dartReconcileController, 1250); _createReconciler(_htmlDoc, _htmlReconcileController, 250); } Document get dartDocument => _dartDoc; Document get htmlDocument => _htmlDoc; Document get cssDocument => _cssDoc; @override String get dartSource => _dartDoc.value; @override set dartSource(String value) { _dartDoc.value = value; } @override String get htmlSource => _htmlDoc.value; @override set htmlSource(String value) { _htmlDoc.value = value; } @override String get cssSource => _cssDoc.value; @override set cssSource(String value) { _cssDoc.value = value; } @override String get activeMode => editor.mode; @override Stream<String> get onModeChange => _modeController.stream; bool hasWebContent() { return htmlSource.trim().isNotEmpty || cssSource.trim().isNotEmpty; } @override void switchTo(String name) { var oldMode = activeMode; if (name == 'dart') { editor.swapDocument(_dartDoc); } else if (name == 'html') { editor.swapDocument(_htmlDoc); } else if (name == 'css') { editor.swapDocument(_cssDoc); } if (oldMode != name) _modeController.add(name); editor.focus(); } @override String get focusedEditor { if (editor.document == _htmlDoc) return 'html'; if (editor.document == _cssDoc) return 'css'; return 'dart'; } Stream get onCssDirty => _cssDirtyController.stream; Stream get onDartDirty => _dartDirtyController.stream; Stream get onHtmlDirty => _htmlDirtyController.stream; Stream get onCssReconcile => _cssReconcileController.stream; Stream get onDartReconcile => _dartReconcileController.stream; Stream get onHtmlReconcile => _htmlReconcileController.stream; void markCssClean() => _cssDoc.markClean(); void markDartClean() => _dartDoc.markClean(); void markHtmlClean() => _htmlDoc.markClean(); /// Restore the focus to the last focused editor. void focus() => editor.focus(); void _createReconciler(Document doc, StreamController controller, int delay) { Timer timer; doc.onChange.listen((_) { if (timer != null) timer.cancel(); timer = Timer(Duration(milliseconds: delay), () { controller.add(null); }); }); } /// Return true if the current cursor position is in a whitespace char. bool cursorPositionIsWhitespace() { var document = editor.document; var str = document.value; var index = document.indexFromPos(document.cursor); if (index < 0 || index >= str.length) return false; var char = str[index]; return char != char.trim(); } }
dart-pad/lib/playground_context.dart/0
{'file_path': 'dart-pad/lib/playground_context.dart', 'repo_id': 'dart-pad', 'token_count': 1361}
// Copyright (c) 2015, 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. @TestOn('browser') import 'dart:html'; import 'package:dart_pad/embed.dart' as embed; import 'package:test/test.dart'; void main() { group('embed', () { setUp(() => embed.init(embed.EmbedOptions(embed.EmbedMode.flutter))); test('Editor tab is selected at init', () { final editorTab = querySelector('#editor-tab'); expect(editorTab.attributes.keys, contains('aria-selected')); expect(editorTab.classes, contains('mdc-tab--active')); }); test('Test tab is not selected at init', () { final testTab = querySelector('#test-tab'); expect(testTab.attributes.keys, isNot(contains('aria-selected'))); expect(testTab.classes, isNot(contains('mdc-tab--active'))); }); test('Test tab is selected when clicked.', () { final testTab = querySelector('#test-tab'); testTab.dispatchEvent(Event('click')); expect(testTab.attributes.keys, contains('aria-selected')); expect(testTab.classes, contains('mdc-tab--active')); }); test('Editor tab is not selected when test tab is clicked', () { final testTab = querySelector('#test-tab'); testTab.dispatchEvent(Event('click')); final editorTab = querySelector('#editor-tab'); expect(editorTab.attributes.keys, isNot(contains('aria-selected'))); expect(editorTab.classes, isNot(contains('mdc-tab--active'))); }); }); group('filterCloudUrls', () { test('cleans dart SDK urls', () { var trace = '(https://storage.googleapis.com/compilation_artifacts/2.2.0/dart_sdk.js:4537:11)'; expect(embed.filterCloudUrls(trace), '([Dart SDK Source]:4537:11)'); }); test('cleans flutter SDK urls', () { var trace = '(https://storage.googleapis.com/compilation_artifacts/2.2.0/flutter_web.js:96550:21)'; expect(embed.filterCloudUrls(trace), '([Flutter SDK Source]:96550:21)'); }); }); }
dart-pad/test/embed/embed_test.dart/0
{'file_path': 'dart-pad/test/embed/embed_test.dart', 'repo_id': 'dart-pad', 'token_count': 797}
import "click_handler_test.dart" as click_handler_test; import "client_test.dart" as client_test; import "link_matcher_test.dart" as link_matcher_test; import "url_template_test.dart" as url_template_test; /// Run tests from project root directory with the following command: /// pub run test -p "content-shell,dartium,chrome,safari" test/all_web_tests.dart main() { click_handler_test.main(); client_test.main(); link_matcher_test.main(); url_template_test.main(); }
dart-pad/third_party/pkg/route.dart/test/all_web_tests.dart/0
{'file_path': 'dart-pad/third_party/pkg/route.dart/test/all_web_tests.dart', 'repo_id': 'dart-pad', 'token_count': 164}
// Copyright (c) 2014, 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. library services.common; import 'dart:io'; import 'sdk_manager.dart'; const kMainDart = 'main.dart'; const kBootstrapDart = 'bootstrap.dart'; const kBootstrapFlutterCode = r''' import 'dart:ui' as ui; import 'main.dart' as user_code; void main() async { await ui.webOnlyInitializePlatform(); user_code.main(); } '''; const kBootstrapDartCode = r''' import 'main.dart' as user_code; void main() { user_code.main(); } '''; const sampleCode = ''' void main() { print("hello"); } '''; const sampleCodeWeb = """ import 'dart:html'; void main() { print("hello"); querySelector('#foo').text = 'bar'; } """; const sampleCodeFlutter = ''' import 'package:flutter/material.dart'; void main() async { runApp( MaterialApp( debugShowCheckedModeBanner: false, home: Scaffold( appBar: AppBar( title: Text('Hey there, boo!'), ), body: Center( child: Text( 'You are pretty okay.', ), ), ), ), ); } '''; const sampleCodeMultiFoo = """ import 'bar.dart'; void main() { print(bar()); } """; const sampleCodeMultiBar = ''' bar() { return 4; } '''; const sampleCodeAsync = """ import 'dart:html'; main() async { print("hello"); querySelector('#foo').text = 'bar'; var foo = await HttpRequest.getString('http://www.google.com'); print(foo); } """; const sampleCodeError = ''' void main() { print("hello") } '''; const sampleCodeErrors = ''' void main() { print1("hello"); print2("hello"); print3("hello"); } '''; const sampleStrongError = """ void main() { foo('whoops'); } void foo(int i) { print(i); } """; const sampleDart2Error = ''' class Foo { final bool isAlwaysNull; Foo(this.isAlwaysNull) {} } void main(List<String> argv) { var x = new Foo(null); var y = 1; y = x; } '''; class Lines { final List<int> _starts = <int>[]; Lines(String source) { final units = source.codeUnits; for (var i = 0; i < units.length; i++) { if (units[i] == 10) _starts.add(i); } } /// Return the 0-based line number. int getLineForOffset(int offset) { assert(offset != null); for (var i = 0; i < _starts.length; i++) { if (offset <= _starts[i]) return i; } return _starts.length; } } /// Returns the version of the current Dart runtime. /// /// The returned `String` is formatted as the [semver](http://semver.org) version /// string of the current Dart runtime, possibly followed by whitespace and other /// version and build details. String get vmVersion => Platform.version; /// If [str] has leading and trailing quotes, remove them. String stripMatchingQuotes(String str) { if (str.length <= 1) return str; if (str.startsWith("'") && str.endsWith("'")) { str = str.substring(1, str.length - 1); } else if (str.startsWith('"') && str.endsWith('"')) { str = str.substring(1, str.length - 1); } return str; } String get sdkPath => SdkManager.sdk.sdkPath;
dart-services/lib/src/common.dart/0
{'file_path': 'dart-services/lib/src/common.dart', 'repo_id': 'dart-services', 'token_count': 1222}
// Copyright (c) 2015, 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. library dart_pad.summarize; import 'package:crypto/crypto.dart'; import 'protos/dart_services.pb.dart' as proto; /// Instances of this class take string input of dart code as well as an /// analysis result, and output a text description ofthe code's size, packages, /// and other useful information. class Summarizer { final String dart; final String html; final String css; final proto.AnalysisResults analysis; _SummarizeToken storage; int _randomizer; static Map<String, List<int>> cuttoffs = <String, List<int>>{ 'size': <int>[8, 30, 1000], //0-7 = small, 8 - 29 = decent, 29+ = gigantic 'errorCount': <int>[1, 10, 100] }; static Map<String, String> codeKeyWords = <String, String>{ 'await': 'await', 'async': 'async', 'rpc': 'RESTful serverside app' }; static Map<String, String> additionKeyWords = <String, String>{ 'pirate': 'pirates', 'bird': 'birds', 'llama': 'llamas', 'dog': 'dogs' }; static Map<String, List<String>> categories = <String, List<String>>{ /// This [size] [codeQuantifier] contains [error] errors and warnings. 'size-2': <String>[ 'gigantic', 'Jupiterian sized', 'immense', 'massive', 'enormous', 'huge', 'epic', 'humongous' ], 'size-1': <String>[ 'decently sized', 'exceptional', 'awesome', 'amazing', 'visionary', 'legendary' ], 'size-0': <String>['itty-bitty', 'miniature', 'tiny', 'pint-sized'], 'compiledQuantifier': <String>['Dart program', 'pad'], 'failedQuantifier': <String>[ 'assemblage of characters', 'series of strings', 'grouping of letters' ], 'errorCount-2': <String>[ 'many', 'a motherload of', 'copious amounts of', 'unholy quantities of' ], 'errorCount-1': <String>[ 'some', 'a few', 'sparse amounts of', 'very few instances of' ], 'errorCount-0': <String>['zero', 'no', 'a nonexistent amount of', '0'], 'use': <String>['demonstrates', 'illustrates', 'depicts'], 'code-0': <String>['it'], 'code-1': <String>['It'], }; Summarizer({this.dart, this.html, this.css, this.analysis}) { if (dart == null) throw ArgumentError('Input cannot be null.'); _randomizer = _sumList(md5.convert(dart.codeUnits).bytes); storage = _SummarizeToken(dart, analysis: analysis); } bool get hasAnalysisResults => analysis != null; int _sumList(List<int> list) => list.reduce((int a, int b) => a + b); String _categorySelector(String category, int itemCount) { if (category == 'size' || category == 'errorCount') { final maxField = cuttoffs[category]; for (var counter = 0; counter < maxField.length; counter++) { if (itemCount < maxField[counter]) return '$category-$counter'; } return '$category-${maxField.length - 1}'; } else { return null; } } String _wordSelector(String category) { if (categories.containsKey(category)) { final returnSet = categories[category]; return returnSet.elementAt(_randomizer % returnSet.length); } else { return null; } } String _sentenceFiller(String word, [int size]) { if (size != null) { return _wordSelector(_categorySelector(word, size)); } else { return _wordSelector(word); } } String _additionList(List<String> list) { if (list.isEmpty) return ''; var englishList = ' Also, mentions '; for (var i = 0; i < list.length; i++) { englishList += list[i]; if (i < list.length - 2) englishList += ', '; if (i == list.length - 2) { if (i != 0) englishList += ','; englishList += ' and '; } } englishList += '. '; return englishList; // TODO: Tokenize features instead of returning as string. } List<String> additionSearch() => _additionSearch(); bool _usedInDartSource(String feature) => dart.contains(feature); List<String> _additionSearch() { final features = <String>[]; for (final feature in additionKeyWords.keys) { if (_usedInDartSource(feature)) features.add(additionKeyWords[feature]); } return features; } List<String> _codeSearch() { final features = <String>[]; for (final feature in codeKeyWords.keys) { if (_usedInDartSource(feature)) features.add(codeKeyWords[feature]); } return features; } String _featureList(List<String> list) { if (list.isEmpty) return '. '; var englishList = ', and ${_sentenceFiller('use')} use of '; for (var i = 0; i < list.length; i++) { englishList += list[i]; if (i < list.length - 2) englishList += ', '; if (i == list.length - 2) { if (i != 0) englishList += ','; englishList += ' and '; } } englishList += ' features. '; return englishList; } String _packageList(List<String> list, {String source}) { if (list.isEmpty) { return source == null ? '' : '. '; } var englishList = ''; if (source == 'packages') { englishList += ', and ${_sentenceFiller('code-0')} imports '; } else { englishList += '${_sentenceFiller('code-1')} imports the '; } for (var i = 0; i < list.length; i++) { englishList += "'${list[i]}'"; if (i < list.length - 2) englishList += ', '; if (i == list.length - 2) { if (i != 0) englishList += ','; englishList += ' and '; } } if (source == 'packages') { englishList += ' from external packages. '; } else { englishList += ' packages as well. '; } return englishList; } String _htmlCSS() { var htmlCSS = 'This code has '; if (_hasCSS && _hasHtml) { htmlCSS += 'associated html and css'; return htmlCSS; } if (!_hasCSS && !_hasHtml) { htmlCSS += 'no associated html or css'; return htmlCSS; } if (!_hasHtml) { htmlCSS += 'no '; } else { htmlCSS += 'some '; } htmlCSS += 'associated html and '; if (!_hasCSS) { htmlCSS += 'no '; } else { htmlCSS += 'some '; } htmlCSS += 'associated css'; return htmlCSS; } bool get _hasHtml => html != null && html.isNotEmpty; bool get _hasCSS => css != null && css.isNotEmpty; String returnAsSimpleSummary() { if (hasAnalysisResults) { var summary = ''; summary += 'This ${_sentenceFiller('size', storage.linesCode)} '; if (storage.errorPresent) { summary += '${_sentenceFiller('failedQuantifier')} contains '; } else { summary += '${_sentenceFiller('compiledQuantifier')} contains '; } summary += '${_sentenceFiller('errorCount', storage.errorCount)} '; summary += 'errors and warnings'; summary += '${_featureList(_codeSearch())}'; summary += '${_htmlCSS()}'; summary += '${_packageList(storage.packageImports, source: 'packages')}'; summary += '${_additionList(_additionSearch())}'; return summary.trim(); } else { var summary = 'Summary: '; summary += 'This is a ${_sentenceFiller('size', storage.linesCode)} '; summary += '${_sentenceFiller('compiledQuantifier')}'; summary += '${_featureList(_codeSearch())}'; summary += '${_htmlCSS()}'; summary += '${_additionList(_additionSearch())}'; return summary.trim(); } } String returnAsMarkDown() { // For now, we're just returning plain text. This might change at some point // to include some markdown styling as well. return returnAsSimpleSummary(); } } class _SummarizeToken { int linesCode; int packageCount; int errorCount; int warningCount; bool errorPresent; bool warningPresent; List<String> packageImports; List<proto.AnalysisIssue> errors; _SummarizeToken(String input, {proto.AnalysisResults analysis}) { linesCode = _linesOfCode(input); if (analysis != null) { errorPresent = analysis.issues .any((proto.AnalysisIssue issue) => issue.kind == 'error'); warningPresent = analysis.issues .any((proto.AnalysisIssue issue) => issue.kind == 'warning'); packageCount = analysis.packageImports.length; packageImports = analysis.packageImports; errors = analysis.issues; errorCount = errors.length; } } int _linesOfCode(String input) => input.split('\n').length; }
dart-services/lib/src/summarize.dart/0
{'file_path': 'dart-services/lib/src/summarize.dart', 'repo_id': 'dart-services', 'token_count': 3363}
// Copyright (c) 2014, 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. library services.redis_cache_test; import 'dart:async'; import 'dart:io'; import 'package:dart_services/src/common_server_impl.dart'; import 'package:dart_services/src/sdk_manager.dart'; import 'package:dart_services/src/server_cache.dart'; import 'package:logging/logging.dart'; import 'package:pedantic/pedantic.dart'; import 'package:synchronized/synchronized.dart'; import 'package:test/test.dart'; void main() => defineTests(); void defineTests() { /// Integration tests for the RedisCache implementation. /// /// We basically assume that redis and dartis work correctly -- this is /// exercising the connection maintenance and exception handling. group('RedisCache', () { // Note: all caches share values between them. RedisCache redisCache, redisCacheAlt; Process redisProcess, redisAltProcess; var logMessages = <String>[]; // Critical section handling -- do not run more than one test at a time // since they talk to the same redis instances. final singleTestOnly = Lock(); // Prevent cases where we might try to reenter addStream for either stdout // or stderr (which will throw a BadState). final singleStreamOnly = Lock(); Future<Process> startRedisProcessAndDrainIO(int port) async { final newRedisProcess = await Process.start('redis-server', ['--port', port.toString()]); unawaited(singleStreamOnly.synchronized(() async { await stdout.addStream(newRedisProcess.stdout); })); unawaited(singleStreamOnly.synchronized(() async { await stderr.addStream(newRedisProcess.stderr); })); return newRedisProcess; } setUpAll(() async { await SdkManager.sdk.init(); redisProcess = await startRedisProcessAndDrainIO(9501); log.onRecord.listen((LogRecord rec) { logMessages.add('${rec.level.name}: ${rec.time}: ${rec.message}'); print(logMessages.last); }); redisCache = RedisCache('redis://localhost:9501', 'aversion'); redisCacheAlt = RedisCache('redis://localhost:9501', 'bversion'); await Future.wait([redisCache.connected, redisCacheAlt.connected]); }); tearDown(() async { if (redisAltProcess != null) { redisAltProcess.kill(); await redisAltProcess.exitCode; redisAltProcess = null; } }); tearDownAll(() async { log.clearListeners(); await Future.wait([redisCache.shutdown(), redisCacheAlt.shutdown()]); redisProcess.kill(); await redisProcess.exitCode; }); test('Verify basic operation of RedisCache', () async { await singleTestOnly.synchronized(() async { logMessages = []; await expectLater(await redisCache.get('unknownkey'), isNull); await redisCache.set('unknownkey', 'value'); await expectLater(await redisCache.get('unknownkey'), equals('value')); await redisCache.remove('unknownkey'); await expectLater(await redisCache.get('unknownkey'), isNull); expect(logMessages, isEmpty); }); }); test('Verify values expire', () async { await singleTestOnly.synchronized(() async { logMessages = []; await redisCache.set('expiringkey', 'expiringValue', expiration: Duration(milliseconds: 1)); await Future.delayed(Duration(milliseconds: 100)); await expectLater(await redisCache.get('expiringkey'), isNull); expect(logMessages, isEmpty); }); }); test( 'Verify two caches with different versions give different results for keys', () async { await singleTestOnly.synchronized(() async { logMessages = []; await redisCache.set('differentVersionKey', 'value1'); await redisCacheAlt.set('differentVersionKey', 'value2'); await expectLater( await redisCache.get('differentVersionKey'), 'value1'); await expectLater( await redisCacheAlt.get('differentVersionKey'), 'value2'); expect(logMessages, isEmpty); }); }); test('Verify disconnected cache logs errors and returns nulls', () async { await singleTestOnly.synchronized(() async { logMessages = []; final redisCacheBroken = RedisCache('redis://localhost:9502', 'cversion'); try { await redisCacheBroken.set('aKey', 'value'); await expectLater(await redisCacheBroken.get('aKey'), isNull); await redisCacheBroken.remove('aKey'); expect( logMessages.join('\n'), stringContainsInOrder([ 'no cache available when setting key server:cversion:dart:', '+aKey', 'no cache available when getting key server:cversion:dart:', '+aKey', 'no cache available when removing key server:cversion:dart:', '+aKey', ])); } finally { await redisCacheBroken.shutdown(); } }); }); test('Verify cache that starts out disconnected retries and works (slow)', () async { await singleTestOnly.synchronized(() async { logMessages = []; final redisCacheRepairable = RedisCache('redis://localhost:9503', 'cversion'); try { // Wait for a retry message. while (logMessages.length < 2) { await (Future.delayed(Duration(milliseconds: 50))); } expect( logMessages.join('\n'), stringContainsInOrder([ 'reconnecting to redis://localhost:9503...\n', 'Unable to connect to redis server, reconnecting in', ])); // Start a redis server. redisAltProcess = await startRedisProcessAndDrainIO(9503); // Wait for connection. await redisCacheRepairable.connected; expect(logMessages.join('\n'), contains('Connected to redis server')); } finally { await redisCacheRepairable.shutdown(); } }); }); test( 'Verify that cache that stops responding temporarily times out and can recover', () async { await singleTestOnly.synchronized(() async { logMessages = []; await redisCache.set('beforeStop', 'truth'); redisProcess.kill(ProcessSignal.sigstop); // Don't fail the test before sending sigcont. final beforeStop = await redisCache.get('beforeStop'); await redisCache.disconnected; redisProcess.kill(ProcessSignal.sigcont); expect(beforeStop, isNull); await redisCache.connected; await expectLater(await redisCache.get('beforeStop'), equals('truth')); expect( logMessages.join('\n'), stringContainsInOrder([ 'timeout on get operation for key server:aversion:dart:', '+beforeStop', '(aversion): reconnecting', '(aversion): Connected to redis server', ])); }); }, onPlatform: {'windows': Skip('Windows does not have sigstop/sigcont')}); test( 'Verify cache that starts out connected but breaks retries until reconnection (slow)', () async { await singleTestOnly.synchronized(() async { logMessages = []; redisAltProcess = await startRedisProcessAndDrainIO(9504); final redisCacheHealing = RedisCache('redis://localhost:9504', 'cversion'); try { await redisCacheHealing.connected; await redisCacheHealing.set('missingKey', 'value'); // Kill process out from under the cache. redisAltProcess.kill(); await redisAltProcess.exitCode; redisAltProcess = null; // Try to talk to the cache and get an error. Wait for the disconnect // to be recognized. await expectLater(await redisCacheHealing.get('missingKey'), isNull); await redisCacheHealing.disconnected; // Start the server and verify we connect appropriately. redisAltProcess = await startRedisProcessAndDrainIO(9504); await redisCacheHealing.connected; expect( logMessages.join('\n'), stringContainsInOrder([ 'Connected to redis server', 'connection terminated with error SocketException', 'reconnecting to redis://localhost:9504', ])); expect(logMessages.last, contains('Connected to redis server')); } finally { await redisCacheHealing.shutdown(); } }); }); }); }
dart-services/test/redis_cache_test.dart/0
{'file_path': 'dart-services/test/redis_cache_test.dart', 'repo_id': 'dart-services', 'token_count': 3630}
import 'package:cloudflare_workers/cloudflare_workers.dart'; class TestClass extends DurableObject { @override FutureOr<Response> fetch(Request request) async { // These calls are transactional. final views = (await state.storage.get<int>('views') ?? 0) + 1; await state.storage.put('views', views); // Set an alarm to trigger in a few seconds (if not already set). if (await state.storage.getAlarm() == null) { await state.storage.setAlarm(DateTime.now().add(Duration(seconds: 2))); } return Response('Path "${request.url.path}" called $views times.'); } @override FutureOr<void> alarm() { print('Durable Object Alarm Called'); } } void main() { CloudflareWorkers( durableObjects: { 'TestClass': () => TestClass(), }, fetch: (request, env, ctx) { // Ignore browser favicon requests. if (request.url.toString().contains('favicon.ico')) { return Response(null); } // Get the DO namespace (defined in your wrangler.toml) final namespace = env.getDurableObjectNamespace('TEST'); // Get an ID for the DO (this can be based on the request, name, user ID etc) final id = namespace.idFromName(request.url.path); // Send the DO a request instance. return namespace.get(id).fetch(request); }, ); }
dart_edge/examples/cloudflare-durable-objects/lib/main.dart/0
{'file_path': 'dart_edge/examples/cloudflare-durable-objects/lib/main.dart', 'repo_id': 'dart_edge', 'token_count': 484}
import 'dart:js_util' as js_util; import 'package:js/js.dart'; import 'package:js/js_util.dart'; import 'package:edge/runtime/interop/utils_interop.dart'; @anonymous @JS() @staticInterop class KVNamespace { external factory KVNamespace(); } extension PropsKVNamespace on KVNamespace { Future<T> get<T>(String name, [KVNamespaceGetOptions? options]) => js_util.promiseToFuture( js_util.callMethod(this, 'get', [name, options ?? jsUndefined])); Future<KVNamespaceGetWithMetadataResult<T>> getWithMetadata<T>( String name, [ KVNamespaceGetOptions? options, ]) => js_util.promiseToFuture( js_util.callMethod(this, 'getWithMetadata', [name, options])); Future<void> put( String key, Object value, [ KVNamespacePutOptions? options, ]) => js_util.promiseToFuture<void>(js_util .callMethod(this, 'put', [key, value, options ?? jsUndefined])); Future<void> delete(/* string | string[] */ dynamic keys) => js_util.promiseToFuture<void>(js_util.callMethod(this, 'delete', [keys])); Future<KVNamespaceListResult> list([KVNamespaceListOptions? options]) => js_util.promiseToFuture(js_util.callMethod(this, 'list', [options])); } @anonymous @JS() @staticInterop class KVNamespaceGetWithMetadataResult<T> { external factory KVNamespaceGetWithMetadataResult(); } extension PropsKVNamespaceGetWithMetadataResult<T> on KVNamespaceGetWithMetadataResult { T get value => js_util.getProperty(this, 'value'); Object get metadata => js_util.getProperty(this, 'metadata'); } @anonymous @JS() @staticInterop class KVNamespaceGetOptions { external factory KVNamespaceGetOptions(); } extension PropsKVNamespaceGetOptions on KVNamespaceGetOptions { set type(String? value) { js_util.setProperty(this, 'type', value ?? jsUndefined); } set cacheTtl(int? value) { js_util.setProperty(this, 'expiration', value ?? jsUndefined); } } @anonymous @JS() @staticInterop class KVNamespacePutOptions { external factory KVNamespacePutOptions(); } extension PropsKVNamespacePutOptions on KVNamespacePutOptions { set expiration(DateTime? value) { js_util.setProperty(this, 'expiration', value != null ? value.millisecondsSinceEpoch / 1000 : jsUndefined); } set expirationTtl(int? value) { js_util.setProperty(this, 'expirationTtl', value ?? jsUndefined); } set metadata(Object? value) { js_util.setProperty( this, 'metadata', value != null ? jsify(value) : jsUndefined); } } @anonymous @JS() @staticInterop class KVNamespaceListResult { external factory KVNamespaceListResult(); } extension PropsKVNamespaceListResult on KVNamespaceListResult { bool get listComplete => js_util.getProperty(this, 'list_complete'); external dynamic get keys; external String? get cursor; } @anonymous @JS() @staticInterop class KVNamespaceListKey { external factory KVNamespaceListKey(); } extension PropsKVNamespaceListKey on KVNamespaceListKey { String get name => js_util.getProperty(this, 'name'); int? get expiration => js_util.getProperty(this, 'expiration'); Object? get metadata => js_util.getProperty(this, 'metadata'); } @anonymous @JS() @staticInterop class KVNamespaceListOptions { external factory KVNamespaceListOptions(); } extension PropsKVNamespaceListOptions on KVNamespaceListOptions { set limit(int? value) { js_util.setProperty(this, 'limit', value ?? jsUndefined); } set prefix(String? value) { js_util.setProperty(this, 'prefix', value); } set cursor(String? value) { js_util.setProperty(this, 'cursor', value); } }
dart_edge/packages/cloudflare_workers/lib/interop/kv_namespace_interop.dart/0
{'file_path': 'dart_edge/packages/cloudflare_workers/lib/interop/kv_namespace_interop.dart', 'repo_id': 'dart_edge', 'token_count': 1291}
import 'dart:async'; import 'package:edge/runtime/abort.dart'; import 'package:edge/runtime/headers.dart'; import 'package:js_bindings/js_bindings.dart' as interop; import 'package:edge/runtime/request.dart'; import 'package:edge/runtime/response.dart'; import '../interop/durable_object_interop.dart' as interop; import 'socket.dart'; abstract class Fetcher { final interop.Fetcher _delegate; Fetcher(this._delegate); Future<Response> fetch( Request request, { String? method, Headers? headers, Object? body, String? referrer, interop.ReferrerPolicy? referrerPolicy, interop.RequestMode? mode, interop.RequestCredentials? credentials, interop.RequestCache? cache, interop.RequestRedirect? redirect, String? integrity, bool? keepalive, AbortSignal? signal, interop.RequestDuplex? duplex, }) async { final response = await _delegate.fetch( request.delegate, interop.RequestInit( method: method, headers: headers?.delegate, body: body, referrer: referrer, referrerPolicy: referrerPolicy, mode: mode, credentials: credentials, cache: cache, redirect: redirect, integrity: integrity, keepalive: keepalive, signal: signal?.delegate, duplex: duplex, ), ); return responseFromJsObject(response); } Socket connect(String address, [SocketOptions? options]) => socketFromJsObject(_delegate.connect(address, options?.delegate)); }
dart_edge/packages/cloudflare_workers/lib/public/fetcher.dart/0
{'file_path': 'dart_edge/packages/cloudflare_workers/lib/public/fetcher.dart', 'repo_id': 'dart_edge', 'token_count': 599}
import 'package:edge/runtime.dart'; void main() { // Setup the runtime environment. setupRuntime(); // Register a fetch event listener. addFetchEventListener((event) { final request = event.request; // Ignore browser favicon requests. if (request.url.toString().contains('favicon')) { event.respondWith(Response('')); } event.respondWith(fetchHandler(request)); }); } /// A fetch event handler. Future<Response> fetchHandler(Request request) async { return Response('Hello, world!!', status: 200); }
dart_edge/packages/edge/example/lib/main.dart/0
{'file_path': 'dart_edge/packages/edge/example/lib/main.dart', 'repo_id': 'dart_edge', 'token_count': 172}
import 'dart:js'; export 'dart:async' show FutureOr; export 'runtime/top.dart'; export 'runtime/abort.dart' show AbortController, AbortSignal; export 'runtime/blob.dart' show Blob, BlobPropertyBag; export 'runtime/body.dart' show Body; export 'runtime/cache/cache_query_options.dart' show CacheQueryOptions, MultiCacheQueryOptions; export 'runtime/cache/cache_storage.dart' show CacheStorage, caches; export 'runtime/cache/cache.dart' show Cache; export 'runtime/fetch_event.dart' show FetchEvent; export 'runtime/file.dart' show File; export 'runtime/form_data.dart' show FormData, FormDataEntryValue; export 'runtime/headers.dart' show Headers; export 'runtime/readable_stream.dart' show ReadableStream; export 'runtime/request.dart' show Request; export 'runtime/resource.dart' show Resource; export 'runtime/response.dart' show Response; export 'runtime/text_decoder.dart' show TextDecoder, TextDecodeOptions, TextDecoderOptions; export 'runtime/text_encoder.dart' show TextEncoder, TextEncoderEncodeIntoResult; export 'package:js_bindings/bindings/referrer_policy.dart' show ReferrerPolicy; export 'package:js_bindings/bindings/fetch.dart' show ResponseType, RequestDuplex, RequestCache, RequestCredentials, RequestDestination, RequestMode, RequestRedirect; /// This should be called before any other platform code is run. void setupRuntime() { context['window'] ??= context['self']; }
dart_edge/packages/edge/lib/runtime.dart/0
{'file_path': 'dart_edge/packages/edge/lib/runtime.dart', 'repo_id': 'dart_edge', 'token_count': 510}
import 'package:js/js.dart' as js; import 'package:js_bindings/js_bindings.dart' as interop; import 'promise_interop.dart'; @js.JS() external void addEventListener( String type, void Function(interop.ExtendableEvent event) callback, ); @js.JS('fetch') external Promise<interop.Response> fetch( interop.Request request, [ // Object, since we need to pass a Map in some cases. Object? init, ]); @js.JS('atob') external String atob(String encodedData); @js.JS('btoa') external String btoa(String encodedData); @js.JS('setInterval') external int setInterval( void Function() callback, int milliseconds, ); @js.JS('clearInterval') external void clearInterval(int handle); @js.JS('setTimeout') external int setTimeout( void Function() callback, int milliseconds, ); @js.JS('clearTimeout') external void clearTimeout(int handle);
dart_edge/packages/edge/lib/runtime/interop/scope_interop.dart/0
{'file_path': 'dart_edge/packages/edge/lib/runtime/interop/scope_interop.dart', 'repo_id': 'dart_edge', 'token_count': 285}
import 'package:edge/runtime.dart'; import 'package:test/test.dart'; void main() { group('Request', () { test('.method', () { final resource = Resource('https://foo.com'); expect( Request(resource).method, 'GET', reason: 'The default method is should be GET', ); expect(Request(resource, method: 'GET').method, 'GET'); expect(Request(resource, method: 'POST').method, 'POST'); expect(Request(resource, method: 'OPTIONS').method, 'OPTIONS'); }); test('.url', () { // Browser adds a / to the path if empty final uri = Uri.parse('https://foo.com/'); final resource = Resource.uri(uri); expect(Request(resource).url, uri); expect(Request(Resource('https://foo.com?foo=bar')).url.queryParameters, { 'foo': 'bar', }); }); test('.headers', () { final request = Request( Resource( 'https://foo.com', ), headers: Headers({ 'foo': 'bar', }), ); expect(request.headers['foo'], 'bar'); }); test('.destination', () { final request = Request(Resource('https://foo.com')); expect(request.destination, RequestDestination.empty); }); test('.destination', () { final request = Request( Resource('https://foo.com'), referrer: 'https://example.com', ); expect(request.referrer.isNotEmpty, true); }); test('.referrerPolicy', () { final request = Request( Resource('https://foo.com'), referrerPolicy: ReferrerPolicy.origin, ); expect(request.referrerPolicy, ReferrerPolicy.origin); }); test('.mode', () { final request = Request( Resource('https://foo.com'), mode: RequestMode.cors, ); expect(request.mode, RequestMode.cors); }); test('.mode', () { final request = Request( Resource('https://foo.com'), credentials: RequestCredentials.sameOrigin, ); expect(request.credentials, RequestCredentials.sameOrigin); }); test('.cache', () { final request = Request( Resource('https://foo.com'), cache: RequestCache.noStore, ); expect(request.cache, RequestCache.noStore); }); test('.redirect', () { final request = Request( Resource('https://foo.com'), redirect: RequestRedirect.error, ); expect(request.redirect, RequestRedirect.error); }); test('.destination', () { final request = Request( Resource('https://foo.com'), integrity: 'foo', ); expect(request.integrity, 'foo'); }); test('.keepalive', () { final request = Request(Resource('https://foo.com')); final request2 = Request( Resource('https://foo.com'), keepalive: true, ); expect(request.keepalive, false); expect(request2.keepalive, true); }); test('.signal', () { final request = Request(Resource('https://foo.com')); // Forces it through to make sure it comes from the correct delegate. // ignore: unnecessary_type_check expect(request.signal is AbortSignal, true); }); test('.bodyUsed', () async { final request = Request( Resource( 'https://foo.com', ), method: 'POST', body: 'foo', ); expect(request.bodyUsed, false); expect(await request.text(), 'foo'); expect(request.bodyUsed, true); }); test('.clone()', () async { final request = Request(Resource('https://foo.com')); final clone = request.clone(); expect(request.url.toString(), clone.url.toString()); }); // TODO body // TODO formData // TODO json test('.text()', () async { final request = Request( Resource( 'https://foo.com', ), method: 'POST', body: 'foo', ); expect(await request.text(), 'foo'); }); }); }
dart_edge/packages/edge/test/request_test.dart/0
{'file_path': 'dart_edge/packages/edge/test/request_test.dart', 'repo_id': 'dart_edge', 'token_count': 1697}
name: netlify_edge description: Write and deploy Dart functions to the Netlify Edge network. homepage: https://dartedge.dev repository: https://github.com/invertase/dart_edge/tree/main/packages/netlify_edge version: 0.0.1-dev.1 environment: sdk: ">=2.18.5 <3.0.0" dependencies: edge: ^0.0.2 js_bindings: ^0.1.0 js: ^0.6.5 path: ^1.8.3 dev_dependencies: lints: ^2.0.0 test: ^1.16.0
dart_edge/packages/netlify_edge/pubspec.yaml/0
{'file_path': 'dart_edge/packages/netlify_edge/pubspec.yaml', 'repo_id': 'dart_edge', 'token_count': 180}
import 'package:js_bindings/js_bindings.dart' as interop; import 'package:edge/runtime/request.dart'; import '../interop/request_interop.dart'; extension VercelEdgeRequestExtension on Request { IncomingRequestVercelProperties get vc => IncomingRequestVercelProperties._(delegate); } class IncomingRequestVercelProperties { final interop.Request _delegate; IncomingRequestVercelProperties._(this._delegate); String? get ipAddress => _delegate.ipAddress; String? get city => _delegate.city; String? get country => _delegate.country; String? get region => _delegate.region; String? get countryRegion => _delegate.countryRegion; String? get latitude => _delegate.latitude; String? get longitude => _delegate.longitude; }
dart_edge/packages/vercel_edge/lib/public/request.dart/0
{'file_path': 'dart_edge/packages/vercel_edge/lib/public/request.dart', 'repo_id': 'dart_edge', 'token_count': 236}
version: 2 updates: - package-ecosystem: "github-actions" directory: "/" schedule: interval: "daily" - package-ecosystem: "npm" directory: "/docs" schedule: interval: "weekly" - package-ecosystem: "npm" directory: "/extensions/vscode" schedule: interval: "weekly" - package-ecosystem: "pub" directory: "/bricks/create_dart_frog/hooks" schedule: interval: "daily" - package-ecosystem: "pub" directory: "/bricks/dart_frog_dev_server/hooks" schedule: interval: "daily" - package-ecosystem: "pub" directory: "/bricks/dart_frog_prod_server/hooks" schedule: interval: "daily" - package-ecosystem: "pub" directory: "/examples/echo" schedule: interval: "daily" - package-ecosystem: "pub" directory: "/examples/hello_world" schedule: interval: "daily" - package-ecosystem: "pub" directory: "/examples/web_socket_counter" schedule: interval: "daily" - package-ecosystem: "pub" directory: "/examples/counter" schedule: interval: "daily" - package-ecosystem: "pub" directory: "/examples/todos" schedule: interval: "daily" - package-ecosystem: "pub" directory: "/examples/todos/packages/todos_data_source" schedule: interval: "daily" - package-ecosystem: "pub" directory: "/examples/todos/packages/in_memory_todos_data_source" schedule: interval: "daily" - package-ecosystem: "pub" directory: "/examples/kitchen_sink" schedule: interval: "daily" - package-ecosystem: "pub" directory: "/packages/dart_frog_cli" schedule: interval: "daily" - package-ecosystem: "pub" directory: "/packages/dart_frog_cli/e2e" schedule: interval: "daily" - package-ecosystem: "pub" directory: "/packages/dart_frog_gen" schedule: interval: "daily" - package-ecosystem: "pub" directory: "/packages/dart_frog" schedule: interval: "daily" - package-ecosystem: "pub" directory: "/packages/dart_frog_web_socket" schedule: interval: "daily" - package-ecosystem: "pub" directory: "/packages/dart_frog_auth" schedule: interval: "daily"
dart_frog/.github/dependabot.yaml/0
{'file_path': 'dart_frog/.github/dependabot.yaml', 'repo_id': 'dart_frog', 'token_count': 924}
import 'dart:io'; import 'package:dart_frog_new_hooks/src/exit_overrides.dart'; import 'package:test/test.dart'; void main() { group('ExitOverrides', () { group('runZoned', () { test('uses default exit when not specified', () { ExitOverrides.runZoned(() { final overrides = ExitOverrides.current; expect(overrides!.exit, equals(exit)); }); }); test('uses custom exit when specified', () { ExitOverrides.runZoned( () { final overrides = ExitOverrides.current; expect(overrides!.exit, isNot(equals(exit))); }, exit: (_) {}, ); }); }); }); }
dart_frog/bricks/dart_frog_new/hooks/test/src/exit_overrides_test.dart/0
{'file_path': 'dart_frog/bricks/dart_frog_new/hooks/test/src/exit_overrides_test.dart', 'repo_id': 'dart_frog', 'token_count': 321}
name: dart_frog_prod_server_hooks publish_to: none environment: sdk: ">=3.0.0 <4.0.0" dependencies: dart_frog_gen: ^1.0.0 io: ^1.0.3 mason: ^0.1.0-dev.39 path: ^1.8.1 pubspec_lock: ^3.0.2 dev_dependencies: mocktail: ^1.0.0 test: ^1.19.2 very_good_analysis: ^5.0.0
dart_frog/bricks/dart_frog_prod_server/hooks/pubspec.yaml/0
{'file_path': 'dart_frog/bricks/dart_frog_prod_server/hooks/pubspec.yaml', 'repo_id': 'dart_frog', 'token_count': 154}
import 'package:basic_authentication/user_repository.dart'; import 'package:dart_frog/dart_frog.dart'; import 'package:dart_frog_auth/dart_frog_auth.dart'; Handler middleware(Handler handler) { final userRepository = UserRepository(); return handler .use( basicAuthentication<User>( authenticator: (context, username, password) { final repository = context.read<UserRepository>(); return repository.userFromCredentials(username, password); }, applies: (RequestContext context) async => context.request.method != HttpMethod.post, ), ) .use(requestLogger()) .use(provider<UserRepository>((_) => userRepository)); }
dart_frog/examples/basic_authentication/routes/users/_middleware.dart/0
{'file_path': 'dart_frog/examples/basic_authentication/routes/users/_middleware.dart', 'repo_id': 'dart_frog', 'token_count': 288}
import 'package:bearer_authentication/session_repository.dart'; import 'package:bearer_authentication/user_repository.dart'; import 'package:dart_frog/dart_frog.dart'; import 'package:dart_frog_auth/dart_frog_auth.dart'; Handler middleware(Handler handler) { return handler .use( bearerAuthentication<User>( authenticator: (context, token) async { final sessionRepository = context.read<SessionRepository>(); final userRepository = context.read<UserRepository>(); final session = await sessionRepository.sessionFromToken(token); return session != null ? userRepository.userFromId(session.userId) : null; }, applies: (RequestContext context) async => context.request.method != HttpMethod.post, ), ) .use(requestLogger()) .use(provider<UserRepository>((_) => UserRepository())) .use(provider<SessionRepository>((_) => const SessionRepository())); }
dart_frog/examples/bearer_authentication/routes/users/_middleware.dart/0
{'file_path': 'dart_frog/examples/bearer_authentication/routes/users/_middleware.dart', 'repo_id': 'dart_frog', 'token_count': 418}
import 'dart:io'; import 'package:dart_frog/dart_frog.dart'; import 'package:mocktail/mocktail.dart'; import 'package:test/test.dart'; import '../../routes/index.dart' as route; class _MockRequestContext extends Mock implements RequestContext {} void main() { group('GET /', () { test('responds with a 200 and count.', () async { const count = 42; final context = _MockRequestContext(); when(() => context.read<int>()).thenReturn(count); final response = route.onRequest(context); expect(response.statusCode, equals(HttpStatus.ok)); expect( response.body(), completion( equals('You have requested this route $count time(s).'), ), ); }); }); }
dart_frog/examples/counter/test/routes/index_test.dart/0
{'file_path': 'dart_frog/examples/counter/test/routes/index_test.dart', 'repo_id': 'dart_frog', 'token_count': 285}
import 'dart:io'; import 'package:dart_frog/dart_frog.dart'; Handler middleware(Handler handler) { return (context) { if (!context.request.headers.containsKey(HttpHeaders.authorizationHeader)) { return Response(statusCode: HttpStatus.unauthorized); } return handler(context); }; }
dart_frog/examples/kitchen_sink/routes/api/_middleware.dart/0
{'file_path': 'dart_frog/examples/kitchen_sink/routes/api/_middleware.dart', 'repo_id': 'dart_frog', 'token_count': 108}
import 'dart:io'; import 'package:dart_frog/dart_frog.dart'; import 'package:mocktail/mocktail.dart'; import 'package:test/test.dart'; import '../../../routes/messages/index.dart' as route; class _MockRequestContext extends Mock implements RequestContext {} void main() { group('POST /', () { test('responds with a 200 and message in body', () async { const message = 'Hello World'; final request = Request.post( Uri.parse('http://localhost/'), body: message, ); final context = _MockRequestContext(); when(() => context.request).thenReturn(request); final response = await route.onRequest(context); expect(response.statusCode, equals(HttpStatus.ok)); expect(response.body(), completion(equals('message: $message'))); }); }); }
dart_frog/examples/kitchen_sink/test/routes/messages/index_test.dart/0
{'file_path': 'dart_frog/examples/kitchen_sink/test/routes/messages/index_test.dart', 'repo_id': 'dart_frog', 'token_count': 292}
import 'package:in_memory_todos_data_source/in_memory_todos_data_source.dart'; import 'package:test/test.dart'; void main() { group('InMemoryTodosDataSource', () { late TodosDataSource dataSource; setUp(() { dataSource = InMemoryTodosDataSource(); }); group('create', () { test('returns the newly created todo', () async { final todo = Todo(title: 'title'); final createdTodo = await dataSource.create(todo); expect(createdTodo.id, isNotNull); expect(createdTodo.title, equals(todo.title)); expect(createdTodo.description, isEmpty); expect(createdTodo.isCompleted, isFalse); }); }); group('readAll', () { test('returns an empty list when there are no todos', () { expect(dataSource.readAll(), completion(isEmpty)); }); test('returns a populated list when there are todos', () async { final todo = Todo(title: 'title'); final createdTodo = await dataSource.create(todo); expect(dataSource.readAll(), completion(equals([createdTodo]))); }); }); group('read', () { test('return null when todo does not exist', () { expect(dataSource.read('id'), completion(isNull)); }); test('returns a todo when it exists', () async { final todo = Todo(title: 'title'); final createdTodo = await dataSource.create(todo); expect( dataSource.read(createdTodo.id!), completion(equals(createdTodo)), ); }); }); group('update', () { test('returns updated todo', () async { final todo = Todo(title: 'title'); final updatedTodo = Todo(title: 'new title'); final createdTodo = await dataSource.create(todo); final newTodo = await dataSource.update(createdTodo.id!, updatedTodo); expect(dataSource.readAll(), completion(equals([newTodo]))); expect(newTodo.id, equals(todo.id)); expect(newTodo.title, equals(updatedTodo.title)); expect(newTodo.description, equals(todo.description)); expect(newTodo.isCompleted, equals(todo.isCompleted)); }); }); group('delete', () { test('removes the todo', () async { final todo = Todo(title: 'title'); final createdTodo = await dataSource.create(todo); await dataSource.delete(createdTodo.id!); expect(dataSource.readAll(), completion(isEmpty)); }); }); }); }
dart_frog/examples/todos/packages/in_memory_todos_data_source/test/src/in_memory_todos_data_source_test.dart/0
{'file_path': 'dart_frog/examples/todos/packages/in_memory_todos_data_source/test/src/in_memory_todos_data_source_test.dart', 'repo_id': 'dart_frog', 'token_count': 1010}
import 'dart:async'; import 'dart:io'; import 'package:dart_frog/dart_frog.dart'; import 'package:todos_data_source/todos_data_source.dart'; FutureOr<Response> onRequest(RequestContext context, String id) async { final dataSource = context.read<TodosDataSource>(); final todo = await dataSource.read(id); if (todo == null) { return Response(statusCode: HttpStatus.notFound, body: 'Not found'); } switch (context.request.method) { case HttpMethod.get: return _get(context, todo); case HttpMethod.put: return _put(context, id, todo); case HttpMethod.delete: return _delete(context, id); case HttpMethod.head: case HttpMethod.options: case HttpMethod.patch: case HttpMethod.post: return Response(statusCode: HttpStatus.methodNotAllowed); } } Future<Response> _get(RequestContext context, Todo todo) async { return Response.json(body: todo); } Future<Response> _put(RequestContext context, String id, Todo todo) async { final dataSource = context.read<TodosDataSource>(); final updatedTodo = Todo.fromJson( await context.request.json() as Map<String, dynamic>, ); final newTodo = await dataSource.update( id, todo.copyWith( title: updatedTodo.title, description: updatedTodo.description, isCompleted: updatedTodo.isCompleted, ), ); return Response.json(body: newTodo); } Future<Response> _delete(RequestContext context, String id) async { final dataSource = context.read<TodosDataSource>(); await dataSource.delete(id); return Response(statusCode: HttpStatus.noContent); }
dart_frog/examples/todos/routes/todos/[id].dart/0
{'file_path': 'dart_frog/examples/todos/routes/todos/[id].dart', 'repo_id': 'dart_frog', 'token_count': 573}
import 'package:bloc_test/bloc_test.dart'; import 'package:test/test.dart'; import 'package:web_socket_counter/counter/cubit/counter_cubit.dart'; void main() { group('CounterCubit', () { test('initial state is 0', () { expect(CounterCubit().state, equals(0)); }); blocTest<CounterCubit, int>( 'emits [1] when increment is called', build: CounterCubit.new, act: (cubit) => cubit.increment(), expect: () => [1], ); blocTest<CounterCubit, int>( 'emits [-1] when decrement is called', build: CounterCubit.new, act: (cubit) => cubit.decrement(), expect: () => [-1], ); }); }
dart_frog/examples/web_socket_counter/test/counter/cubit/counter_cubit_test.dart/0
{'file_path': 'dart_frog/examples/web_socket_counter/test/counter/cubit/counter_cubit_test.dart', 'repo_id': 'dart_frog', 'token_count': 279}
/// {@template http_method} /// HTTP Method such as GET or PUT. /// {@endtemplate} enum HttpMethod { /// DELETE HTTP Method delete('DELETE'), /// GET HTTP Method get('GET'), /// HEAD HTTP Method head('HEAD'), /// OPTIONS HTTP Method options('OPTIONS'), /// PATCH HTTP Method patch('PATCH'), /// POST HTTP Method post('POST'), /// PUT HTTP Method put('PUT'); /// {@macro http_method} const HttpMethod(this.value); /// The HTTP method value as a string. final String value; }
dart_frog/packages/dart_frog/lib/src/http_method.dart/0
{'file_path': 'dart_frog/packages/dart_frog/lib/src/http_method.dart', 'repo_id': 'dart_frog', 'token_count': 168}
import 'dart:io'; import 'package:dart_frog/dart_frog.dart'; import 'package:http/http.dart' as http; import 'package:mocktail/mocktail.dart'; import 'package:test/test.dart'; class _MockRequestContext extends Mock implements RequestContext {} void main() { test('multiple middleware can be used on a handler', () async { const stringValue = '__test_value__'; const intValue = 42; Handler stringProvider(Handler handler) { return handler.use(provider<String>((_) => stringValue)); } Handler intProvider(Handler handler) { return handler.use(provider<int>((_) => intValue)); } Handler middleware(Handler handler) { return handler.use(stringProvider).use(intProvider); } Response onRequest(RequestContext context) { final stringValue = context.read<String>(); final intValue = context.read<int>(); return Response(body: '$stringValue $intValue'); } final handler = const Pipeline().addMiddleware(middleware).addHandler(onRequest); final server = await serve(handler, 'localhost', 3020); final client = http.Client(); final response = await client.get(Uri.parse('http://localhost:3020/')); await expectLater(response.statusCode, equals(HttpStatus.ok)); await expectLater(response.body, equals('$stringValue $intValue')); await server.close(); }); test('middleware can be used to read the request body', () async { Middleware requestValidator() { return (handler) { return (context) async { final body = await context.request.body(); if (body.isEmpty) return Response(statusCode: HttpStatus.badRequest); return handler(context); }; }; } Future<Response> onRequest(RequestContext context) async { final body = await context.request.body(); return Response(body: 'body: $body'); } final handler = const Pipeline() .addMiddleware(requestValidator()) .addHandler(onRequest); var request = Request.get(Uri.parse('http://localhost/')); var context = _MockRequestContext(); when(() => context.request).thenReturn(request); var response = await handler(context); expect(response.statusCode, equals(HttpStatus.badRequest)); const body = '__test_body__'; request = Request.get(Uri.parse('http://localhost/'), body: body); context = _MockRequestContext(); when(() => context.request).thenReturn(request); response = await handler(context); expect(response.statusCode, equals(HttpStatus.ok)); expect(await response.body(), equals('body: $body')); }); test('middleware can be used to read the response body', () async { const emptyBody = '(empty)'; Middleware responseValidator() { return (handler) { return (context) async { final response = await handler(context); final body = await response.body(); if (body.isEmpty) return Response(body: emptyBody); return response; }; }; } Future<Response> onRequest(RequestContext context) async { final body = await context.request.body(); return Response(body: body); } final handler = const Pipeline() .addMiddleware(responseValidator()) .addHandler(onRequest); var request = Request.get(Uri.parse('http://localhost/')); var context = _MockRequestContext(); when(() => context.request).thenReturn(request); var response = await handler(context); expect(response.statusCode, equals(HttpStatus.ok)); expect(response.body(), completion(equals(emptyBody))); const body = '__test_body__'; request = Request.get(Uri.parse('http://localhost/'), body: body); context = _MockRequestContext(); when(() => context.request).thenReturn(request); response = await handler(context); expect(response.statusCode, equals(HttpStatus.ok)); expect(response.body(), completion(equals(body))); }); test('chaining middleware retains request context', () async { const value = 'test-value'; Middleware noop() => (handler) => (context) => handler(context); Future<Response> onRequest(RequestContext context) async { final value = context.read<String>(); return Response(body: value); } final handler = const Pipeline().addMiddleware(noop()).addHandler(onRequest); final request = Request.get(Uri.parse('http://localhost/')); final context = _MockRequestContext(); when(() => context.read<String>()).thenReturn(value); when(() => context.request).thenReturn(request); final response = await handler(context); expect(response.statusCode, equals(HttpStatus.ok)); expect(response.body(), completion(equals(value))); }); }
dart_frog/packages/dart_frog/test/src/middleware_test.dart/0
{'file_path': 'dart_frog/packages/dart_frog/test/src/middleware_test.dart', 'repo_id': 'dart_frog', 'token_count': 1628}
import 'dart:convert'; import 'dart:io'; import 'package:dart_frog/dart_frog.dart'; extension on Map<String, String> { String? authorization(String type) { final value = this['Authorization']?.split(' '); if (value != null && value.length == 2 && value.first == type) { return value.last; } return null; } String? bearer() => authorization('Bearer'); String? basic() => authorization('Basic'); } /// Function definition for the predicate function used by Dart Frog Auth /// middleware to determine if the request should be authenticated or not. typedef Applies = Future<bool> Function(RequestContext); Future<bool> _defaultApplies(RequestContext context) async => true; /// Authentication that uses the `Authorization` header with the `Basic` scheme. /// /// `Basic` scheme expects the header to be in the format: /// ``` /// Authorization: Basic <token> /// ``` /// /// Token should be a base64 encoded string of the format: /// ``` /// <username>:<password> /// ``` /// /// In order to use this middleware, you must provide a function that will /// return a user object from the username, password and request context. /// /// If the given function returns null for the given username and password, /// the middleware will return a `401 Unauthorized` response. /// /// By default, this middleware will apply to all routes. You can change this /// behavior by providing a function that returns a boolean value based on the /// [RequestContext]. If the function returns false, the middleware will not /// apply to the route and the call will have authentication validation. Middleware basicAuthentication<T extends Object>({ @Deprecated( 'Deprecated in favor of authenticator. ' 'This will be removed in future versions', ) Future<T?> Function( String username, String password, )? userFromCredentials, Future<T?> Function( RequestContext context, String username, String password, )? authenticator, Applies applies = _defaultApplies, }) { assert( userFromCredentials != null || authenticator != null, 'You must provide either a userFromCredentials or a ' 'authenticator function', ); return (handler) => (context) async { if (!await applies(context)) { return handler(context); } Future<T?> call(String username, String password) async { if (userFromCredentials != null) { return userFromCredentials(username, password); } else { return authenticator!(context, username, password); } } final authorization = context.request.headers.basic(); if (authorization != null) { final [username, password] = String.fromCharCodes(base64Decode(authorization)).split(':'); final user = await call(username, password); if (user != null) { return handler(context.provide(() => user)); } } return Response(statusCode: HttpStatus.unauthorized); }; } /// Authentication that uses the `Authorization` header with the `Bearer` /// scheme. /// /// `Bearer` scheme expects the header to be in the format: /// ``` /// Authorization: Bearer <token> /// ``` /// /// The token format is up to the user. Usually it will be an encrypted token. /// /// In order to use this middleware, you must provide a function that will /// return a user object from the received token and request context. /// /// If the given function returns null for the given username and password, /// the middleware will return a `401 Unauthorized` response. /// /// By default, this middleware will apply to all routes. You can change this /// behavior by providing a function that returns a boolean value based on the /// [RequestContext]. If the function returns false, the middleware will not /// apply to the route and the call will have no authentication validation. Middleware bearerAuthentication<T extends Object>({ @Deprecated( 'Deprecated in favor of authenticator. ' 'This will be removed in future versions', ) Future<T?> Function(String token)? userFromToken, Future<T?> Function(RequestContext context, String token)? authenticator, Applies applies = _defaultApplies, }) { assert( userFromToken != null || authenticator != null, 'You must provide either a userFromToken or a ' 'authenticator function', ); return (handler) => (context) async { if (!await applies(context)) { return handler(context); } Future<T?> call(String token) async { if (userFromToken != null) { return userFromToken(token); } else { return authenticator!(context, token); } } final authorization = context.request.headers.bearer(); if (authorization != null) { final user = await call(authorization); if (user != null) { return handler(context.provide(() => user)); } } return Response(statusCode: HttpStatus.unauthorized); }; }
dart_frog/packages/dart_frog_auth/lib/src/dart_frog_auth.dart/0
{'file_path': 'dart_frog/packages/dart_frog_auth/lib/src/dart_frog_auth.dart', 'repo_id': 'dart_frog', 'token_count': 1653}
import 'dart:io'; import 'package:dart_frog_cli/src/daemon/daemon.dart'; import 'package:test/test.dart'; import '../helpers/helpers.dart'; /// Objectives: /// /// * Generate a new Dart Frog project via `dart_frog create` /// * Start the daemon /// * verify daemon is ready /// * send invalid messages /// * request daemon.* methods void main() { const projectName = 'example'; final tempDirectory = Directory.systemTemp.createTempSync(); late Process daemonProcess; late final DaemonStdioHelper daemonStdio; setUpAll(() async { await dartFrogCreate( projectName: projectName, directory: tempDirectory, ); daemonProcess = await dartFrogDaemonStart(); daemonStdio = DaemonStdioHelper(daemonProcess); addTearDown(() => daemonStdio.dispose()); }); group('daemon domain', () { test('daemon is ready', () async { final readyEvent = await daemonStdio.awaitForDaemonEvent('daemon.ready'); expect( readyEvent.params?.keys, containsAll(['version', 'processId']), ); }); group('daemon responds to invalid messages', () { test('daemon responds to an invalid message', () async { await daemonStdio.sendStringMessage('ooga boga'); final protocolError = await daemonStdio.awaitForDaemonEvent( 'daemon.protocolError', ); expect( protocolError.params?['message'], equals('Not a valid JSON'), ); }); test('daemon process responds to invalid json', () async { await daemonStdio.sendStringMessage('{}'); final protocolError = await daemonStdio.awaitForDaemonEvent( 'daemon.protocolError', ); expect( protocolError.params?['message'], equals('Message should be placed within a JSON list'), ); }); test('daemon process responds to unkown message type', () async { await daemonStdio.sendStringMessage('[{}]'); final protocolError = await daemonStdio.awaitForDaemonEvent( 'daemon.protocolError', ); expect( protocolError.params?['message'], equals('Unknown message type: {}'), ); }); test('daemon process responds to unkown message type', () async { await daemonStdio.sendStringMessage('[{"id": 0, "method": "foo.bar"}]'); final protocolError = await daemonStdio.awaitForDaemonEvent( 'daemon.protocolError', ); expect( protocolError.params?['message'], equals('Malformed message, Invalid id: 0'), ); }); test('daemon process responds to unknown domain', () async { final response = await daemonStdio.sendDaemonRequest( const DaemonRequest( id: '1', domain: 'wrongdomain', method: 'unkownmethod', ), timeout: const Duration(seconds: 5), ); expect( response.error, equals({'message': 'Invalid domain: wrongdomain'}), ); }); test('daemon process responds to unknown method', () async { final response = await daemonStdio.sendDaemonRequest( const DaemonRequest( id: '1', domain: 'daemon', method: 'unkownmethod', ), timeout: const Duration(seconds: 5), ); expect( response.error, equals({'message': 'Method not found: unkownmethod'}), ); }); }); test('daemon.requestVersion', () async { final response = await daemonStdio.sendDaemonRequest( const DaemonRequest( id: '1', domain: 'daemon', method: 'requestVersion', ), ); expect( response.result, equals({'version': '0.0.1'}), ); }); test('daemon.kill', () async { final response = await daemonStdio.sendDaemonRequest( const DaemonRequest(id: '1', domain: 'daemon', method: 'kill'), ); expect( response.result, equals({'message': 'Hogarth. You stay, I go. No following.'}), ); final exitCode = await daemonProcess.exitCode; expect(exitCode, equals(0)); }); }); }
dart_frog/packages/dart_frog_cli/e2e/test/daemon/daemon_domain_test.dart/0
{'file_path': 'dart_frog/packages/dart_frog_cli/e2e/test/daemon/daemon_domain_test.dart', 'repo_id': 'dart_frog', 'token_count': 1802}
import 'dart:io'; import 'package:path/path.dart' as path; import 'package:test/test.dart'; import 'helpers/helpers.dart'; /// Objectives: /// /// * Generate a new Dart Frog project via `dart_frog create` /// * Generate a new route via `dart_frog new route` /// * Generate a new middleware via `dart_frog new middleware` void main() { final String slash; final isWindowsStyle = path.Style.platform == path.Style.windows; if (isWindowsStyle) { slash = r'\'; } else { slash = '/'; } const projectName = 'example'; final tempDirectory = Directory.systemTemp.createTempSync(); final projectDirectory = Directory( path.join(tempDirectory.path, projectName), ); final routesDirectory = Directory(path.join(projectDirectory.path, 'routes')); setUpAll(() async { await dartFrogCreate(projectName: projectName, directory: tempDirectory); }); tearDownAll(() async { await tempDirectory.delete(recursive: true); }); group('dart_frog new route', () { test('Creates route', () async { await dartFrogNewRoute('/new_route', directory: projectDirectory); expect(fileAt('new_route.dart', on: routesDirectory), exists); }); test('Creates route without the leading slash', () async { await dartFrogNewRoute('another_new_route', directory: projectDirectory); expect(fileAt('another_new_route.dart', on: routesDirectory), exists); }); test(skip: true, 'Creates dynamic route', () async { await dartFrogNewRoute('/[id]', directory: projectDirectory); expect(fileAt('[id].dart', on: routesDirectory), exists); }); test('Creates nested dynamic route', () async { await dartFrogNewRoute('/inn/[id]/route', directory: projectDirectory); expect( fileAt('inn/[id]/route.dart', on: routesDirectory), exists, ); }); test('Creates a index route for an existing directory', () async { Directory(path.join(routesDirectory.path, 'nested')) .createSync(recursive: true); await dartFrogNewRoute('/nested', directory: projectDirectory); expect(fileAt('nested/index.dart', on: routesDirectory), exists); }); test('Avoid rogue routes', () async { await dartFrogNewRoute('/some_route', directory: projectDirectory); expect(fileAt('some_route.dart', on: routesDirectory), exists); await dartFrogNewRoute( '/some_route/internal', directory: projectDirectory, ); expect(fileAt('some_route.dart', on: routesDirectory), doesNotExist); expect(fileAt('some_route/index.dart', on: routesDirectory), exists); expect(fileAt('some_route/internal.dart', on: routesDirectory), exists); }); test('Avoid rogue routes (nested)', () async { await dartFrogNewRoute('/some_other_route', directory: projectDirectory); expect(fileAt('some_other_route.dart', on: routesDirectory), exists); await dartFrogNewRoute( '/some_other_route/deep/deep/internal', directory: projectDirectory, ); expect( fileAt('some_other_route.dart', on: routesDirectory), doesNotExist, ); expect( fileAt('some_other_route/index.dart', on: routesDirectory), exists, ); expect( fileAt( 'some_other_route/deep/deep/internal.dart', on: routesDirectory, ), exists, ); }); test( 'Creates route normally when there is a non-dart file with the same ' 'route path', () async { File(path.join(routesDirectory.path, 'something.py')) .createSync(recursive: true); await dartFrogNewRoute('/something', directory: projectDirectory); expect(fileAt('something.dart', on: routesDirectory), exists); expect(fileAt('something.py', on: routesDirectory), exists); }, ); test('Excuse root route', () async { await expectLater( () async => dartFrogNewRoute('/', directory: projectDirectory), failsWith(stderr: 'Failed to create route: / already exists.'), ); }); test('Excuse existing endpoints', () async { await dartFrogNewRoute('/existing_endpoint', directory: projectDirectory); await expectLater( () async => dartFrogNewRoute('/existing_endpoint', directory: projectDirectory), failsWith( stderr: 'Failed to create route: /existing_endpoint already exists.', ), ); }); test('Excuse existing endpoints (indexed route)', () async { await dartFrogNewRoute( '/existing_endpoint_dir', directory: projectDirectory, ); await dartFrogNewRoute( '/existing_endpoint_dir/inside', directory: projectDirectory, ); await expectLater( () async => dartFrogNewRoute( '/existing_endpoint_dir', directory: projectDirectory, ), failsWith( stderr: 'Failed to create route: /existing_endpoint_dir already exists.', ), ); }); test('Excuse route creation of invalid route identifiers', () async { await expectLater( () async => dartFrogNewRoute('/👯‍', directory: projectDirectory), failsWith( stderr: 'Route path segments must be valid Dart identifiers', ), ); }); test('Excuse route creation of doubled route params', () async { await expectLater( () async => dartFrogNewRoute( '/[id]/something/[id]', directory: projectDirectory, ), failsWith( stderr: 'Failed to create route: Duplicate parameter name found: id', ), ); }); group('Invalid states', () { // These tests create invalid states that may break other tests if // running in parallel on shared files. const projectName = 'error_project'; late Directory testDirectory; late Directory routesDirectory; late Directory projectDirectory; setUp(() async { testDirectory = tempDirectory.createTempSync(projectName); await dartFrogCreate( projectName: projectName, directory: testDirectory, ); projectDirectory = Directory( path.join(testDirectory.path, projectName), ); routesDirectory = Directory( path.join(projectDirectory.path, 'routes'), ); }); tearDown(() async { await projectDirectory.delete(recursive: true); }); test('Excuse existing endpoints (existing rogue route)', () async { await dartFrogNewRoute('/existing_rogue', directory: projectDirectory); Directory(path.join(routesDirectory.path, 'existing_rogue')) .createSync(recursive: true); await expectLater( () => dartFrogNewRoute('/existing_rogue', directory: projectDirectory), failsWith( stderr: 'Failed to create route: Rogue route detected. ' 'Rename routes${slash}existing_rogue.dart to ' 'routes${slash}existing_rogue${slash}index.dart.', ), ); }); test('Excuse route creation upon existing route conflicts', () async { await dartFrogNewRoute( '/conflicting_route', directory: projectDirectory, ); File(path.join(routesDirectory.path, 'conflicting_route/index.dart')) .createSync(recursive: true); await expectLater( () async => dartFrogNewRoute( '/conflicting_route', directory: projectDirectory, ), failsWith( stderr: 'Failed to create route: ' 'Route conflict detected. ' 'routes${slash}conflicting_route.dart and ' 'routes${slash}conflicting_route${slash}index.dart ' 'both resolve to /conflicting_route.', ), ); }); }); }); group('dart_frog new middleware', () { test('Creates global middleware', () async { await dartFrogNewMiddleware('/', directory: projectDirectory); expect(fileAt('_middleware.dart', on: routesDirectory), exists); }); test('Creates middleware', () async { await dartFrogNewMiddleware('/new_route', directory: projectDirectory); expect(fileAt('new_route/_middleware.dart', on: routesDirectory), exists); }); test('Creates middleware without the leading slash', () async { await dartFrogNewMiddleware( 'another_new_route', directory: projectDirectory, ); expect( fileAt('another_new_route/_middleware.dart', on: routesDirectory), exists, ); }); test('Creates middleware in dynamic route', () async { await dartFrogNewMiddleware('/[id]', directory: projectDirectory); expect(fileAt('[id]/_middleware.dart', on: routesDirectory), exists); }); test('Creates middleware in nested dynamic route', () async { await dartFrogNewMiddleware( '/inn/[id]/route', directory: projectDirectory, ); expect( fileAt('inn/[id]/route/_middleware.dart', on: routesDirectory), exists, ); }); test('Creates middleware in existing file route', () async { await dartFrogNewRoute( '/existing_file_route', directory: projectDirectory, ); expect(fileAt('existing_file_route.dart', on: routesDirectory), exists); await dartFrogNewMiddleware( '/existing_file_route', directory: projectDirectory, ); expect( fileAt('existing_file_route.dart', on: routesDirectory), doesNotExist, ); expect( fileAt('existing_file_route/index.dart', on: routesDirectory), exists, ); expect( fileAt('existing_file_route/_middleware.dart', on: routesDirectory), exists, ); }); test('Creates middleware in existing dynamic route', () async { await dartFrogNewRoute( '/prefix/[existing_dynamic_route]', directory: projectDirectory, ); expect( fileAt('prefix/[existing_dynamic_route].dart', on: routesDirectory), exists, ); await dartFrogNewMiddleware( '/prefix/[existing_dynamic_route]', directory: projectDirectory, ); expect( fileAt('prefix/[existing_dynamic_route].dart', on: routesDirectory), doesNotExist, ); expect( fileAt( 'prefix/[existing_dynamic_route]/index.dart', on: routesDirectory, ), exists, ); expect( fileAt( 'prefix/[existing_dynamic_route]/_middleware.dart', on: routesDirectory, ), exists, ); }); test('Excuse existing middlewares', () async { await dartFrogNewMiddleware( '/existing_middleware', directory: projectDirectory, ); await expectLater( () async => dartFrogNewMiddleware( '/existing_middleware', directory: projectDirectory, ), failsWith( stderr: 'There is already a middleware at ' 'routes${slash}existing_middleware${slash}_middleware.dart', ), ); }); test('Excuse middleware creation of invalid route identifier', () async { await expectLater( () async => dartFrogNewMiddleware('/👯‍', directory: projectDirectory), failsWith( stderr: 'Route path segments must be valid Dart identifiers', ), ); }); test('Excuse middleware creation of doubled route params', () async { await expectLater( () async => dartFrogNewMiddleware( '/[id]/something/[id]', directory: projectDirectory, ), failsWith( stderr: 'Failed to create middleware: ' 'Duplicate parameter name found: id', ), ); }); group('Invalid states', () { // These tests create invalid states that may break other tests if // running in parallel on shared files. const projectName = 'error_project'; late Directory testDirectory; late Directory routesDirectory; late Directory projectDirectory; setUp(() async { testDirectory = tempDirectory.createTempSync(projectName); await dartFrogCreate( projectName: projectName, directory: testDirectory, ); projectDirectory = Directory( path.join(testDirectory.path, projectName), ); routesDirectory = Directory( path.join(projectDirectory.path, 'routes'), ); }); tearDown(() async { await projectDirectory.delete(recursive: true); }); test('Excuse middleware creation upon existing rogue routes', () async { await dartFrogNewRoute('/existing_rogue', directory: projectDirectory); Directory(path.join(routesDirectory.path, 'existing_rogue')) .createSync(recursive: true); await expectLater( () async => dartFrogNewMiddleware( '/existing_rogue', directory: projectDirectory, ), failsWith( stderr: 'Failed to create middleware: Rogue route detected. ' 'Rename routes${slash}existing_rogue.dart to ' 'routes${slash}existing_rogue${slash}index.dart.', ), ); }); test('Excuse middleware creation upon existing route conflicts', () async { await dartFrogNewRoute( '/conflicting_route', directory: projectDirectory, ); File(path.join(routesDirectory.path, 'conflicting_route/index.dart')) .createSync(recursive: true); await expectLater( () async => dartFrogNewMiddleware( '/conflicting_route', directory: projectDirectory, ), failsWith( stderr: 'Failed to create middleware: Route conflict detected. ' 'routes${slash}conflicting_route.dart and ' 'routes${slash}conflicting_route${slash}index.dart both ' 'resolve to /conflicting_route.', ), ); }); }); }); }
dart_frog/packages/dart_frog_cli/e2e/test/new_test.dart/0
{'file_path': 'dart_frog/packages/dart_frog_cli/e2e/test/new_test.dart', 'repo_id': 'dart_frog', 'token_count': 5955}
import 'package:args/command_runner.dart'; import 'package:dart_frog_cli/src/command_runner.dart'; import 'package:mason/mason.dart' hide packageVersion; /// {@template uninstall_command} /// `dart_frog uninstall` command which explains how to uninstall /// the dart_frog_cli. /// {@endtemplate} class UninstallCommand extends Command<int> { /// {@macro uninstall_command} UninstallCommand({ required Logger logger, }) : _logger = logger; final Logger _logger; @override String get description => 'Explains how to uninstall the Dart Frog CLI.'; @override String get name => 'uninstall'; @override Future<int> run() async { final docs = link( uri: Uri.parse('https://dartfrog.vgv.dev/docs/overview#uninstalling-'), ); _logger.info( 'For instructions on how to uninstall $packageName completely, check out:' '\n$docs', ); return ExitCode.success.code; } }
dart_frog/packages/dart_frog_cli/lib/src/commands/uninstall/uninstall.dart/0
{'file_path': 'dart_frog/packages/dart_frog_cli/lib/src/commands/uninstall/uninstall.dart', 'repo_id': 'dart_frog', 'token_count': 316}
name: dart_frog_cli description: The official command line interface for Dart Frog. Built by Very Good Ventures. version: 1.0.0 homepage: https://dartfrog.vgv.dev repository: https://github.com/VeryGoodOpenSource/dart_frog issue_tracker: https://github.com/VeryGoodOpenSource/dart_frog/issues documentation: https://dartfrog.vgv.dev/docs/overview topics: [server, backend, shelf, dart-frog, cli] screenshots: - description: 'Dart Frog logo.' path: assets/logo.png environment: sdk: ">=3.0.0 <4.0.0" dependencies: args: ^2.1.0 cli_completion: ^0.3.0 dart_frog_gen: ^1.0.0 equatable: ^2.0.5 mason: 0.1.0-dev.50 meta: ^1.7.0 path: ^1.8.1 pub_updater: ">=0.2.4 <0.4.0" pubspec_parse: ^1.2.0 stream_transform: ^2.0.0 uuid: ^3.0.7 watcher: ^1.0.1 dev_dependencies: build_runner: ^2.0.0 build_verify: ^3.0.0 build_version: ^2.0.0 mocktail: ^1.0.0 test: ^1.19.2 very_good_analysis: ^5.0.0 executables: dart_frog:
dart_frog/packages/dart_frog_cli/pubspec.yaml/0
{'file_path': 'dart_frog/packages/dart_frog_cli/pubspec.yaml', 'repo_id': 'dart_frog', 'token_count': 429}
import 'package:dart_frog_cli/src/daemon/daemon.dart'; import 'package:mason/mason.dart'; import 'package:mocktail/mocktail.dart'; import 'package:test/test.dart'; class _MockDaemonServer extends Mock implements DaemonServer {} void main() { group('$DaemonDomain', () { late DaemonServer daemonServer; setUp(() { daemonServer = _MockDaemonServer(); when(() => daemonServer.version).thenReturn('1.0.0'); }); test('can be instantiated', () async { expect(DaemonDomain(daemonServer), isNotNull); }); test('emits initial event', () async { expect( DaemonDomain( daemonServer, processId: 42, ), isNotNull, ); verify( () => daemonServer.sendEvent( const DaemonEvent( domain: 'daemon', event: 'ready', params: { 'version': '1.0.0', 'processId': 42, }, ), ), ).called(1); }); group('requestVersion', () { test('returns current version', () async { final domain = DaemonDomain(daemonServer, processId: 42); final response = await domain.handleRequest( const DaemonRequest( id: '12', domain: 'daemon', method: 'requestVersion', ), ); expect( response, equals( const DaemonResponse.success( id: '12', result: {'version': '1.0.0'}, ), ), ); }); }); group('kill', () { test('kills the daemon and sends goodbye', () async { final domain = DaemonDomain(daemonServer, processId: 42); when(() => daemonServer.kill(ExitCode.success)) .thenAnswer((_) async {}); final response = await domain.handleRequest( const DaemonRequest( id: '12', domain: 'daemon', method: 'kill', ), ); verify(() => daemonServer.kill(ExitCode.success)).called(1); expect( response, equals( const DaemonResponse.success( id: '12', result: { 'message': 'Hogarth. You stay, I go. No following.', }, ), ), ); }); }); }); }
dart_frog/packages/dart_frog_cli/test/src/daemon/domain/daemon_domain_test.dart/0
{'file_path': 'dart_frog/packages/dart_frog_cli/test/src/daemon/domain/daemon_domain_test.dart', 'repo_id': 'dart_frog', 'token_count': 1189}
import 'package:dart_frog_gen/dart_frog_gen.dart'; import 'package:path/path.dart' as path; /// Type definition for callbacks that report rogue routes. typedef OnRogueRoute = void Function(String filePath, String idealPath); /// Reports existence of rogue routes on a [RouteConfiguration]. void reportRogueRoutes( RouteConfiguration configuration, { /// Callback called when any rogue route is found. void Function()? onViolationStart, /// Callback called for each rogue route found. OnRogueRoute? onRogueRoute, /// Callback called when any rogue route is found. void Function()? onViolationEnd, }) { if (configuration.rogueRoutes.isNotEmpty) { onViolationStart?.call(); for (final route in configuration.rogueRoutes) { final filePath = path.normalize(path.join('routes', route.path)); final fileDirectory = path.dirname(filePath); final idealPath = path.join( fileDirectory, path.basenameWithoutExtension(filePath), 'index.dart', ); onRogueRoute?.call(filePath, idealPath); } onViolationEnd?.call(); } }
dart_frog/packages/dart_frog_gen/lib/src/validate_route_configuration/rogue_routes.dart/0
{'file_path': 'dart_frog/packages/dart_frog_gen/lib/src/validate_route_configuration/rogue_routes.dart', 'repo_id': 'dart_frog', 'token_count': 370}
import 'package:sealed_unions/generic/union_1_first.dart'; import 'package:sealed_unions/generic/union_1_none.dart'; import 'package:sealed_unions/union_1.dart'; // Creator class for Union1 abstract class Factory1<Result> { /// Creates a Union0 wrapping a value /// @param single the value /// @return a Union0 object wrapping the value Union1<Result> first(Result result); /// Creates a Union1 wrapping no value /// @return a Union1 object wrapping no value Union1<Result> none(); } class Singlet<Result> implements Factory1<Result> { const Singlet(); @override Union1<Result> first(Result result) => new Union1First<Result>(result); @override Union1<Result> none() => new Union1None<Result>(); }
dart_sealed_unions/lib/factories/singlet_factory.dart/0
{'file_path': 'dart_sealed_unions/lib/factories/singlet_factory.dart', 'repo_id': 'dart_sealed_unions', 'token_count': 230}
import 'package:sealed_unions/union_5.dart'; class Union5Fourth<A, B, C, D, E> implements Union5<A, B, C, D, E> { final D _value; Union5Fourth(this._value); @override void continued( Function(A) continuationFirst, Function(B) continuationSecond, Function(C) continuationThird, Function(D) continuationFourth, Function(E) continuationFifth, ) { continuationFourth(_value); } @override R join<R>( R Function(A) mapFirst, R Function(B) mapSecond, R Function(C) mapThird, R Function(D) mapFourth, R Function(E) mapFifth, ) { return mapFourth(_value); } @override bool operator ==(Object other) => identical(this, other) || other is Union5Fourth && runtimeType == other.runtimeType && _value == other._value; @override int get hashCode => _value.hashCode; @override String toString() => _value.toString(); }
dart_sealed_unions/lib/generic/union_5_fourth.dart/0
{'file_path': 'dart_sealed_unions/lib/generic/union_5_fourth.dart', 'repo_id': 'dart_sealed_unions', 'token_count': 352}
import 'package:sealed_unions/union_8.dart'; class Union8Eighth<A, B, C, D, E, F, G, H> implements Union8<A, B, C, D, E, F, G, H> { final H _value; Union8Eighth(this._value); @override void continued( Function(A) continuationFirst, Function(B) continuationSecond, Function(C) continuationThird, Function(D) continuationFourth, Function(E) continuationFifth, Function(F) continuationSixth, Function(G) continuationSeventh, Function(H) continuationEighth, ) { continuationEighth(_value); } @override R join<R>( R Function(A) mapFirst, R Function(B) mapSecond, R Function(C) mapThird, R Function(D) mapFourth, R Function(E) mapFifth, R Function(F) mapSixth, R Function(G) mapSeventh, R Function(H) mapEighth, ) { return mapEighth(_value); } @override bool operator ==(Object other) => identical(this, other) || other is Union8Eighth && runtimeType == other.runtimeType && _value == other._value; @override int get hashCode => _value.hashCode; @override String toString() => _value.toString(); }
dart_sealed_unions/lib/generic/union_8_eighth.dart/0
{'file_path': 'dart_sealed_unions/lib/generic/union_8_eighth.dart', 'repo_id': 'dart_sealed_unions', 'token_count': 448}
abstract class Union4<First, Second, Third, Fourth> { void continued( Function(First) continuationFirst, Function(Second) continuationSecond, Function(Third) continuationThird, Function(Fourth) continuationFourth, ); R join<R>( R Function(First) mapFirst, R Function(Second) mapSecond, R Function(Third) mapThird, R Function(Fourth) mapFourth, ); }
dart_sealed_unions/lib/union_4.dart/0
{'file_path': 'dart_sealed_unions/lib/union_4.dart', 'repo_id': 'dart_sealed_unions', 'token_count': 128}
import 'package:collection/src/utils.dart'; import 'package:tennis_game_example/player_points.dart'; class Points extends Pair<PlayerPoints, PlayerPoints> { Points(PlayerPoints key, PlayerPoints value) :super(key, value); @override String toString() { return "Points{" + PlayerPoints.getString(first) + ", " + PlayerPoints.getString(last) + "}"; } @override bool operator ==(Object other) => identical(this, other) || other is Points && runtimeType == other.runtimeType && first == other.first && last == other.last; @override int get hashCode => (first == null ? 0 : first.hashCode) ^ (last == null ? 0 : last.hashCode); }
dart_sealed_unions/tennis/lib/points.dart/0
{'file_path': 'dart_sealed_unions/tennis/lib/points.dart', 'repo_id': 'dart_sealed_unions', 'token_count': 257}
export 'src/compilation_unit.dart' show serializeCompilationUnit;
dartdoc_json/lib/dartdoc_json.dart/0
{'file_path': 'dartdoc_json/lib/dartdoc_json.dart', 'repo_id': 'dartdoc_json', 'token_count': 20}
import 'package:analyzer/dart/ast/ast.dart'; import 'package:dartdoc_json/src/annotations.dart'; import 'package:dartdoc_json/src/comment.dart'; import 'package:dartdoc_json/src/formal_parameter_list.dart'; import 'package:dartdoc_json/src/type_parameter_list.dart'; import 'package:dartdoc_json/src/utils.dart'; /// Converts a FunctionDeclaration into a json-compatible object. Map<String, dynamic>? serializeFunctionDeclaration( FunctionDeclaration function, ) { final annotations = serializeAnnotations(function.metadata); if (function.name.lexeme.startsWith('_') || hasPrivateAnnotation(annotations)) { return null; } return filterMap(<String, dynamic>{ 'kind': 'function', 'name': function.name.lexeme, 'typeParameters': serializeTypeParameterList(function.functionExpression.typeParameters), 'description': serializeComment(function.documentationComment), 'parameters': serializeFormalParameterList(function.functionExpression.parameters), 'returns': function.returnType?.toString(), 'annotations': annotations, }); }
dartdoc_json/lib/src/function_declaration.dart/0
{'file_path': 'dartdoc_json/lib/src/function_declaration.dart', 'repo_id': 'dartdoc_json', 'token_count': 365}
import 'package:test/test.dart'; import 'utils.dart'; void main() { group('ClassDeclaration', () { test('bare class', () { expect( parseAsJson('class X {}'), {'kind': 'class', 'name': 'X'}, ); }); test('private classes', () { expect( parseAsJson(''' class _X {} @internal class Y {} @visibleForTesting class Z {} '''), isEmpty, ); }); test('abstract class', () { expect( parseAsJson('abstract class X {}'), {'kind': 'class', 'name': 'X', 'abstract': true}, ); }); test('template class 1', () { expect( parseAsJson('class X<T extends Base> {}'), { 'kind': 'class', 'name': 'X', 'typeParameters': [ {'name': 'T', 'extends': 'Base'}, ], }, ); }); test('template class 2', () { expect( parseAsJson('class Xyz<T extends A<B>, S extends Base2, R> {}'), { 'kind': 'class', 'name': 'Xyz', 'typeParameters': [ {'name': 'T', 'extends': 'A<B>'}, {'name': 'S', 'extends': 'Base2'}, {'name': 'R'}, ], }, ); }); test('class extends', () { expect( parseAsJson('class X extends A<X> {}'), { 'kind': 'class', 'name': 'X', 'extends': 'A<X>', }, ); }); test('class implements', () { expect( parseAsJson('class X implements A<X>, B {}'), { 'kind': 'class', 'name': 'X', 'implements': ['A<X>', 'B'], }, ); }); test('class with', () { expect( parseAsJson('class X with A, B, C<D<E>> {}'), { 'kind': 'class', 'name': 'X', 'with': ['A', 'B', 'C<D<E>>'], }, ); }); test('class annotations', () { expect( parseAsJson( ''' @external @Deprecated('will be removed when hell freezes over') class X {} ''', ), { 'kind': 'class', 'name': 'X', 'annotations': [ {'name': '@external'}, { 'name': '@Deprecated', 'arguments': ["'will be removed when hell freezes over'"], }, ], }, ); }); test('class comment', () { expect( parseAsJson( ''' /// This is a class doc-comment /// /// More lines /// ...example class X {} ''', ), { 'kind': 'class', 'name': 'X', 'description': 'This is a class doc-comment\n' '\n' 'More lines\n' ' ...example\n', }, ); }); test('class non-comment', () { expect( parseAsJson( ''' // This is not a class doc-comment class X {} ''', ), {'kind': 'class', 'name': 'X'}, ); }); test('class mixed comments', () { expect( parseAsJson( ''' /// This is a class doc-comment ///------ // // (not a comment) class X {} ''', ), { 'kind': 'class', 'name': 'X', 'description': 'This is a class doc-comment\n------\n', }, ); }); }); }
dartdoc_json/test/class_declaration_test.dart/0
{'file_path': 'dartdoc_json/test/class_declaration_test.dart', 'repo_id': 'dartdoc_json', 'token_count': 2048}
part of dartx; Comparator<E> _getComparator<E>(int order, Comparable selector(E element), {Comparator<E> parent}) { final newComparator = (E a, E b) { return order * selector(a).compareTo(selector(b)); }; return parent?.compose(newComparator) ?? newComparator; } class _SortedList<E> extends _DelegatingList<E> { final Iterable<E> _source; final Comparator<E> _comparator; List<E> _sortedResults; _SortedList._( this._source, this._comparator, ); _SortedList._withSelector( this._source, Comparable selector(E element), int order, Comparator<E> parentComparator, ) : _comparator = _getComparator(order, selector, parent: parentComparator); @override List<E> get delegate { if (_sortedResults == null) { _sortedResults = _source.toList(); _sortedResults.sort(_compare); } return _sortedResults; } /// Returns a new list with all elements sorted according to previously /// defined order and natural sort order of the values returned by specified /// [selector] function. /// /// **Note:** The actual sorting is performed when an element is accessed for /// the first time. _SortedList<E> thenBy(Comparable selector(E element)) { return _SortedList<E>._withSelector(this, selector, 1, _comparator); } /// Returns a new list with all elements sorted according to previously /// defined order and descending natural sort order of the values returned by /// specified [selector] function. /// /// **Note:** The actual sorting is performed when an element is accessed for /// the first time. _SortedList<E> thenByDescending(Comparable selector(E element)) { return _SortedList<E>._withSelector(this, selector, -1, _comparator); } /// Returns a new list with all elements sorted according to previously /// defined order and specified [comparator]. /// /// **Note:** The actual sorting is performed when an element is accessed for /// the first time. _SortedList<E> thenWith(Comparator<E> comparator) { return _SortedList<E>._(this, _comparator.compose(comparator)); } @override List<T> cast<T>() => delegate.cast<T>(); int _compare(E element1, E element2) { return _comparator(element1, element2); } } /// An implementation of [List] that delegates all methods to another [List]. /// /// Copied from quiver /// /// For instance you can create a FruitList like this : /// /// class FruitList extends DelegatingList<Fruit> { /// final List<Fruit> _fruits = []; /// /// List<Fruit> get delegate => _fruits; /// /// // custom methods /// } abstract class _DelegatingList<E> extends _DelegatingIterable<E> implements List<E> { @override List<E> get delegate; @override E operator [](int index) => delegate[index]; @override void operator []=(int index, E value) { delegate[index] = value; } @override List<E> operator +(List<E> other) => delegate + other; @override void add(E value) => delegate.add(value); @override void addAll(Iterable<E> iterable) => delegate.addAll(iterable); @override Map<int, E> asMap() => delegate.asMap(); @override void clear() => delegate.clear(); @override void fillRange(int start, int end, [E fillValue]) => delegate.fillRange(start, end, fillValue); @override set first(E element) { if (isEmpty) throw RangeError.index(0, this); this[0] = element; } @override Iterable<E> getRange(int start, int end) => delegate.getRange(start, end); @override int indexOf(E element, [int start = 0]) => delegate.indexOf(element, start); @override int indexWhere(bool test(E element), [int start = 0]) => delegate.indexWhere(test, start); @override void insert(int index, E element) => delegate.insert(index, element); @override void insertAll(int index, Iterable<E> iterable) => delegate.insertAll(index, iterable); @override set last(E element) { if (isEmpty) throw RangeError.index(0, this); this[length - 1] = element; } @override int lastIndexOf(E element, [int start]) => delegate.lastIndexOf(element, start); @override int lastIndexWhere(bool test(E element), [int start]) => delegate.lastIndexWhere(test, start); @override set length(int newLength) { delegate.length = newLength; } @override bool remove(Object value) => delegate.remove(value); @override E removeAt(int index) => delegate.removeAt(index); @override E removeLast() => delegate.removeLast(); @override void removeRange(int start, int end) => delegate.removeRange(start, end); @override void removeWhere(bool test(E element)) => delegate.removeWhere(test); @override void replaceRange(int start, int end, Iterable<E> iterable) => delegate.replaceRange(start, end, iterable); @override void retainWhere(bool test(E element)) => delegate.retainWhere(test); @override Iterable<E> get reversed => delegate.reversed; @override void setAll(int index, Iterable<E> iterable) => delegate.setAll(index, iterable); @override void setRange(int start, int end, Iterable<E> iterable, [int skipCount = 0]) => delegate.setRange(start, end, iterable, skipCount); @override void shuffle([Random random]) => delegate.shuffle(random); @override void sort([int compare(E a, E b)]) => delegate.sort(compare); @override List<E> sublist(int start, [int end]) => delegate.sublist(start, end); } /// An implementation of [Iterable] that delegates all methods to another /// [Iterable]. /// /// Copied from quiver /// /// For instance you can create a FruitIterable like this : /// /// class FruitIterable extends DelegatingIterable<Fruit> { /// final Iterable<Fruit> _fruits = []; /// /// Iterable<Fruit> get delegate => _fruits; /// /// // custom methods /// } abstract class _DelegatingIterable<E> implements Iterable<E> { Iterable<E> get delegate; @override bool any(bool test(E element)) => delegate.any(test); @override Iterable<T> cast<T>() => delegate.cast<T>(); @override bool contains(Object element) => delegate.contains(element); @override E elementAt(int index) => delegate.elementAt(index); @override bool every(bool test(E element)) => delegate.every(test); @override Iterable<T> expand<T>(Iterable<T> f(E element)) => delegate.expand(f); @override E get first => delegate.first; @override E firstWhere(bool test(E element), {E orElse()}) => delegate.firstWhere(test, orElse: orElse); @override T fold<T>(T initialValue, T combine(T previousValue, E element)) => delegate.fold(initialValue, combine); @override Iterable<E> followedBy(Iterable<E> other) => delegate.followedBy(other); @override void forEach(void f(E element)) => delegate.forEach(f); @override bool get isEmpty => delegate.isEmpty; @override bool get isNotEmpty => delegate.isNotEmpty; @override Iterator<E> get iterator => delegate.iterator; @override String join([String separator = '']) => delegate.join(separator); @override E get last => delegate.last; @override E lastWhere(bool test(E element), {E orElse()}) => delegate.lastWhere(test, orElse: orElse); @override int get length => delegate.length; @override Iterable<T> map<T>(T f(E e)) => delegate.map(f); @override E reduce(E combine(E value, E element)) => delegate.reduce(combine); @override E get single => delegate.single; @override E singleWhere(bool test(E element), {E orElse()}) => delegate.singleWhere(test, orElse: orElse); @override Iterable<E> skip(int n) => delegate.skip(n); @override Iterable<E> skipWhile(bool test(E value)) => delegate.skipWhile(test); @override Iterable<E> take(int n) => delegate.take(n); @override Iterable<E> takeWhile(bool test(E value)) => delegate.takeWhile(test); @override List<E> toList({bool growable = true}) => delegate.toList(growable: growable); @override Set<E> toSet() => delegate.toSet(); @override Iterable<E> where(bool test(E element)) => delegate.where(test); @override Iterable<T> whereType<T>() => delegate.whereType<T>(); }
dartx/lib/src/sorted_list.dart/0
{'file_path': 'dartx/lib/src/sorted_list.dart', 'repo_id': 'dartx', 'token_count': 2813}
import 'package:dashbook/dashbook.dart'; import 'package:example/stories.dart'; import 'package:example/text_story.dart'; import 'package:flutter/material.dart'; void main() { final dashbook = Dashbook.dualTheme( light: ThemeData(), dark: ThemeData.dark(), title: 'Dashbook Example', autoPinStoriesOnLargeScreen: true, ); addTextStories(dashbook); addStories(dashbook); runApp(dashbook); }
dashbook/example/lib/main.dart/0
{'file_path': 'dashbook/example/lib/main.dart', 'repo_id': 'dashbook', 'token_count': 149}
export 'unsupported.dart' if (dart.library.html) 'web.dart' if (dart.library.io) 'mobile.dart';
dashbook/lib/src/platform_utils/platform_utils.dart/0
{'file_path': 'dashbook/lib/src/platform_utils/platform_utils.dart', 'repo_id': 'dashbook', 'token_count': 47}
import 'package:dashbook/dashbook.dart'; import 'package:flutter/material.dart'; class BoolProperty extends StatefulWidget { final Property<bool> property; final PropertyChanged onChanged; const BoolProperty({ required this.property, required this.onChanged, Key? key, }) : super(key: key); @override State<StatefulWidget> createState() => BoolPropertyState(property.getValue()); } class BoolPropertyState extends State<BoolProperty> { bool? _value; BoolPropertyState(this._value); @override Widget build(BuildContext context) { return PropertyScaffold( tooltipMessage: widget.property.tooltipMessage, label: widget.property.name, child: Checkbox( value: _value, onChanged: (newValue) { widget.property.value = newValue; widget.onChanged(); setState(() { _value = newValue; }); }, ), ); } }
dashbook/lib/src/widgets/property_widgets/bool_property.dart/0
{'file_path': 'dashbook/lib/src/widgets/property_widgets/bool_property.dart', 'repo_id': 'dashbook', 'token_count': 362}
import 'package:flutter/material.dart'; class DeviceDialogButtons extends StatelessWidget { const DeviceDialogButtons({ Key? key, required this.onSelect, required this.onClear, required this.onCancel, }) : super(key: key); final VoidCallback onSelect; final VoidCallback onClear; final VoidCallback onCancel; @override Widget build(BuildContext context) { return Row( mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.center, children: [ ElevatedButton( onPressed: onSelect, child: const Text('Select'), ), const SizedBox( width: 15, ), ElevatedButton( onPressed: onCancel, child: const Text('Cancel'), ), const SizedBox( width: 15, ), ElevatedButton( onPressed: onClear, child: const Text('Clear'), ), ], ); } }
dashbook/lib/src/widgets/select_device/device_dialog_buttons.dart/0
{'file_path': 'dashbook/lib/src/widgets/select_device/device_dialog_buttons.dart', 'repo_id': 'dashbook', 'token_count': 433}
import 'package:dashbook/dashbook.dart'; import 'package:dashbook/src/widgets/keys.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import '../helpers.dart'; Dashbook _getDashbook() { final dashbook = Dashbook(); dashbook.storiesOf('Options').add('default', (ctx) { return Text( ctx.optionsProperty('optionsProperty', 'ValueX', [ PropertyOption('First option', 'ValueX'), PropertyOption('Second option', 'ValueY'), ]), ); }); return dashbook; } void main() { group('Properties - Options', () { testWidgets('shows the property input', (tester) async { await tester.pumpDashbook(_getDashbook()); expect(find.byKey(kPropertiesIcon), findsOneWidget); }); testWidgets('returns the default value on first render', (tester) async { await tester.pumpDashbook(_getDashbook()); expect(find.text('ValueX'), findsOneWidget); }); testWidgets('can change the property', (tester) async { await tester.pumpDashbook(_getDashbook()); await tester.openPropertiesPanel(); await tester.tap(find.text('First option')); await tester.pumpAndSettle(); await tester.tap(find.text('Second option').last); await tester.pumpAndSettle(); expect(find.text('ValueY'), findsOneWidget); }); }); }
dashbook/test/properties/options_property_test.dart/0
{'file_path': 'dashbook/test/properties/options_property_test.dart', 'repo_id': 'dashbook', 'token_count': 504}
import 'package:dashtronaut/presentation/common/animations/utils/animations_manager.dart'; import 'package:flutter/material.dart'; class ScaleUpTransition extends StatefulWidget { final Widget child; final Duration? delay; const ScaleUpTransition({ Key? key, required this.child, this.delay, }) : super(key: key); @override _ScaleUpTransitionState createState() => _ScaleUpTransitionState(); } class _ScaleUpTransitionState extends State<ScaleUpTransition> with SingleTickerProviderStateMixin { late final AnimationController _animationController; late final Animation<double> _scale; @override void initState() { _animationController = AnimationController( vsync: this, duration: AnimationsManager.scaleUp.duration, ); _scale = AnimationsManager.scaleUp.tween.animate( CurvedAnimation( parent: _animationController, curve: AnimationsManager.scaleUp.curve, ), ); if (widget.delay == null) { _animationController.forward(); } else { Future.delayed(widget.delay!, () { _animationController.forward(); }); } super.initState(); } @override void dispose() { _animationController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return ScaleTransition( scale: _scale, child: widget.child, ); } }
dashtronaut/lib/presentation/common/animations/widgets/scale_up_transition.dart/0
{'file_path': 'dashtronaut/lib/presentation/common/animations/widgets/scale_up_transition.dart', 'repo_id': 'dashtronaut', 'token_count': 503}
import 'dart:io'; import 'package:dashtronaut/presentation/drawer/drawer_button.dart'; import 'package:dashtronaut/presentation/layout/layout_delegate.dart'; import 'package:dashtronaut/presentation/layout/screen_type_helper.dart'; import 'package:dashtronaut/presentation/layout/spacing.dart'; import 'package:dashtronaut/presentation/puzzle/ui/puzzle_header.dart'; import 'package:dashtronaut/presentation/puzzle/ui/reset_puzzle_button.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; class PuzzleLayout implements LayoutDelegate { @override final BuildContext context; PuzzleLayout(this.context); @override ScreenTypeHelper get screenTypeHelper => ScreenTypeHelper(context); double get containerWidth { switch (screenTypeHelper.type) { case ScreenType.xSmall: case ScreenType.small: return MediaQuery.of(context).size.width - Spacing.screenHPadding * 2; case ScreenType.medium: if (screenTypeHelper.landscapeMode) { return MediaQuery.of(context).size.flipped.width - Spacing.screenHPadding * 2; } else { return 500; } case ScreenType.large: return 500; } } double get distanceOutsidePuzzle { double screenHeight = screenTypeHelper.landscapeMode ? MediaQuery.of(context).size.width : MediaQuery.of(context).size.height; return ((screenHeight - containerWidth) / 2) + containerWidth; } static const double tilePadding = 4; static double? tileTextSize(int puzzleSize) { return puzzleSize > 5 ? 20 : puzzleSize > 4 ? 25 : puzzleSize > 3 ? 30 : null; } List<Widget> get horizontalPuzzleUIElements { return [ Positioned( width: distanceOutsidePuzzle - containerWidth - MediaQuery.of(context).padding.left - (!kIsWeb && Platform.isAndroid ? Spacing.md : 0), top: !kIsWeb && Platform.isAndroid ? MediaQuery.of(context).padding.top + Spacing.md : MediaQuery.of(context).padding.bottom, left: !kIsWeb && Platform.isAndroid ? Spacing.md : MediaQuery.of(context).padding.left, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: const [ DrawerButton(), SizedBox(height: 20), PuzzleHeader(), ResetPuzzleButton(), ], ), ), ]; } List<Widget> get verticalPuzzleUIElements { return [ Positioned( top: kIsWeb ? Spacing.md : !kIsWeb && (Platform.isAndroid || Platform.isMacOS) ? MediaQuery.of(context).padding.top + Spacing.md : MediaQuery.of(context).padding.top, left: Spacing.screenHPadding, child: const DrawerButton(), ), Positioned( bottom: distanceOutsidePuzzle, width: containerWidth, left: (MediaQuery.of(context).size.width - containerWidth) / 2, child: const PuzzleHeader(), ), Positioned( top: distanceOutsidePuzzle, right: 0, left: (MediaQuery.of(context).size.width - containerWidth) / 2, child: const Align( alignment: Alignment.centerLeft, child: ResetPuzzleButton(), ), ), ]; } List<Widget> get buildUIElements { return screenTypeHelper.landscapeMode ? horizontalPuzzleUIElements : verticalPuzzleUIElements; } }
dashtronaut/lib/presentation/layout/puzzle_layout.dart/0
{'file_path': 'dashtronaut/lib/presentation/layout/puzzle_layout.dart', 'repo_id': 'dashtronaut', 'token_count': 1530}
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class AppTextStyles { static const String primaryFontFamily = 'PaytoneOne'; static const String secondaryFontFamily = 'Montserrat'; static const TextStyle tile = TextStyle( fontFamily: primaryFontFamily, fontSize: 40, fontWeight: FontWeight.w700, ); static const TextStyle title = TextStyle( fontFamily: primaryFontFamily, fontSize: 25, ); static const TextStyle h1 = TextStyle( fontFamily: secondaryFontFamily, fontSize: 20, ); static const TextStyle h1Bold = TextStyle( fontFamily: secondaryFontFamily, fontSize: 20, fontWeight: FontWeight.w700, ); static const TextStyle h2 = TextStyle( fontFamily: secondaryFontFamily, fontSize: 18, ); static const TextStyle h3 = TextStyle( fontFamily: secondaryFontFamily, fontSize: 18, fontWeight: FontWeight.w700, ); static const TextStyle body = TextStyle( fontFamily: secondaryFontFamily, fontSize: 16, ); static const TextStyle bodyBold = TextStyle( fontFamily: secondaryFontFamily, fontSize: 16, fontWeight: FontWeight.w700, ); static const TextStyle bodySm = TextStyle( fontFamily: secondaryFontFamily, fontSize: 14, ); static const TextStyle bodyXs = TextStyle( fontFamily: secondaryFontFamily, fontSize: 12, ); static const TextStyle bodyXxs = TextStyle( fontFamily: secondaryFontFamily, fontSize: 10, ); static const TextStyle button = TextStyle( fontFamily: primaryFontFamily, fontSize: 16, height: 1, ); static const TextStyle buttonSm = TextStyle( fontFamily: primaryFontFamily, fontSize: 14, height: 1, ); }
dashtronaut/lib/presentation/styles/app_text_styles.dart/0
{'file_path': 'dashtronaut/lib/presentation/styles/app_text_styles.dart', 'repo_id': 'dashtronaut', 'token_count': 590}
language: dart sudo: false dart: - stable - dev with_content_shell: false dart_task: - test: --platform vm - dartanalyzer: --fatal-warnings lib - dartfmt: sdk
date_utils/.travis.yml/0
{'file_path': 'date_utils/.travis.yml', 'repo_id': 'date_utils', 'token_count': 59}
import 'package:daylight/daylight.dart'; import 'package:intl/intl.dart'; import 'package:test/test.dart'; void main() { const perth = DaylightLocation(-31.953512, 115.857048); const berlin = DaylightLocation(52.518611, 13.408056); final july = DateTime(2020, 7, 15); final october = DateTime(2020, 10, 15); group('DayTypeUtils', () { test('isNoChange', () { expect(DayType.sunriseAndSunset.isNoChange, false); expect(DayType.allDay.isNoChange, true); expect(DayType.allNight.isNoChange, true); }); test('hasSunrise', () { expect(DayType.sunsetOnly.hasSunrise, false); expect(DayType.sunriseOnly.hasSunrise, true); expect(DayType.sunriseAndSunset.hasSunrise, true); }); test('hasSunset', () { expect(DayType.allDay.hasSunset, false); expect(DayType.sunsetOnly.hasSunset, true); expect(DayType.sunriseAndSunset.hasSunset, true); }); }); group('$Zenith', () { test('angle', () { expect(Zenith.astronomical.angle, 108.0); expect(Zenith.nautical.angle, 102.0); expect(Zenith.civil.angle, 96.0); expect(Zenith.golden.angle, 86.0); expect(Zenith.official.angle, 90.8333); }); }); group('$DaylightResult', () { group('type', () { test('sunriseAndSunset', () { final daylightResult = DaylightResult(DateTime.now(), DateTime.now(), july, perth); expect(daylightResult.type, DayType.sunriseAndSunset); }); test('sunriseOnly', () { final daylightResult = DaylightResult(DateTime.now(), null, july, perth); expect(daylightResult.type, DayType.sunriseOnly); }); test('sunsetOnly', () { final daylightResult = DaylightResult(null, DateTime.now(), july, perth); expect(daylightResult.type, DayType.sunsetOnly); }); test('allDay south', () { final daylightResult = DaylightResult(null, null, october, perth); expect(daylightResult.type, DayType.allDay); }); test('allDay north', () { final daylightResult = DaylightResult(null, null, july, berlin); expect(daylightResult.type, DayType.allDay); }); test('allNight south', () { final daylightResult = DaylightResult(null, null, july, perth); expect(daylightResult.type, DayType.allNight); }); test('allNight north', () { final daylightResult = DaylightResult(null, null, october, berlin); expect(daylightResult.type, DayType.allNight); }); }); test('equality', () { final now = DateTime.now(); final daylightResult1 = DaylightResult(now, now, july, perth); final daylightResult2 = DaylightResult(now, now, july, perth); expect(daylightResult1, daylightResult2); }); }); group('$DaylightCalculator', () { group('calculateEvent', () { group('sunrise', () { const calculator = DaylightCalculator(perth); test('official', () { final time = calculator.calculateEvent( october, Zenith.official, EventType.sunrise, ); expect(DateFormat('HH:mm:ss').format(time!), '21:36:33'); // UTC expect(time.isUtc, true); }); test('nautical', () { final time = calculator.calculateEvent( october, Zenith.nautical, EventType.sunrise, ); expect(DateFormat('HH:mm:ss').format(time!), '20:42:09'); // UTC expect(time.isUtc, true); }); test('civil', () { final time = calculator.calculateEvent( october, Zenith.civil, EventType.sunrise, ); expect(DateFormat('HH:mm:ss').format(time!), '21:11:36'); // UTC expect(time.isUtc, true); }); test('astronomical', () { final time = calculator.calculateEvent( october, Zenith.astronomical, EventType.sunrise, ); expect(DateFormat('HH:mm:ss').format(time!), '20:11:56'); // UTC expect(time.isUtc, true); }); test('golden', () { final time = calculator.calculateEvent( october, Zenith.golden, EventType.sunrise, ); expect(DateFormat('HH:mm:ss').format(time!), '21:59:38'); // UTC expect(time.isUtc, true); }); }); group('sunset', () { const calculator = DaylightCalculator(berlin); test('official', () { final time = calculator.calculateEvent( july, Zenith.official, EventType.sunset, ); expect(DateFormat('HH:mm:ss').format(time!), '19:21:47'); // UTC expect(time.isUtc, true); }); test('nautical', () { final time = calculator.calculateEvent( july, Zenith.nautical, EventType.sunset, ); expect(DateFormat('HH:mm:ss').format(time!), '21:17:10'); // UTC expect(time.isUtc, true); }); test('civil', () { final time = calculator.calculateEvent( july, Zenith.civil, EventType.sunset, ); expect(DateFormat('HH:mm:ss').format(time!), '20:08:08'); // UTC expect(time.isUtc, true); }); test('astronomical', () { final time = calculator.calculateEvent( july, Zenith.astronomical, EventType.sunset, ); expect(time, null); // UTC }); test('golden', () { final time = calculator.calculateEvent( july, Zenith.golden, EventType.sunset, ); expect(DateFormat('HH:mm:ss').format(time!), '18:43:17'); // UTC expect(time.isUtc, true); }); }); }); group('calculateForDay', () { test('official', () { const calculator = DaylightCalculator(berlin); final resultForDay = calculator.calculateForDay(october); expect( DateFormat('HH:mm:ss').format(resultForDay.sunrise!), '05:32:48', ); // UTC expect( DateFormat('HH:mm:ss').format(resultForDay.sunset!), '16:10:14', ); // UTC }); }); }); group('$DaylightLocation', () { test('equality', () { // ignore: prefer_const_constructors expect(berlin, DaylightLocation(52.518611, 13.408056)); }); }); }
daylight/test/src/daylight_test.dart/0
{'file_path': 'daylight/test/src/daylight_test.dart', 'repo_id': 'daylight', 'token_count': 3114}
import 'package:declarative_reactivity_workshop/log.dart'; import 'package:declarative_reactivity_workshop/src/atom.dart'; import 'package:declarative_reactivity_workshop/state.dart'; void main() { final container = AtomContainer() // ..onDispose(() => log('on-dispose-container', 0)); log('result', container.get(result)); container.mutate(age, (value) => value + 1); log('result', container.get(result)); container.invalidate(age); log('result', container.get(result)); container.mutate(age, (value) => value + 2); log('result', container.get(result)); container.mutate(lastname, (value) => 'v. $value'); log('result', container.get(result)); container.dispose(); }
declarative_reactivity_workshop/bin/computed_getter.dart/0
{'file_path': 'declarative_reactivity_workshop/bin/computed_getter.dart', 'repo_id': 'declarative_reactivity_workshop', 'token_count': 229}
export 'order_by.dart';
deposit/packages/deposit/lib/src/operators/operators.dart/0
{'file_path': 'deposit/packages/deposit/lib/src/operators/operators.dart', 'repo_id': 'deposit', 'token_count': 10}
name: deposit_firestore description: Provides a Firestore adapter for the deposit package version: 0.0.2 repository: https://github.com/bluefireteam/deposit/tree/main/packages/deposit_firestore issue_tracker: https://github.com/bluefireteam/deposit homepage: https://github.com/bluefireteam/deposit environment: sdk: ">=2.15.1 <3.0.0" flutter: ">=1.17.0" dependencies: cloud_firestore: ^3.1.5 deposit: ^0.0.2 dev_dependencies: fake_cloud_firestore: ^1.2.1 flutter_test: sdk: flutter very_good_analysis: ^2.4.0
deposit/packages/deposit_firestore/pubspec.yaml/0
{'file_path': 'deposit/packages/deposit_firestore/pubspec.yaml', 'repo_id': 'deposit', 'token_count': 207}
// 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:async'; import 'package:intl/intl.dart'; class Logging { Logging() { model = TimeModel(this)..start(); } TimeModel model; static Logging _theLogging; static Logging get logging { _theLogging ??= Logging(); return _theLogging; } final List<String> _logs = []; void add(String entry) { final TimeStamp newTimeStamp = TimeStamp.record(DateTime.now()); _logs.add('[${model.log.length}] : ${newTimeStamp.time}] $entry'); } List<String> get logs => _logs; } class TimeStamp { TimeStamp() : time = '', date = '', meridiem = ''; TimeStamp.record(DateTime now) { time = currentTime.format(now); date = currentDate.format(now); meridiem = currentMeridiem.format(now); } String time; String date; String meridiem; DateFormat currentTime = DateFormat('h:mm:ss', 'en_US'); DateFormat currentDate = DateFormat('EEEE, MMM d', 'en_US'); DateFormat currentMeridiem = DateFormat('aaa', 'en_US'); } class TimeModel { TimeModel(this._logging); final Logging _logging; List<TimeStamp> log = <TimeStamp>[]; final String _time = ''; final String _date = ''; final String _meridiem = ''; Timer _clockUpdateTimer; DateTime now = DateTime.now(); /// Start updating. void start() { log.add(TimeStamp()); _updateLog(); _clockUpdateTimer = Timer.periodic( const Duration(milliseconds: 100), (_) => _updateLog(), ); } /// Stop updating. void stop() { _clockUpdateTimer?.cancel(); _clockUpdateTimer = null; } /// The current time in the ambient format. String get time => _time; /// The current date in the ambient format. String get date => _date; /// The current meridiem in the ambient format. String get meridiem => _meridiem; String get partOfDay { if (now.hour < 5) { return 'night'; } if (now.hour < 12) { return 'morning'; } if (now.hour < 12 + 5) { return 'afternoon'; } if (now.hour < 12 + 8) { return 'evening'; } return 'night'; } void _updateLog() { now = DateTime.now(); final _year = now.year; /// Due to a bug, need to verify the date has the current year before /// returning a date and time. if (_year < 2019) { return; } final TimeStamp newTimeStamp = TimeStamp.record(now); log.add(newTimeStamp); if (newTimeStamp.time != log.last.time || newTimeStamp.date != log.last.date || newTimeStamp.meridiem != log.last.meridiem) { _logging.add('${newTimeStamp.time} idle...'); } } }
devtools/case_study/memory_leak/lib/logging.dart/0
{'file_path': 'devtools/case_study/memory_leak/lib/logging.dart', 'repo_id': 'devtools', 'token_count': 1062}
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; class ChannelDemo extends StatefulWidget { @override _ChannelDemoState createState() => _ChannelDemoState(); } class _ChannelDemoState extends State<ChannelDemo> { static const sendMessage = 'Send message by clicking the "Mail" button below'; BasicMessageChannel<String> _channel; String _response; void _sendMessage() { _channel.send('Message from Dart'); } void _reset() { setState(() { _response = sendMessage; }); } @override void initState() { super.initState(); _response = sendMessage; _channel = const BasicMessageChannel<String>('shuttle', StringCodec()); _channel.setMessageHandler((String response) { setState(() => _response = response); return null; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Channel Demo'), ), body: Padding( padding: const EdgeInsets.all(16.0), child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Center(child: Text(_response)), Align( alignment: Alignment.bottomRight, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ FloatingActionButton( heroTag: 'reset', child: const Icon(Icons.refresh), onPressed: _reset, ), FloatingActionButton( heroTag: 'send_message', child: const Icon(Icons.mail), onPressed: _sendMessage, ), ], ), ), ], ), ), ); } }
devtools/case_study/platform_channel/lib/channel_demo.dart/0
{'file_path': 'devtools/case_study/platform_channel/lib/channel_demo.dart', 'repo_id': 'devtools', 'token_count': 893}
// Copyright 2020 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 'package:flutter/material.dart'; import 'package:vm_snapshot_analysis/precompiler_trace.dart'; import 'package:vm_snapshot_analysis/program_info.dart'; import '../common_widgets.dart'; import '../table.dart'; import '../table_data.dart'; import '../theme.dart'; import '../trees.dart'; import '../utils.dart'; class CallGraphWithDominators extends StatefulWidget { const CallGraphWithDominators({@required this.callGraphRoot}); final CallGraphNode callGraphRoot; @override _CallGraphWithDominatorsState createState() => _CallGraphWithDominatorsState(); } class _CallGraphWithDominatorsState extends State<CallGraphWithDominators> { bool showCallGraph = false; DominatorTreeNode dominatorTreeRoot; @override void initState() { super.initState(); dominatorTreeRoot = DominatorTreeNode.from(widget.callGraphRoot.dominatorRoot); } @override void didUpdateWidget(covariant CallGraphWithDominators oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.callGraphRoot != widget.callGraphRoot) { dominatorTreeRoot = DominatorTreeNode.from(widget.callGraphRoot.dominatorRoot); } } @override Widget build(BuildContext context) { return Column( children: [ AreaPaneHeader( title: Text(showCallGraph ? 'Call Graph' : 'Dominator Tree'), needsTopBorder: false, needsBottomBorder: false, needsLeftBorder: true, actions: [ const Text('Show call graph'), Switch( value: showCallGraph, onChanged: _toggleShowCallGraph, ), ], ), Expanded( child: showCallGraph ? CallGraphView(node: widget.callGraphRoot) : DominatorTree( dominatorTreeRoot: dominatorTreeRoot, selectedNode: widget.callGraphRoot, ), ), ], ); } void _toggleShowCallGraph(bool shouldShow) { setState(() { showCallGraph = shouldShow; }); } } class CallGraphView extends StatefulWidget { const CallGraphView({@required this.node}); static const Key fromTableKey = Key('CallGraphView - From table'); static const Key toTableKey = Key('CallGraphView - To table'); final CallGraphNode node; @override _CallGraphViewState createState() => _CallGraphViewState(); } class _CallGraphViewState extends State<CallGraphView> { final _fromColumn = FromColumn(); final _toColumn = ToColumn(); CallGraphNode selectedNode; @override void initState() { super.initState(); selectedNode = widget.node; } @override void didUpdateWidget(covariant CallGraphView oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.node != widget.node) { selectedNode = widget.node; } } @override Widget build(BuildContext context) { return LayoutBuilder( builder: (context, constraints) { return Stack( children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.start, children: [ Flexible( child: _buildFromTable(), ), Container( height: constraints.maxHeight, width: densePadding, color: Theme.of(context).titleSolidBackgroundColor, ), Flexible( child: _buildToTable(), ), ], ), Positioned( top: 0, width: constraints.maxWidth, child: _buildMainNode(), ), ], ); }, ); } Widget _buildFromTable() { return FlatTable<CallGraphNode>( key: CallGraphView.fromTableKey, columns: [_fromColumn], data: selectedNode.pred, keyFactory: (CallGraphNode node) => ValueKey<CallGraphNode>(node), onItemSelected: _selectMainNode, sortColumn: _fromColumn, sortDirection: SortDirection.descending, ); } Widget _buildToTable() { return FlatTable<CallGraphNode>( key: CallGraphView.toTableKey, columns: [_toColumn], data: selectedNode.succ, keyFactory: (CallGraphNode node) => ValueKey<CallGraphNode>(node), onItemSelected: _selectMainNode, sortColumn: _toColumn, sortDirection: SortDirection.descending, ); } Widget _buildMainNode() { return Row( mainAxisAlignment: MainAxisAlignment.center, children: [ const Padding( padding: EdgeInsets.symmetric(horizontal: densePadding), child: Icon(Icons.arrow_forward), ), Tooltip( waitDuration: tooltipWait, message: selectedNode.data.toString(), child: Container( padding: const EdgeInsets.all(densePadding), child: Text( selectedNode.display, overflow: TextOverflow.ellipsis, ), ), ), const Padding( padding: EdgeInsets.symmetric(horizontal: densePadding), child: Icon(Icons.arrow_forward), ), ], ); } void _selectMainNode(CallGraphNode node) { setState(() { selectedNode = node; }); } } class FromColumn extends ColumnData<CallGraphNode> { FromColumn() : super.wide('From'); @override String getValue(CallGraphNode dataObject) => dataObject.display; } class ToColumn extends ColumnData<CallGraphNode> { ToColumn() : super.wide('To'); @override ColumnAlignment get alignment => ColumnAlignment.right; @override String getValue(CallGraphNode dataObject) => dataObject.display; } class DominatorTree extends StatelessWidget { DominatorTree({ @required this.dominatorTreeRoot, @required this.selectedNode, }); static const dominatorTreeTableKey = Key('DominatorTree - table'); final DominatorTreeNode dominatorTreeRoot; final CallGraphNode selectedNode; final _packageColumn = _PackageColumn(); @override Widget build(BuildContext context) { _expandToSelected(); // TODO(kenz): programmatically select [selectedNode] in the table. return TreeTable<DominatorTreeNode>( key: dominatorTreeTableKey, dataRoots: [dominatorTreeRoot], columns: [_packageColumn], treeColumn: _packageColumn, keyFactory: (node) => PageStorageKey<String>('${node.callGraphNode.id}'), sortColumn: _packageColumn, sortDirection: SortDirection.descending, autoExpandRoots: true, ); } void _expandToSelected() { var selected = dominatorTreeRoot.firstChildWithCondition( (node) => node.callGraphNode.id == selectedNode.id); while (selected != null) { selected.expand(); selected = selected.parent; } } } class _PackageColumn extends TreeColumnData<DominatorTreeNode> { _PackageColumn() : super('Package'); @override String getValue(DominatorTreeNode dataObject) => dataObject.callGraphNode.display; } extension CallGraphNodeDisplay on CallGraphNode { String get display { final displayText = data is ProgramInfoNode ? data.qualifiedName : data.toString(); if (displayText == '@shared') { // Special case '@shared' because this is the name of the call graph root, // and '@root' has a more intuitive meaning. return '@root'; } return displayText; } CallGraphNode get dominatorRoot { var root = this; while (root.dominator != null) { root = root.dominator; } return root; } } class DominatorTreeNode extends TreeNode<DominatorTreeNode> { DominatorTreeNode._(this.callGraphNode); factory DominatorTreeNode.from(CallGraphNode cgNode) { final domNode = DominatorTreeNode._(cgNode); for (var dominated in cgNode.dominated) { domNode.addChild(DominatorTreeNode.from(dominated)); } return domNode; } final CallGraphNode callGraphNode; }
devtools/packages/devtools_app/lib/src/app_size/code_size_attribution.dart/0
{'file_path': 'devtools/packages/devtools_app/lib/src/app_size/code_size_attribution.dart', 'repo_id': 'devtools', 'token_count': 3284}
// Copyright 2020 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 'drag_and_drop.dart'; // TODO(kenz): implement once Desktop support is available. See // https://github.com/flutter/flutter/issues/30719. DragAndDropManagerDesktop createDragAndDropManager() { return DragAndDropManagerDesktop(); } class DragAndDropManagerDesktop extends DragAndDropManager { DragAndDropManagerDesktop() : super.impl(); }
devtools/packages/devtools_app/lib/src/config_specific/drag_and_drop/_drag_and_drop_desktop.dart/0
{'file_path': 'devtools/packages/devtools_app/lib/src/config_specific/drag_and_drop/_drag_and_drop_desktop.dart', 'repo_id': 'devtools', 'token_count': 145}
// Copyright 2020 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 'package:flutter/widgets.dart'; import '../../theme.dart'; export 'ide_theme_stub.dart' if (dart.library.html) 'ide_theme_web.dart' if (dart.library.io) 'ide_theme_desktop.dart'; /// IDE-supplied theming. class IdeTheme { IdeTheme({ this.backgroundColor, this.foregroundColor, this.fontSize, this.embed, }); final Color backgroundColor; final Color foregroundColor; final double fontSize; final bool embed; double get fontSizeFactor => fontSize != null ? fontSize / defaultFontSize : 1.0; }
devtools/packages/devtools_app/lib/src/config_specific/ide_theme/ide_theme.dart/0
{'file_path': 'devtools/packages/devtools_app/lib/src/config_specific/ide_theme/ide_theme.dart', 'repo_id': 'devtools', 'token_count': 243}
// Copyright 2020 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. class Notification { Notification(String title, {String body}) { throw Exception('unsupported platform'); } static Future<String> requestPermission() { throw Exception('unsupported platform'); } void close() { throw Exception('unsupported platform'); } }
devtools/packages/devtools_app/lib/src/config_specific/notifications/notifications_desktop.dart/0
{'file_path': 'devtools/packages/devtools_app/lib/src/config_specific/notifications/notifications_desktop.dart', 'repo_id': 'devtools', 'token_count': 120}
// Copyright 2020 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 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import '../common_widgets.dart'; import '../theme.dart'; import '../utils.dart'; import 'common.dart'; import 'debugger_controller.dart'; import 'debugger_model.dart'; const executableLineRadius = 1.5; const breakpointRadius = 6.0; class Breakpoints extends StatefulWidget { const Breakpoints({Key key}) : super(key: key); @override _BreakpointsState createState() => _BreakpointsState(); } class _BreakpointsState extends State<Breakpoints> { DebuggerController controller; @override void didChangeDependencies() { super.didChangeDependencies(); final newController = Provider.of<DebuggerController>(context); if (newController == controller) return; controller = newController; } @override Widget build(BuildContext context) { return ValueListenableBuilder<List<BreakpointAndSourcePosition>>( valueListenable: controller.breakpointsWithLocation, builder: (context, breakpoints, _) { return ValueListenableBuilder<BreakpointAndSourcePosition>( valueListenable: controller.selectedBreakpoint, builder: (context, selectedBreakpoint, _) { return ListView.builder( itemCount: breakpoints.length, itemExtent: defaultListItemHeight, itemBuilder: (_, index) { return buildBreakpoint( breakpoints[index], selectedBreakpoint, ); }, ); }, ); }, ); } Widget buildBreakpoint( BreakpointAndSourcePosition bp, BreakpointAndSourcePosition selectedBreakpoint, ) { final theme = Theme.of(context); final isSelected = bp.id == selectedBreakpoint?.id; return Material( color: isSelected ? theme.selectedRowColor : null, child: InkWell( onTap: () => _onBreakpointSelected(bp), child: Padding( padding: const EdgeInsets.all(borderPadding), child: Row( children: [ Padding( padding: const EdgeInsets.only( left: borderPadding, right: borderPadding * 2, ), child: createCircleWidget( breakpointRadius, (isSelected ? theme.selectedTextStyle : theme.regularTextStyle) .color, ), ), Flexible( child: RichText( maxLines: 1, overflow: TextOverflow.ellipsis, text: TextSpan( text: _descriptionFor(bp), style: isSelected ? theme.selectedTextStyle : theme.regularTextStyle, children: [ TextSpan( text: ' (${bp.scriptUri})', style: isSelected ? theme.selectedTextStyle : theme.subtleTextStyle, ), ], ), ), ), ], ), ), ), ); } void _onBreakpointSelected(BreakpointAndSourcePosition bp) { controller.selectBreakpoint(bp); } String _descriptionFor(BreakpointAndSourcePosition breakpoint) { final fileName = breakpoint.scriptUri.split('/').last; // Consider showing columns in the future if we allow multiple breakpoints // per line. return '$fileName:${breakpoint.line}'; } } class BreakpointsCountBadge extends StatelessWidget { const BreakpointsCountBadge({@required this.breakpoints}); final List<BreakpointAndSourcePosition> breakpoints; @override Widget build(BuildContext context) { return Badge('${nf.format(breakpoints.length)}'); } }
devtools/packages/devtools_app/lib/src/debugger/breakpoints.dart/0
{'file_path': 'devtools/packages/devtools_app/lib/src/debugger/breakpoints.dart', 'repo_id': 'devtools', 'token_count': 1905}
// Copyright 2020 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 'package:flutter/material.dart'; import 'common_widgets.dart'; import 'theme.dart'; const dialogDefaultContext = 'dialog'; Text dialogTitleText(ThemeData theme, String text) { return Text(text, style: theme.textTheme.headline6); } List<Widget> dialogSubHeader(ThemeData theme, String titleText) { return [ Text(titleText, style: theme.textTheme.subtitle1), const PaddedDivider(padding: EdgeInsets.only(bottom: denseRowSpacing)), ]; } /// A standardized dialog for use in DevTools. /// /// It normalizes dialog layout, spacing, and look and feel. class DevToolsDialog extends StatelessWidget { const DevToolsDialog({ @required this.title, @required this.content, this.includeDivider = true, this.actions, }); static const contentPadding = 24.0; final Widget title; final Widget content; final bool includeDivider; final List<Widget> actions; @override Widget build(BuildContext context) { return AlertDialog( scrollable: true, title: Column( children: [ title, includeDivider ? const PaddedDivider( padding: EdgeInsets.only(bottom: denseRowSpacing), ) : const SizedBox(height: defaultSpacing), ], ), contentPadding: const EdgeInsets.fromLTRB( contentPadding, 0, contentPadding, contentPadding), content: content, actions: actions, buttonPadding: const EdgeInsets.symmetric(horizontal: defaultSpacing), ); } } /// A TextButton used to close a containing dialog (Close). class DialogCloseButton extends StatelessWidget { @override Widget build(BuildContext context) { return DialogTextButton( onPressed: () { Navigator.of(context, rootNavigator: true).pop('dialog'); }, child: const Text('CLOSE'), ); } } /// A TextButton used to close a containing dialog (Cancel). class DialogCancelButton extends StatelessWidget { const DialogCancelButton({this.cancelAction}) : super(); final VoidCallback cancelAction; @override Widget build(BuildContext context) { return DialogTextButton( onPressed: () { if (cancelAction != null) cancelAction(); Navigator.of(context).pop(dialogDefaultContext); }, child: const Text('CANCEL'), ); } } /// A TextButton used to close a containing dialog (APPLY). class DialogApplyButton extends StatelessWidget { const DialogApplyButton({@required this.onPressed}) : super(); final Function onPressed; @override Widget build(BuildContext context) { return DialogTextButton( onPressed: () { if (onPressed != null) onPressed(); Navigator.of(context).pop(dialogDefaultContext); }, child: const Text('APPLY'), ); } } class DialogTextButton extends StatelessWidget { const DialogTextButton({this.onPressed, this.child}); final VoidCallback onPressed; final Widget child; @override Widget build(BuildContext context) { return SizedBox( height: defaultButtonHeight, child: TextButton( onPressed: onPressed, child: child, ), ); } }
devtools/packages/devtools_app/lib/src/dialogs.dart/0
{'file_path': 'devtools/packages/devtools_app/lib/src/dialogs.dart', 'repo_id': 'devtools', 'token_count': 1211}
// Copyright 2021 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 'package:flutter/material.dart'; import 'common_widgets.dart'; import 'debugger/common.dart'; import 'history_manager.dart'; import 'theme.dart'; /// A [Widget] that allows for displaying content based on the current state of a /// [HistoryManager]. Includes built-in controls for navigating back and forth /// through the content stored in the provided [HistoryManager]. /// /// [history] is the [HistoryManger] that contains the data to be displayed. /// /// [contentBuilder] is invoked with the currently selected historical data /// when building the contents of the viewport. /// /// If [controls] is provided, each [Widget] will be inserted with padding /// at the end of the viewport title bar. /// /// If [generateTitle] is provided, the title string will be set to the /// returned value. If not provided, the title will be empty. class HistoryViewport<T> extends StatelessWidget { const HistoryViewport({ @required this.history, @required this.contentBuilder, this.controls, this.generateTitle, }); final HistoryManager<T> history; final String Function(T) generateTitle; final List<Widget> controls; final Widget Function(BuildContext, T) contentBuilder; @override Widget build(BuildContext context) { final theme = Theme.of(context); return OutlineDecoration( child: ValueListenableBuilder( valueListenable: history.current, builder: (context, current, _) { return Column( children: [ _buildTitle(context, theme), contentBuilder(context, current), ], ); }, ), ); } Widget _buildTitle(BuildContext context, ThemeData theme) { return debuggerSectionTitle( theme, child: Row( children: [ ToolbarAction( icon: Icons.chevron_left, onPressed: history.hasPrevious ? history.moveBack : null, ), ToolbarAction( icon: Icons.chevron_right, onPressed: history.hasNext ? history.moveForward : null, ), const SizedBox(width: denseSpacing), const VerticalDivider(thickness: 1.0), const SizedBox(width: defaultSpacing), Expanded( child: Text( generateTitle == null ? ' ' : generateTitle(history.current.value), style: theme.textTheme.subtitle2, ), ), if (controls != null) ...[ const SizedBox(width: denseSpacing), for (final widget in controls) ...[ widget, const SizedBox(width: denseSpacing), ], ], ], ), ); } }
devtools/packages/devtools_app/lib/src/history_viewport.dart/0
{'file_path': 'devtools/packages/devtools_app/lib/src/history_viewport.dart', 'repo_id': 'devtools', 'token_count': 1145}
import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import '../../../math_utils.dart'; import '../../../theme.dart'; import '../../../utils.dart'; import '../../inspector_data_models.dart'; import '../ui/arrow.dart'; import '../ui/dimension.dart'; import '../ui/theme.dart'; import 'utils.dart'; class VisualizeWidthAndHeightWithConstraints extends StatelessWidget { const VisualizeWidthAndHeightWithConstraints({ @required this.properties, this.arrowHeadSize = defaultIconSize, @required this.child, this.warnIfUnconstrained = true, }); final Widget child; final LayoutProperties properties; final double arrowHeadSize; final bool warnIfUnconstrained; @override Widget build(BuildContext context) { final showChildrenWidthsSum = properties is FlexLayoutProperties && properties.isOverflowWidth; const bottomHeight = widthAndConstraintIndicatorSize; const rightWidth = heightAndConstraintIndicatorSize; final colorScheme = Theme.of(context).colorScheme; final showOverflowHeight = properties is FlexLayoutProperties && properties.isOverflowHeight; final heightDescription = RotatedBox( quarterTurns: 1, child: dimensionDescription( TextSpan( children: [ TextSpan( text: '${properties.describeHeight()}', ), if (properties.constraints != null) ...[ if (!showOverflowHeight) const TextSpan(text: '\n'), TextSpan( text: ' (${properties.describeHeightConstraints()})', style: properties.constraints.hasBoundedHeight || !warnIfUnconstrained ? null : TextStyle( color: colorScheme.unconstrainedColor, ), ) ], if (showOverflowHeight) TextSpan( text: '\nchildren take: ' '${toStringAsFixed(sum(properties.childrenHeights))}', ), ], ), properties.isOverflowHeight, colorScheme), ); final right = Container( margin: const EdgeInsets.only( top: margin, left: margin, bottom: bottomHeight, right: minPadding, // custom margin for not sticking to the corner ), child: LayoutBuilder(builder: (context, constraints) { final displayHeightOutsideArrow = constraints.maxHeight < minHeightToDisplayHeightInsideArrow; return Row( children: [ Truncateable( truncate: !displayHeightOutsideArrow, child: Container( margin: const EdgeInsets.symmetric(horizontal: arrowMargin), child: ArrowWrapper.bidirectional( arrowColor: heightIndicatorColor, arrowStrokeWidth: arrowStrokeWidth, arrowHeadSize: arrowHeadSize, direction: Axis.vertical, child: displayHeightOutsideArrow ? null : heightDescription, ), ), ), if (displayHeightOutsideArrow) Flexible( child: heightDescription, ), ], ); }), ); final widthDescription = dimensionDescription( TextSpan( children: [ TextSpan(text: '${properties.describeWidth()}; '), if (properties.constraints != null) ...[ if (!showChildrenWidthsSum) const TextSpan(text: '\n'), TextSpan( text: '(${properties.describeWidthConstraints()})', style: properties.constraints.hasBoundedWidth || !warnIfUnconstrained ? null : TextStyle(color: colorScheme.unconstrainedColor), ) ], if (showChildrenWidthsSum) TextSpan( text: '\nchildren take ' '${toStringAsFixed(sum(properties.childrenWidths))}', ) ], ), properties.isOverflowWidth, colorScheme, ); final bottom = Container( margin: const EdgeInsets.only( top: margin, left: margin, right: rightWidth, bottom: minPadding, ), child: LayoutBuilder(builder: (context, constraints) { final maxWidth = constraints.maxWidth; final displayWidthOutsideArrow = maxWidth < minWidthToDisplayWidthInsideArrow; return Column( children: [ Truncateable( truncate: !displayWidthOutsideArrow, child: Container( margin: const EdgeInsets.symmetric(vertical: arrowMargin), child: ArrowWrapper.bidirectional( arrowColor: widthIndicatorColor, arrowHeadSize: arrowHeadSize, arrowStrokeWidth: arrowStrokeWidth, direction: Axis.horizontal, child: displayWidthOutsideArrow ? null : widthDescription, ), ), ), if (displayWidthOutsideArrow) Flexible( child: Container( padding: const EdgeInsets.only(top: minPadding), child: widthDescription, ), ), ], ); }), ); return BorderLayout( center: child, right: right, rightWidth: rightWidth, bottom: bottom, bottomHeight: bottomHeight, ); } }
devtools/packages/devtools_app/lib/src/inspector/layout_explorer/ui/widget_constraints.dart/0
{'file_path': 'devtools/packages/devtools_app/lib/src/inspector/layout_explorer/ui/widget_constraints.dart', 'repo_id': 'devtools', 'token_count': 2789}
// 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 'package:vm_service/vm_service.dart'; import '../globals.dart'; import '../utils.dart'; import '../version.dart'; import 'network_controller.dart'; class NetworkService { NetworkService(this.networkController); final NetworkController networkController; /// Updates the last refresh time to the current time. /// /// If [alreadyRecordingHttp] is true it's unclear when the last refresh time /// would have occurred, so the refresh time is not updated. Otherwise, /// [NetworkController.lastRefreshMicros] is updated to the current /// timeline timestamp. /// /// Returns the current timestamp. Future<int> updateLastRefreshTime({bool alreadyRecordingHttp = false}) async { // Set the current timeline time as the time of the last refresh. final timestamp = await serviceManager.service.getVMTimelineMicros(); if (!alreadyRecordingHttp) { // Only include HTTP requests issued after the current time. networkController.lastRefreshMicros = timestamp.timestamp; } return timestamp.timestamp; } /// Force refreshes the HTTP requests logged to the timeline as well as any /// recorded Socket traffic. Future<void> refreshNetworkData() async { if (serviceManager.service == null) return; final timestamp = await serviceManager.service.getVMTimelineMicros(); final sockets = await _refreshSockets(); List<HttpProfileRequest> httpRequests; Timeline timeline; if (await serviceManager.service.isDartIoVersionSupported( supportedVersion: SemanticVersion(major: 1, minor: 6), isolateId: serviceManager.isolateManager.selectedIsolate.id, )) { httpRequests = await _refreshHttpProfile(); } else { timeline = await serviceManager.service.getVMTimeline( timeOriginMicros: networkController.lastRefreshMicros, timeExtentMicros: timestamp.timestamp - networkController.lastRefreshMicros, ); } networkController.lastRefreshMicros = timestamp.timestamp; networkController.processNetworkTraffic( timeline: timeline, sockets: sockets, httpRequests: httpRequests, ); } Future<List<HttpProfileRequest>> _refreshHttpProfile() async { assert(serviceManager.service != null); if (serviceManager.service == null) return []; final requests = <HttpProfileRequest>[]; await serviceManager.service.forEachIsolate((isolate) async { final request = await serviceManager.service.getHttpProfile( isolate.id, updatedSince: networkController.lastRefreshMicros, ); requests.addAll(request.requests); }); return requests; } Future<List<SocketStatistic>> _refreshSockets() async { assert(serviceManager.service != null); if (serviceManager.service == null) return []; final sockets = <SocketStatistic>[]; await serviceManager.service.forEachIsolate((isolate) async { final socketProfile = await serviceManager.service.getSocketProfile(isolate.id); sockets.addAll(socketProfile.sockets); }); return sockets; } Future<void> _clearSocketProfile() async { assert(serviceManager.service != null); if (serviceManager.service == null) return; await serviceManager.service.forEachIsolate((isolate) async { final socketProfilingAvailable = await serviceManager.service.isSocketProfilingAvailable(isolate.id); if (socketProfilingAvailable) { final future = serviceManager.service.clearSocketProfile(isolate.id); // The above call won't complete immediately if the isolate is paused, so // give up waiting after 500ms. However, the call will complete eventually // if the isolate is eventually resumed. // TODO(jacobr): detect whether the isolate is paused using the vm // service and handle this case gracefully rather than timing out. await timeout(future, 500); } }); } /// Enables or disables Socket profiling for all isolates. Future<void> toggleSocketProfiling(bool state) async { assert(serviceManager.service != null); if (serviceManager.service == null) return; await serviceManager.service.forEachIsolate((isolate) async { final socketProfilingAvailable = await serviceManager.service.isSocketProfilingAvailable(isolate.id); if (socketProfilingAvailable) { final future = serviceManager.service.socketProfilingEnabled(isolate.id, state); // The above call won't complete immediately if the isolate is paused, so // give up waiting after 500ms. However, the call will complete eventually // if the isolate is eventually resumed. // TODO(jacobr): detect whether the isolate is paused using the vm // service and handle this case gracefully rather than timing out. await timeout(future, 500); } }); } Future<void> clearData() async { await updateLastRefreshTime(); await _clearSocketProfile(); } }
devtools/packages/devtools_app/lib/src/network/network_service.dart/0
{'file_path': 'devtools/packages/devtools_app/lib/src/network/network_service.dart', 'repo_id': 'devtools', 'token_count': 1645}
// Copyright 2020 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 '../utils.dart'; import 'performance_model.dart'; class PerformanceUtils { static String computeEventGroupKey( TimelineEvent event, Map<int, String> threadNamesById, ) { if (event.groupKey != null) { return event.groupKey; } else if (event.isAsyncEvent) { return event.root.name; } else if (event.isUiEvent) { return PerformanceData.uiKey; } else if (event.isRasterEvent) { return PerformanceData.rasterKey; } else if (threadNamesById[event.threadId] != null) { return threadNamesById[event.threadId]; } else { return PerformanceData.unknownKey; } } static int eventGroupComparator(String a, String b) { if (a == b) return 0; // TODO(kenz): Once https://github.com/flutter/flutter/issues/83835 is // addressed, match on the group key that all skia.shader events will have. // Order shader buckets first. final aIsShade = a.toLowerCase().contains('shade'); final bIsShade = b.toLowerCase().contains('shade'); if (aIsShade || bIsShade) { final shadeCompare = aIsShade.boolCompare(bIsShade); if (shadeCompare == 0) { // If they both have "shade" in the name, alphabetize them. return a.compareTo(b); } return shadeCompare; } // Order Unknown buckets last. Unknown buckets will be of the form "Unknown" // or "Unknown (12345)". final aIsUnknown = a.toLowerCase().contains(PerformanceData.unknownKey); final bIsUnknown = b.toLowerCase().contains(PerformanceData.unknownKey); if (aIsUnknown || bIsUnknown) { final unknownCompare = aIsUnknown.boolCompare(bIsUnknown); if (unknownCompare == 0) { // If they both have "Unknown" in the name, alphabetize them. return a.compareTo(b); } return unknownCompare; } // Order the Raster event bucket after the UI event bucket. if ((a == PerformanceData.uiKey && b == PerformanceData.rasterKey) || (a == PerformanceData.rasterKey && b == PerformanceData.uiKey)) { return -1 * a.compareTo(b); } // Order non-UI and non-raster buckets after the UI / Raster buckets. if (a == PerformanceData.uiKey || a == PerformanceData.rasterKey) return -1; if (b == PerformanceData.uiKey || b == PerformanceData.rasterKey) return 1; // Alphabetize all other buckets. return a.compareTo(b); } }
devtools/packages/devtools_app/lib/src/performance/performance_utils.dart/0
{'file_path': 'devtools/packages/devtools_app/lib/src/performance/performance_utils.dart', 'repo_id': 'devtools', 'token_count': 926}
// 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. /// Low 'profile_period' value. /// /// When this value is applied to the 'profile_period' VM flag, the VM will /// collect one sample every millisecond. const lowProfilePeriod = '1000'; /// Medium 'profile_period' value. /// /// When this value is applied to the 'profile_period' VM flag, the VM will /// collect one sample every 250 microseconds. const mediumProfilePeriod = '250'; /// High 'profile_period' value. /// /// When this value is applied to the 'profile_period' VM flag, the VM will /// collect one sample every 50 microseconds. const highProfilePeriod = '50'; enum ProfileGranularity { low, medium, high, } extension ProfileGranularityExtension on ProfileGranularity { String get display { switch (this) { case ProfileGranularity.low: return 'Profile granularity: low'; case ProfileGranularity.medium: return 'Profile granularity: medium'; case ProfileGranularity.high: default: return 'Profile granularity: high'; } } String get value { switch (this) { case ProfileGranularity.low: return lowProfilePeriod; case ProfileGranularity.medium: return mediumProfilePeriod; case ProfileGranularity.high: default: return highProfilePeriod; } } static ProfileGranularity fromValue(String value) { switch (value) { case lowProfilePeriod: return ProfileGranularity.low; case highProfilePeriod: return ProfileGranularity.high; case mediumProfilePeriod: default: return ProfileGranularity.medium; } } }
devtools/packages/devtools_app/lib/src/profiler/profile_granularity.dart/0
{'file_path': 'devtools/packages/devtools_app/lib/src/profiler/profile_granularity.dart', 'repo_id': 'devtools', 'token_count': 598}
// Copyright 2020 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:collection'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'globals.dart'; /// The page ID (used in routing) for the standalone app-size page. /// /// This must be different to the AppSizeScreen ID which is also used in routing when /// cnnected to a VM to ensure they have unique URLs. const appSizePageId = 'appsize'; const homePageId = ''; const snapshotPageId = 'snapshot'; /// Represents a Page/route for a DevTools screen. class DevToolsRouteConfiguration { DevToolsRouteConfiguration(this.page, this.args); final String page; final Map<String, String> args; } /// Converts between structured [DevToolsRouteConfiguration] (our internal data /// for pages/routing) and [RouteInformation] (generic data that can be persisted /// in the address bar/state objects). class DevToolsRouteInformationParser extends RouteInformationParser<DevToolsRouteConfiguration> { @override Future<DevToolsRouteConfiguration> parseRouteInformation( RouteInformation routeInformation) { final uri = Uri.parse(routeInformation.location); // If the uri has been modified and we do not have a vm service uri as a // query parameter, ensure we manually disconnect from any previously // connected applications. if (uri.queryParameters['uri'] == null) { serviceManager.manuallyDisconnect(); } // routeInformation.path comes from the address bar and (when not empty) is // prefixed with a leading slash. Internally we use "page IDs" that do not // start with slashes but match the screenId for each screen. final path = uri.path.isNotEmpty ? uri.path.substring(1) : ''; final configuration = DevToolsRouteConfiguration(path, uri.queryParameters); return SynchronousFuture<DevToolsRouteConfiguration>(configuration); } @override RouteInformation restoreRouteInformation( DevToolsRouteConfiguration configuration, ) { // Add a leading slash to convert the page ID to a URL path (this is // the opposite of what's done in [parseRouteInformation]). final path = '/${configuration.page ?? ''}'; // Create a new map in case the one we were given was unmodifiable. final params = {...?configuration.args}; params?.removeWhere((key, value) => value == null); return RouteInformation( location: Uri(path: path, queryParameters: params).toString()); } } class DevToolsRouterDelegate extends RouterDelegate<DevToolsRouteConfiguration> with ChangeNotifier, PopNavigatorRouterDelegateMixin<DevToolsRouteConfiguration> { DevToolsRouterDelegate(this._getPage, [GlobalKey<NavigatorState> key]) : navigatorKey = key ?? GlobalKey<NavigatorState>(); static DevToolsRouterDelegate of(BuildContext context) => Router.of(context).routerDelegate as DevToolsRouterDelegate; @override final GlobalKey<NavigatorState> navigatorKey; final Page Function(BuildContext, String, Map<String, String>) _getPage; /// A list of any routes/pages on the stack. /// /// This will usually only contain a single item (it's the visible stack, /// not the history). final routes = ListQueue<DevToolsRouteConfiguration>(); @override DevToolsRouteConfiguration get currentConfiguration => routes.isEmpty ? null : routes.last; @override Widget build(BuildContext context) { final routeConfig = currentConfiguration; final page = routeConfig?.page; final args = routeConfig?.args ?? {}; return Navigator( key: navigatorKey, pages: [_getPage(context, page, args)], onPopPage: _handleOnPopPage, ); } bool _handleOnPopPage(Route<dynamic> route, dynamic result) { if (routes.length <= 1) { return false; } routes.removeLast(); notifyListeners(); return true; } /// Navigates to a new page, optionally updating arguments. /// /// If page and args would be the same, does nothing. /// Existing arguments (for example &uri=) will be preserved unless /// overwritten by [argUpdates]. void navigateIfNotCurrent(String page, [Map<String, String> argUpdates]) { final pageChanged = page != currentConfiguration.page; final argsChanged = _changesArgs(argUpdates); if (!pageChanged && !argsChanged) { return; } navigate(page, argUpdates); } /// Navigates to a new page, optionally updating arguments. /// /// Existing arguments (for example &uri=) will be preserved unless /// overwritten by [argUpdates]. void navigate(String page, [Map<String, String> argUpdates]) { final newArgs = {...currentConfiguration.args, ...?argUpdates}; // Ensure we disconnect from any previously connected applications if we do // not have a vm service uri as a query parameter. if (newArgs['uri'] == null) { serviceManager.manuallyDisconnect(); } _replaceStack(DevToolsRouteConfiguration(page, newArgs)); notifyListeners(); } /// Replaces the navigation stack with a new route. void _replaceStack(DevToolsRouteConfiguration configuration) { routes ..clear() ..add(configuration); } @override Future<void> setNewRoutePath(DevToolsRouteConfiguration configuration) { _replaceStack(configuration); return SynchronousFuture<void>(null); } /// Updates arguments for the current page. /// /// Existing arguments (for example &uri=) will be preserved unless /// overwritten by [argUpdates]. void updateArgsIfNotCurrent(Map<String, String> argUpdates) { final argsChanged = _changesArgs(argUpdates); if (!argsChanged) { return; } final currentPage = currentConfiguration.page; final newArgs = {...currentConfiguration.args, ...?argUpdates}; _replaceStack(DevToolsRouteConfiguration(currentPage, newArgs)); notifyListeners(); } /// Checks whether applying [changes] over the current routes args will result /// in any changes. bool _changesArgs(Map<String, String> changes) => !mapEquals( {...?currentConfiguration.args, ...?changes}, {...?currentConfiguration.args}, ); }
devtools/packages/devtools_app/lib/src/routing.dart/0
{'file_path': 'devtools/packages/devtools_app/lib/src/routing.dart', 'repo_id': 'devtools', 'token_count': 1900}
// 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:async'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:meta/meta.dart'; import 'trees.dart'; import 'utils.dart'; class HoverCellData<T> { HoverCellData(this.data); final T data; } abstract class TableDataClient<T> { void rebuildTable(); /// Override to update data after setting rows. void onSetRows(); void setState(VoidCallback modifyState); /// The way the columns are sorted have changed. /// /// Update the UI to reflect the new state. void onColumnSortChanged(ColumnData<T> column, SortDirection sortDirection); /// Selects by index. Note: This is index of the row as it's rendered /// and not necessarily for rows[] since it may be being rendered in reverse. /// This way, +1 will always move down the visible table. /// scrollBehaviour is a string as defined for the HTML scrollTo() method /// https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollTo (eg. /// `smooth`, `instance`, `auto`). void selectByIndex( int newIndex, { bool keepVisible = true, String scrollBehavior = 'smooth', }); void scrollToIndex(int rowIndex, {String scrollBehavior = 'smooth'}); void clearSelection(); } class TableData<T> extends Object { void setState(VoidCallback modifyState) { client?.setState(modifyState); } TableDataClient<T> client; bool _hasPendingRebuild = false; List<ColumnData<T>> get columns => _columns; final List<ColumnData<T>> _columns = <ColumnData<T>>[]; List<T> data = []; int get rowCount => data?.length ?? 0; ColumnData<T> _sortColumn; SortDirection _sortDirection; set sortColumn(ColumnData<T> column) { _sortColumn = column; _sortDirection = column.numeric ? SortDirection.descending : SortDirection.ascending; } @protected final StreamController<T> selectController = StreamController<T>.broadcast(); final StreamController<HoverCellData<T>> selectElementController = StreamController<HoverCellData<T>>.broadcast(); @mustCallSuper void dispose() { client = null; } Stream<T> get onSelect => selectController.stream; Stream<void> get onRowsChanged => _rowsChangedController.stream; final _rowsChangedController = StreamController<void>.broadcast(); Stream<HoverCellData<T>> get onCellHover => selectElementController.stream; void addColumn(ColumnData<T> column) { _columns.add(column); } void setRows(List<T> data) { // If the selected object is no longer valid, clear the selection and // scroll to the top. if (!data.contains(_selectedObject)) { if (rowCount > 0) { client?.scrollToIndex(0, scrollBehavior: 'auto'); } client?.clearSelection(); } // Copy the list, so that changes to it don't affect us. this.data = data.toList(); _rowsChangedController.add(null); client?.onSetRows(); if (_sortColumn == null) { final ColumnData<T> column = _columns.firstWhere( (ColumnData<T> c) => c.supportsSorting, orElse: () => null); if (column != null) { sortColumn = column; } } if (_sortColumn != null) { _doSort(); } scheduleRebuild(); } void scrollTo(T row, {String scrollBehavior = 'smooth'}) { final index = data.indexOf(row); if (index == -1) { return; } if (_hasPendingRebuild) { // Wait for the content to be rendered before we scroll otherwise we may // not be able to scroll far enough. setState(() { // We assume the index is still valid. Alternately we search for the // index again. The one thing we should absolutely not do is call the // scrollTo helper method again as there is a significant risk scrollTo // would never be called if items are added to the table every frame. client?.scrollToIndex(index, scrollBehavior: scrollBehavior); }); return; } client?.scrollToIndex(index, scrollBehavior: scrollBehavior); } void scheduleRebuild() { if (!_hasPendingRebuild) { // Set a flag to ensure we don't schedule rebuilds if there's already one // in the queue. _hasPendingRebuild = true; setState(() { _hasPendingRebuild = false; client?.rebuildTable(); }); } } void _doSort() { final ColumnData<T> column = _sortColumn; final int direction = _sortDirection == SortDirection.ascending ? 1 : -1; client?.onColumnSortChanged(column, _sortDirection); _sortData(column, direction); } void _sortData(ColumnData column, int direction) { data.sort((T a, T b) => _compareData(a, b, column, direction)); } int _compareData(T a, T b, ColumnData column, int direction) { return column.compare(a, b) * direction; } T get selectedObject => _selectedObject; T _selectedObject; int get selectedObjectIndex => _selectedObjectIndex; int _selectedObjectIndex; void setSelection(T object, int index) { assert(index == null || data[index] == object); _selectedObjectIndex = index; if (selectedObject != object) { _selectedObject = object; selectController.add(object); } } bool get hasSelection => _selectedObject != null; void onColumnClicked(ColumnData<T> column) { if (!column.supportsSorting) { return; } if (_sortColumn == column) { _sortDirection = _sortDirection.reverse(); } else { sortColumn = column; } _doSort(); scheduleRebuild(); } /// Override this method if the table should handle left key strokes. void handleLeftKey() {} /// Override this method if the table should handle right key strokes. void handleRightKey() {} } /// Data for a tree table where nodes in the tree can be expanded and /// collapsed. /// /// A TreeTableData must have exactly one column that is a [TreeColumnData]. class TreeTableData<T extends TreeNode<T>> extends TableData<T> { @override void addColumn(ColumnData<T> column) { // Avoid adding multiple TreeColumnData columns. assert(column is! TreeColumnData<T> || _columns.whereType<TreeColumnData>().isEmpty); super.addColumn(column); } @override void handleLeftKey() { if (_selectedObject != null) { if (_selectedObject.isExpanded) { // Collapse node and preserve selection. collapseNode(_selectedObject); } else { // Select the node's parent. final parentIndex = data.indexOf(_selectedObject.parent); if (parentIndex != null && parentIndex != -1) { client?.selectByIndex(parentIndex); } } } } @override void handleRightKey() { if (_selectedObject != null) { if (_selectedObject.isExpanded) { // Select the node's first child. final firstChildIndex = data.indexOf(_selectedObject.children.first); client?.selectByIndex(firstChildIndex); } else if (_selectedObject.isExpandable) { // Expand node and preserve selection. expandNode(_selectedObject); } else { // The node is not expandable. Select the next node in range. final nextIndex = data.indexOf(_selectedObject) + 1; if (nextIndex != data.length) { client?.selectByIndex(nextIndex); } } } } @override void _sortData(ColumnData column, int direction) { final List<T> sortedData = []; void _addToSortedData(T dataObject) { sortedData.add(dataObject); if (dataObject.isExpanded) { dataObject.children ..sort((T a, T b) => _compareData(a, b, column, direction)) ..forEach(_addToSortedData); } } data.where((dataObject) => dataObject.level == 0).toList() ..sort((T a, T b) => _compareData(a, b, column, direction)) ..forEach(_addToSortedData); data = sortedData; } void collapseNode(T dataObject) { void cascadingRemove(T _dataObject) { if (!data.contains(_dataObject)) return; data.remove(_dataObject); (_dataObject.children).forEach(cascadingRemove); } assert(data.contains(dataObject)); dataObject.children.forEach(cascadingRemove); dataObject.collapse(); _selectedObject ??= dataObject; setRows(data); } void expandNode(T dataObject) { void expand(T node) { assert(data.contains(node)); int insertIndex = data.indexOf(node) + 1; for (T child in node.children) { data.insert(insertIndex, child); if (child.isExpanded) { expand(child); } insertIndex++; } node.expand(); } expand(dataObject); _selectedObject ??= dataObject; setRows(data); } } // TODO(peterdjlee): Remove get from method names. abstract class ColumnData<T> { ColumnData( this.title, { this.titleTooltip, @required this.fixedWidthPx, this.alignment = ColumnAlignment.left, }) : assert(fixedWidthPx != null), minWidthPx = null; ColumnData.wide( this.title, { this.titleTooltip, this.minWidthPx, this.alignment = ColumnAlignment.left, }) : fixedWidthPx = null; final String title; final String titleTooltip; /// Width of the column expressed as a fixed number of pixels. final double fixedWidthPx; final double minWidthPx; /// How much to indent the data object by. /// /// This should only be non-zero for [TreeColumnData]. double getNodeIndentPx(T dataObject) => 0.0; final ColumnAlignment alignment; bool get numeric => false; bool get supportsSorting => numeric; int compare(T a, T b) { final Comparable valueA = getValue(a); final Comparable valueB = getValue(b); return valueA.compareTo(valueB); } /// Get the cell's value from the given [dataObject]. dynamic getValue(T dataObject); /// Get the cell's display value from the given [dataObject]. String getDisplayValue(T dataObject) => getValue(dataObject).toString(); // TODO(kenz): this isn't hooked up to the table elements. Do this. /// Get the cell's tooltip value from the given [dataObject]. String getTooltip(T dataObject) => getDisplayValue(dataObject); /// Get the cell's text color from the given [dataObject]. Color getTextColor(T dataObject) => null; @override String toString() => title; } abstract class TreeColumnData<T extends TreeNode<T>> extends ColumnData<T> { TreeColumnData(String title) : super.wide(title); static const treeToggleWidth = 14.0; final StreamController<T> nodeExpandedController = StreamController<T>.broadcast(); Stream<T> get onNodeExpanded => nodeExpandedController.stream; final StreamController<T> nodeCollapsedController = StreamController<T>.broadcast(); Stream<T> get onNodeCollapsed => nodeCollapsedController.stream; @override double getNodeIndentPx(T dataObject) { return dataObject.level * treeToggleWidth; } } enum ColumnAlignment { left, right, center, }
devtools/packages/devtools_app/lib/src/table_data.dart/0
{'file_path': 'devtools/packages/devtools_app/lib/src/table_data.dart', 'repo_id': 'devtools', 'token_count': 3934}
// 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. /// Returns a simplified version of a package url, replacing "path/to/flutter" /// with "package:". /// /// This is a bit of a hack, as we have file paths instead of the explicit /// "package:uris" we'd like to have. This will be problematic for a use case /// such as "packages/my_package/src/utils/packages/flutter/". String getSimplePackageUrl(String url) { const newPackagePrefix = 'package:'; const originalPackagePrefix = 'packages/'; const flutterPrefix = 'packages/flutter/'; const flutterWebPrefix = 'packages/flutter_web/'; final flutterPrefixIndex = url.indexOf(flutterPrefix); final flutterWebPrefixIndex = url.indexOf(flutterWebPrefix); if (flutterPrefixIndex != -1) { return newPackagePrefix + url.substring(flutterPrefixIndex + originalPackagePrefix.length); } else if (flutterWebPrefixIndex != -1) { return newPackagePrefix + url.substring(flutterWebPrefixIndex + originalPackagePrefix.length); } return url; } /// Returns a normalized vm service uri. /// /// Removes trailing characters, trailing url fragments, and decodes urls that /// were accidentally encoded. /// /// For example, given a [value] of http://127.0.0.1:60667/72K34Xmq0X0=/#/vm, /// this method will return the URI http://127.0.0.1:60667/72K34Xmq0X0=/. /// /// Returns null if the [Uri] parsed from [value] is not [Uri.absolute] /// (ie, it has no scheme or it has a fragment). Uri normalizeVmServiceUri(String value) { value = value.trim(); // Clean up urls that have a devtools server's prefix, aka: // http://127.0.0.1:9101?uri=http%3A%2F%2F127.0.0.1%3A56142%2FHOwgrxalK00%3D%2F const uriParamToken = '?uri='; if (value.contains(uriParamToken)) { value = value.substring(value.indexOf(uriParamToken) + uriParamToken.length); } // Cleanup encoded urls likely copied from the uri of an existing running // DevTools app. if (value.contains('%3A%2F%2F')) { value = Uri.decodeFull(value); } final uri = Uri.parse(value.trim()).removeFragment(); if (!uri.isAbsolute) { return null; } if (uri.path.endsWith('/')) return uri; return uri.replace(path: uri.path); }
devtools/packages/devtools_app/lib/src/url_utils.dart/0
{'file_path': 'devtools/packages/devtools_app/lib/src/url_utils.dart', 'repo_id': 'devtools', 'token_count': 806}
// 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:async'; import 'package:devtools_app/src/auto_dispose.dart'; import 'package:devtools_app/src/auto_dispose_mixin.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; class AutoDisposedWidget extends StatefulWidget { const AutoDisposedWidget(this.stream, {Key key}) : super(key: key); final Stream stream; @override _AutoDisposedWidgetState createState() => _AutoDisposedWidgetState(); } class AutoDisposeContoller extends DisposableController with AutoDisposeControllerMixin {} class _AutoDisposedWidgetState extends State<AutoDisposedWidget> with AutoDisposeMixin { int eventCount = 0; @override void initState() { super.initState(); autoDispose(widget.stream.listen(_onData)); } void _onData(dynamic data) { eventCount++; } @override Widget build(BuildContext context) { return Container(); } } void main() { group('Disposer', () { test('disposes streams', () { final disposer = Disposer(); final controller1 = StreamController(sync: true); final controller2 = StreamController(sync: true); var c1Events = 0; var c2Events = 0; disposer.autoDispose(controller1.stream.listen((data) { c1Events++; })); disposer.autoDispose(controller2.stream.listen((data) { c2Events++; })); expect(c1Events, 0); expect(c2Events, 0); controller1.add(null); expect(c1Events, 1); expect(c2Events, 0); controller1.add(null); controller2.add(null); expect(c1Events, 2); expect(c2Events, 1); disposer.cancel(); // Make sure stream subscriptions are cancelled. controller1.add(null); controller2.add(null); expect(c1Events, 2); expect(c2Events, 1); }); test('disposes listeners', () { final disposer = Disposer(); final notifier = ValueNotifier<int>(42); final values = <int>[]; disposer.addAutoDisposeListener(notifier, () { values.add(notifier.value); }); // ignore: invalid_use_of_protected_member expect(notifier.hasListeners, isTrue); notifier.value = 13; expect(values.length, equals(1)); expect(values.last, equals(13)); notifier.value = 15; expect(values.length, equals(2)); expect(values.last, equals(15)); // ignore: invalid_use_of_protected_member expect(notifier.hasListeners, isTrue); disposer.cancel(); // ignore: invalid_use_of_protected_member expect(notifier.hasListeners, isFalse); notifier.value = 17; // Verify listener not fired. expect(values.length, equals(2)); expect(values.last, equals(15)); // Add a new listener: disposer.addAutoDisposeListener(notifier, () { values.add(notifier.value); }); // ignore: invalid_use_of_protected_member expect(notifier.hasListeners, isTrue); notifier.value = 19; expect(values.length, equals(3)); expect(values.last, equals(19)); disposer.cancel(); // ignore: invalid_use_of_protected_member expect(notifier.hasListeners, isFalse); notifier.value = 21; expect(values.length, equals(3)); expect(values.last, equals(19)); }); test('throws an error when disposing already-disposed listeners', () { final disposer = Disposer(); final notifier = ValueNotifier<int>(42); final values = <int>[]; void callback() { values.add(notifier.value); } disposer.addAutoDisposeListener(notifier, callback); notifier.value = 72; expect(values, [72]); // After disposal, all notifier methods will throw. Disposer needs // to ignore this when cancelling. notifier.dispose(); expect(() => disposer.cancel(), throwsA(anything)); expect(values, [72]); }); }); testWidgets('Test stream auto dispose', (WidgetTester tester) async { // Build our app and trigger a frame. final key = GlobalKey(); final controller = StreamController(); await tester.pumpWidget(AutoDisposedWidget(controller.stream, key: key)); final _AutoDisposedWidgetState state = key.currentState; // Verify that the eventCount matches the number of events sent. expect(state.eventCount, 0); controller.add(null); await tester.pump(); expect(state.eventCount, 1); controller.add(null); await tester.pump(); expect(state.eventCount, 2); await tester.pumpWidget(Container()); // Verify that the eventCount is not updated after the widget has been // disposed. expect(state.eventCount, 2); controller.add(null); await tester.pump(); expect(state.eventCount, 2); }); test('Test Listenable auto dispose', () async { final controller = AutoDisposeContoller(); final notifier = ValueNotifier<int>(42); final values = <int>[]; controller.addAutoDisposeListener(notifier, () { values.add(notifier.value); }); // ignore: invalid_use_of_protected_member expect(notifier.hasListeners, isTrue); notifier.value = 13; expect(values.length, equals(1)); expect(values.last, equals(13)); notifier.value = 15; expect(values.length, equals(2)); expect(values.last, equals(15)); // ignore: invalid_use_of_protected_member expect(notifier.hasListeners, isTrue); controller.cancel(); // ignore: invalid_use_of_protected_member expect(notifier.hasListeners, isFalse); notifier.value = 17; // Verify listener not fired. expect(values.length, equals(2)); expect(values.last, equals(15)); }); }
devtools/packages/devtools_app/test/auto_dispose_mixin_test.dart/0
{'file_path': 'devtools/packages/devtools_app/test/auto_dispose_mixin_test.dart', 'repo_id': 'devtools', 'token_count': 2194}
// 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 'package:devtools_app/src/enum_utils.dart'; import 'package:flutter_test/flutter_test.dart'; enum Color { red, green, blue } void main() { final colorUtils = EnumUtils<Color>(Color.values); test('getEnum', () { expect(colorUtils.enumEntry('red'), Color.red); expect(colorUtils.enumEntry('green'), Color.green); expect(colorUtils.enumEntry('blue'), Color.blue); expect(colorUtils.enumEntry('yellow'), null); }); test('getName', () { expect(colorUtils.name(Color.red), 'red'); expect(colorUtils.name(Color.green), 'green'); expect(colorUtils.name(Color.blue), 'blue'); }); }
devtools/packages/devtools_app/test/enum_utils_test.dart/0
{'file_path': 'devtools/packages/devtools_app/test/enum_utils_test.dart', 'repo_id': 'devtools', 'token_count': 272}
// Copyright 2020 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. @TestOn('vm') import 'package:devtools_app/src/globals.dart'; import 'package:devtools_app/src/http/http_request_data.dart'; import 'package:devtools_app/src/network/network_controller.dart'; import 'package:devtools_app/src/network/network_model.dart'; import 'package:devtools_app/src/service_manager.dart'; import 'package:devtools_app/src/ui/filter.dart'; import 'package:devtools_app/src/version.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:vm_service/vm_service.dart'; import 'support/mocks.dart'; import 'support/utils.dart'; void main() { group('NetworkController', () { NetworkController controller; FakeServiceManager fakeServiceManager; Timeline timeline; SocketProfile socketProfile; setUp(() async { timeline = await loadNetworkProfileTimeline(); socketProfile = loadSocketProfile(); fakeServiceManager = FakeServiceManager( service: FakeServiceManager.createFakeService( timelineData: timeline, socketProfile: socketProfile, ), ); setGlobal(ServiceConnectionManager, fakeServiceManager); // Disables getHttpProfile support. (fakeServiceManager.service as FakeVmService).dartIoVersion = SemanticVersion( major: 1, minor: 2, ); controller = NetworkController(); }); test('initialize recording state', () async { expect(controller.isPolling, false); // Fake service pretends HTTP timeline logging and socket profiling are // always enabled. await controller.startRecording(); expect(controller.isPolling, true); controller.stopRecording(); }); test('start and pause recording', () async { expect(controller.isPolling, false); final notifier = controller.recordingNotifier; await addListenerScope( listenable: notifier, listener: () { expect(notifier.value, true); expect(controller.isPolling, true); }, callback: () async { await controller.startRecording(); }, ); // Pause polling. controller.togglePolling(false); expect(notifier.value, false); expect(controller.isPolling, false); // Resume polling. controller.togglePolling(true); expect(notifier.value, true); expect(controller.isPolling, true); controller.stopRecording(); expect(notifier.value, false); expect(controller.isPolling, false); }); test('process network data', () async { await controller.startRecording(); final requestsNotifier = controller.requests; NetworkRequests profile = requestsNotifier.value; // Check profile is initially empty. expect(profile.requests.isEmpty, true); expect(profile.outstandingHttpRequests.isEmpty, true); // The number of valid requests recorded in the test data. const numRequests = 16; // Refresh network data and ensure requests are populated. await controller.networkService.refreshNetworkData(); profile = requestsNotifier.value; expect(profile.requests.length, numRequests); expect(profile.outstandingHttpRequests.isEmpty, true); const httpMethods = <String>{ 'CONNECT', 'DELETE', 'GET', 'HEAD', 'PATCH', 'POST', 'PUT', }; final List<HttpRequestData> httpRequests = profile.requests .whereType<HttpRequestData>() .cast<HttpRequestData>() .toList(); for (final request in httpRequests) { expect(request.duration, isNotNull); expect(request.general, isNotNull); expect(request.general.length, greaterThan(0)); expect(request.hasCookies, isNotNull); expect(request.inProgress, false); expect(request.instantEvents, isNotNull); expect(httpMethods.contains(request.method), true); expect(request.requestCookies, isNotNull); expect(request.responseCookies, isNotNull); expect(request.startTimestamp, isNotNull); expect(request.status, isNotNull); expect(request.uri, isNotNull); } // Finally, call `clear()` and ensure the requests have been cleared. await controller.clear(); profile = requestsNotifier.value; expect(profile.requests.isEmpty, true); expect(profile.outstandingHttpRequests.isEmpty, true); controller.stopRecording(); }); test('matchesForSearch', () async { // The number of valid requests recorded in the test data. const numRequests = 16; final requestsNotifier = controller.requests; // Refresh network data and ensure requests are populated. await controller.networkService.refreshNetworkData(); final profile = requestsNotifier.value; expect(profile.requests.length, numRequests); expect(controller.matchesForSearch('year=2019').length, equals(5)); expect(controller.matchesForSearch('127.0.0.1').length, equals(14)); expect(controller.matchesForSearch('IPv6').length, equals(2)); expect(controller.matchesForSearch('').length, equals(0)); // Search with incorrect case. expect(controller.matchesForSearch('YEAR').length, equals(5)); }); test('matchesForSearch sets isSearchMatch property', () async { // The number of valid requests recorded in the test data. const numRequests = 16; final requestsNotifier = controller.requests; // Refresh network data and ensure requests are populated. await controller.networkService.refreshNetworkData(); final profile = requestsNotifier.value; expect(profile.requests.length, numRequests); var matches = controller.matchesForSearch('year=2019'); expect(matches.length, equals(5)); verifyIsSearchMatch(profile.requests, matches); matches = controller.matchesForSearch('IPv6'); expect(matches.length, equals(2)); verifyIsSearchMatch(profile.requests, matches); }); test('filterData', () async { // The number of valid requests recorded in the test data. const numRequests = 16; final requestsNotifier = controller.requests; // Refresh network data and ensure requests are populated. await controller.networkService.refreshNetworkData(); final profile = requestsNotifier.value; for (final r in profile.requests) { print('${r.uri}, ${r.method}, ${r.status}, ${r.type}'); } expect(profile.requests, hasLength(numRequests)); expect(controller.filteredData.value, hasLength(numRequests)); controller .filterData(QueryFilter.parse('127.0.0.1', controller.filterArgs)); expect(profile.requests, hasLength(numRequests)); expect(controller.filteredData.value, hasLength(14)); controller.filterData(QueryFilter.parse('', controller.filterArgs)); expect(profile.requests, hasLength(numRequests)); expect(controller.filteredData.value, hasLength(numRequests)); controller .filterData(QueryFilter.parse('method:put', controller.filterArgs)); expect(profile.requests, hasLength(numRequests)); expect(controller.filteredData.value, hasLength(2)); controller.filterData(QueryFilter.parse('m:head', controller.filterArgs)); expect(profile.requests, hasLength(numRequests)); expect(controller.filteredData.value, hasLength(2)); controller .filterData(QueryFilter.parse('-method:put', controller.filterArgs)); expect(profile.requests, hasLength(numRequests)); expect(controller.filteredData.value, hasLength(14)); controller .filterData(QueryFilter.parse('status:Error', controller.filterArgs)); expect(profile.requests, hasLength(numRequests)); expect(controller.filteredData.value, hasLength(7)); controller.filterData(QueryFilter.parse('s:101', controller.filterArgs)); expect(profile.requests, hasLength(numRequests)); expect(controller.filteredData.value, hasLength(2)); controller .filterData(QueryFilter.parse('-s:Error', controller.filterArgs)); expect(profile.requests, hasLength(numRequests)); expect(controller.filteredData.value, hasLength(9)); controller .filterData(QueryFilter.parse('type:http', controller.filterArgs)); expect(profile.requests, hasLength(numRequests)); expect(controller.filteredData.value, hasLength(7)); controller.filterData(QueryFilter.parse('t:ws', controller.filterArgs)); expect(profile.requests, hasLength(numRequests)); expect(controller.filteredData.value, hasLength(2)); controller.filterData(QueryFilter.parse('-t:ws', controller.filterArgs)); expect(profile.requests, hasLength(numRequests)); expect(controller.filteredData.value, hasLength(14)); controller.filterData(QueryFilter.parse('-', controller.filterArgs)); expect(profile.requests, hasLength(numRequests)); expect(controller.filteredData.value, hasLength(0)); controller .filterData(QueryFilter.parse('nonsense', controller.filterArgs)); expect(profile.requests, hasLength(numRequests)); expect(controller.filteredData.value, hasLength(0)); controller .filterData(QueryFilter.parse('-nonsense', controller.filterArgs)); expect(profile.requests, hasLength(numRequests)); expect(controller.filteredData.value, hasLength(0)); controller.filterData(null); expect(profile.requests, hasLength(numRequests)); expect(controller.filteredData.value, hasLength(numRequests)); controller .filterData(QueryFilter.parse('-t:ws,http', controller.filterArgs)); expect(profile.requests, hasLength(numRequests)); expect(controller.filteredData.value, hasLength(7)); controller.filterData( QueryFilter.parse('-t:ws,http method:put', controller.filterArgs)); expect(profile.requests, hasLength(numRequests)); expect(controller.filteredData.value, hasLength(1)); controller.filterData( QueryFilter.parse('-status:error method:get', controller.filterArgs)); expect(profile.requests, hasLength(numRequests)); expect(controller.filteredData.value, hasLength(3)); controller.filterData(QueryFilter.parse( '-status:error method:get t:txt', controller.filterArgs)); expect(profile.requests, hasLength(numRequests)); expect(controller.filteredData.value, hasLength(1)); }); }); }
devtools/packages/devtools_app/test/network_controller_test.dart/0
{'file_path': 'devtools/packages/devtools_app/test/network_controller_test.dart', 'repo_id': 'devtools', 'token_count': 3852}
// 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:async'; import 'package:devtools_app/src/core/message_bus.dart'; import 'package:devtools_app/src/globals.dart'; import 'package:devtools_app/src/notifications.dart'; import 'package:devtools_app/src/service_extensions.dart'; import 'package:devtools_app/src/service_manager.dart'; import 'package:devtools_app/src/service_registrations.dart'; import 'package:devtools_app/src/ui/service_extension_widgets.dart'; import 'package:devtools_app/src/utils.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/mockito.dart'; import 'support/mocks.dart'; import 'support/wrappers.dart'; void main() { MockServiceManager mockServiceManager; setUp(() { mockServiceManager = MockServiceManager(); when(mockServiceManager.serviceExtensionManager) .thenReturn(FakeServiceExtensionManager()); setGlobal(ServiceConnectionManager, mockServiceManager); }); group('Hot Reload Button', () { int reloads = 0; setUp(() { reloads = 0; when(mockServiceManager.performHotReload()).thenAnswer((invocation) { reloads++; return Future<void>.value(); }); }); testWidgetsWithContext('performs a hot reload when pressed', (WidgetTester tester) async { registerServiceExtension(mockServiceManager, hotReload); final button = HotReloadButton(); await tester.pumpWidget( wrap(wrapWithNotifications(Scaffold(body: Center(child: button)))), ); expect(find.byWidget(button), findsOneWidget); await tester.pumpAndSettle(); expect(reloads, 0); await tester.tap(find.byWidget(button)); await tester.pumpAndSettle(); expect(reloads, 1); }, context: { MessageBus: MessageBus(), }); testWidgets( 'does not perform a hot reload when the extension is not registered.', (WidgetTester tester) async { registerServiceExtension( mockServiceManager, hotReload, serviceAvailable: false, ); final button = HotReloadButton(); await tester.pumpWidget(wrap(Scaffold(body: Center(child: button)))); expect(find.byWidget(button), findsOneWidget); await tester.pumpAndSettle(); expect(reloads, 0); await tester.tap(find.byWidget(button)); await tester.pumpAndSettle(); expect(reloads, 0); }); }); group('Hot Restart Button', () { int restarts = 0; setUp(() { restarts = 0; when(mockServiceManager.performHotRestart()).thenAnswer((invocation) { restarts++; return Future<void>.value(); }); }); testWidgetsWithContext('performs a hot restart when pressed', (WidgetTester tester) async { registerServiceExtension(mockServiceManager, hotRestart); final button = HotRestartButton(); await tester.pumpWidget( wrap(wrapWithNotifications(Scaffold(body: Center(child: button)))), ); expect(find.byWidget(button), findsOneWidget); await tester.pumpAndSettle(); expect(restarts, 0); await tester.tap(find.byWidget(button)); await tester.pumpAndSettle(); expect(restarts, 1); }, context: { MessageBus: MessageBus(), }); testWidgets( 'does not perform a hot restart when the service is not available', (WidgetTester tester) async { registerServiceExtension( mockServiceManager, hotRestart, serviceAvailable: false, ); final button = HotRestartButton(); await tester.pumpWidget(wrap(Scaffold(body: Center(child: button)))); expect(find.byWidget(button), findsOneWidget); await tester.pumpAndSettle(); expect(restarts, 0); await tester.tap(find.byWidget(button)); await tester.pumpAndSettle(); expect(restarts, 0); }); }); group('Structured Errors toggle', () { ValueListenable<ServiceExtensionState> serviceState; ServiceExtensionState mostRecentState; final serviceStateListener = () { mostRecentState = serviceState.value; }; setUp(() { (mockServiceManager.serviceExtensionManager as FakeServiceExtensionManager) .fakeFrame(); serviceState = mockServiceManager.serviceExtensionManager .getServiceExtensionState(structuredErrors.extension); serviceState.addListener(serviceStateListener); }); tearDown(() async { serviceState.removeListener(serviceStateListener); }); testWidgets('toggles', (WidgetTester tester) async { await (mockServiceManager.serviceExtensionManager as FakeServiceExtensionManager) .fakeAddServiceExtension(structuredErrors.extension); final button = StructuredErrorsToggle(); await tester.pumpWidget(wrap(Scaffold(body: Center(child: button)))); expect(find.byWidget(button), findsOneWidget); await tester.tap(find.byWidget(button)); await tester.pumpAndSettle(); (mockServiceManager.serviceExtensionManager as FakeServiceExtensionManager) .fakeFrame(); expect(mostRecentState.value, true); await tester.tap(find.byWidget(button)); await tester.pumpAndSettle(); expect(mostRecentState.value, false); }); testWidgets('updates based on the service extension', (WidgetTester tester) async { await (mockServiceManager.serviceExtensionManager as FakeServiceExtensionManager) .fakeAddServiceExtension(structuredErrors.extension); final button = StructuredErrorsToggle(); await tester.pumpWidget(wrap(Scaffold(body: Center(child: button)))); expect(find.byWidget(button), findsOneWidget); await mockServiceManager.serviceExtensionManager .setServiceExtensionState(structuredErrors.extension, true, true); await tester.pumpAndSettle(); expect(toggle.value, true, reason: 'The extension is enabled.'); await mockServiceManager.serviceExtensionManager .setServiceExtensionState(structuredErrors.extension, false, false); await tester.pumpAndSettle(); expect(toggle.value, false, reason: 'The extension is disabled.'); }); }); } Widget wrapWithNotifications(Widget child) { return Notifications(child: child); } void registerServiceExtension( MockServiceManager mockServiceManager, RegisteredServiceDescription description, { bool serviceAvailable = true, }) { when(mockServiceManager.registeredServiceListenable(description.service)) .thenAnswer((invocation) { final listenable = ImmediateValueNotifier(serviceAvailable); return listenable; }); } Switch get toggle => find.byType(Switch).evaluate().first.widget;
devtools/packages/devtools_app/test/service_extension_widgets_test.dart/0
{'file_path': 'devtools/packages/devtools_app/test/service_extension_widgets_test.dart', 'repo_id': 'devtools', 'token_count': 2581}
// 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 'package:devtools_app/src/version.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { group('FlutterVersion', () { test('infers semantic version', () { var flutterVersion = FlutterVersion.parse({'frameworkVersion': '1.10.7-pre.42'}); expect(flutterVersion.major, equals(1)); expect(flutterVersion.minor, equals(10)); expect(flutterVersion.patch, equals(7)); expect(flutterVersion.preReleaseMajor, equals(42)); expect(flutterVersion.preReleaseMinor, equals(0)); flutterVersion = FlutterVersion.parse({'frameworkVersion': '1.10.7-pre42'}); expect(flutterVersion.major, equals(1)); expect(flutterVersion.minor, equals(10)); expect(flutterVersion.patch, equals(7)); expect(flutterVersion.preReleaseMajor, equals(42)); expect(flutterVersion.preReleaseMinor, equals(0)); flutterVersion = FlutterVersion.parse({'frameworkVersion': '1.10.11-pre42'}); expect(flutterVersion.major, equals(1)); expect(flutterVersion.minor, equals(10)); expect(flutterVersion.patch, equals(11)); expect(flutterVersion.preReleaseMajor, equals(42)); expect(flutterVersion.preReleaseMinor, equals(0)); flutterVersion = FlutterVersion.parse({'frameworkVersion': '2.3.0-17.0.pre.355'}); expect(flutterVersion.major, equals(2)); expect(flutterVersion.minor, equals(3)); expect(flutterVersion.patch, equals(0)); expect(flutterVersion.preReleaseMajor, equals(17)); expect(flutterVersion.preReleaseMinor, equals(0)); flutterVersion = FlutterVersion.parse({'frameworkVersion': '2.3.0-17.0.pre'}); expect(flutterVersion.major, equals(2)); expect(flutterVersion.minor, equals(3)); expect(flutterVersion.patch, equals(0)); expect(flutterVersion.preReleaseMajor, equals(17)); expect(flutterVersion.preReleaseMinor, equals(0)); flutterVersion = FlutterVersion.parse({'frameworkVersion': '2.3.0-17'}); expect(flutterVersion.major, equals(2)); expect(flutterVersion.minor, equals(3)); expect(flutterVersion.patch, equals(0)); expect(flutterVersion.preReleaseMajor, equals(17)); expect(flutterVersion.preReleaseMinor, equals(0)); flutterVersion = FlutterVersion.parse({'frameworkVersion': '2.3.0'}); expect(flutterVersion.major, equals(2)); expect(flutterVersion.minor, equals(3)); expect(flutterVersion.patch, equals(0)); expect(flutterVersion.preReleaseMajor, isNull); expect(flutterVersion.preReleaseMinor, isNull); flutterVersion = FlutterVersion.parse({'frameworkVersion': 'bad-version'}); expect(flutterVersion.major, equals(0)); expect(flutterVersion.minor, equals(0)); expect(flutterVersion.patch, equals(0)); }); }); group('SemanticVersion', () { test('isVersionSupported', () { final supportedVersion = SemanticVersion(major: 1, minor: 1, patch: 1); expect( SemanticVersion().isSupported(supportedVersion: SemanticVersion()), isTrue, ); expect( SemanticVersion(major: 1, minor: 1, patch: 2) .isSupported(supportedVersion: supportedVersion), isTrue, ); expect( SemanticVersion(major: 1, minor: 2, patch: 1) .isSupported(supportedVersion: supportedVersion), isTrue, ); expect( SemanticVersion(major: 2, minor: 1, patch: 1) .isSupported(supportedVersion: supportedVersion), isTrue, ); expect( SemanticVersion(major: 2, minor: 1, patch: 1).isSupported( supportedVersion: SemanticVersion(major: 2, minor: 2, patch: 1)), isFalse, ); }); test('compareTo', () { var version = SemanticVersion(major: 1, minor: 1, patch: 1); expect( version.compareTo(SemanticVersion(major: 1, minor: 1, patch: 2)), equals(-1), ); expect( version.compareTo(SemanticVersion(major: 1, minor: 2, patch: 1)), equals(-1), ); expect( version.compareTo(SemanticVersion(major: 2, minor: 1, patch: 1)), equals(-1), ); expect( version.compareTo(SemanticVersion(major: 1, minor: 1)), equals(1), ); expect( version.compareTo(SemanticVersion(major: 1, minor: 1, patch: 1)), equals(0), ); expect( version.compareTo( SemanticVersion(major: 1, minor: 1, patch: 1, preReleaseMajor: 1)), equals(-1), ); version = SemanticVersion( major: 1, minor: 1, patch: 1, preReleaseMajor: 1, preReleaseMinor: 2, ); expect( version.compareTo( SemanticVersion(major: 1, minor: 1, patch: 1, preReleaseMajor: 1)), equals(1), ); expect( version.compareTo(SemanticVersion( major: 1, minor: 1, patch: 1, preReleaseMajor: 2, preReleaseMinor: 1, )), equals(-1), ); }); test('toString', () { expect( SemanticVersion(major: 1, minor: 1, patch: 1).toString(), equals('1.1.1'), ); expect( SemanticVersion(major: 1, minor: 1, patch: 1, preReleaseMajor: 17) .toString(), equals('1.1.1-17'), ); expect( SemanticVersion( major: 1, minor: 1, patch: 1, preReleaseMajor: 17, preReleaseMinor: 1, ).toString(), equals('1.1.1-17.1'), ); expect( SemanticVersion( major: 1, minor: 1, patch: 1, preReleaseMinor: 1, ).toString(), equals('1.1.1-0.1'), ); }); }); }
devtools/packages/devtools_app/test/version_test.dart/0
{'file_path': 'devtools/packages/devtools_app/test/version_test.dart', 'repo_id': 'devtools', 'token_count': 2636}
// 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. /// All server APIs prefix: const String apiPrefix = 'api/'; /// Flutter GA properties APIs: const String apiGetFlutterGAEnabled = '${apiPrefix}getFlutterGAEnabled'; const String apiGetFlutterGAClientId = '${apiPrefix}getFlutterGAClientId'; /// DevTools GA properties APIs: const String apiResetDevTools = '${apiPrefix}resetDevTools'; const String apiGetDevToolsFirstRun = '${apiPrefix}getDevToolsFirstRun'; const String apiGetDevToolsEnabled = '${apiPrefix}getDevToolsEnabled'; const String apiSetDevToolsEnabled = '${apiPrefix}setDevToolsEnabled'; /// Property name to apiSetDevToolsEnabled the DevToolsEnabled is the name used /// in queryParameter: const String devToolsEnabledPropertyName = 'enabled'; /// Survey properties APIs: /// setActiveSurvey sets the survey property to fetch and save JSON values e.g., Q1-2020 const String apiSetActiveSurvey = '${apiPrefix}setActiveSurvey'; /// Survey name passed in apiSetActiveSurvey, the activeSurveyName is the property name /// passed as a queryParameter and is the property in ~/.devtools too. const String activeSurveyName = 'activeSurveyName'; /// Returns the surveyActionTaken of the activeSurvey (apiSetActiveSurvey). const String apiGetSurveyActionTaken = '${apiPrefix}getSurveyActionTaken'; /// Sets the surveyActionTaken of the of the activeSurvey (apiSetActiveSurvey). const String apiSetSurveyActionTaken = '${apiPrefix}setSurveyActionTaken'; /// Property name to apiSetSurveyActionTaken the surveyActionTaken is the name /// passed in queryParameter: const String surveyActionTakenPropertyName = 'surveyActionTaken'; /// Returns the surveyShownCount of the of the activeSurvey (apiSetActiveSurvey). const String apiGetSurveyShownCount = '${apiPrefix}getSurveyShownCount'; /// Increments the surveyShownCount of the of the activeSurvey (apiSetActiveSurvey). const String apiIncrementSurveyShownCount = '${apiPrefix}incrementSurveyShownCount'; /// Returns the base app size file, if present. const String apiGetBaseAppSizeFile = '${apiPrefix}getBaseAppSizeFile'; /// Returns the test app size file used for comparing two files in a diff, if /// present. const String apiGetTestAppSizeFile = '${apiPrefix}getTestAppSizeFile'; const String baseAppSizeFilePropertyName = 'appSizeBase'; const String testAppSizeFilePropertyName = 'appSizeTest';
devtools/packages/devtools_shared/lib/src/devtools_api.dart/0
{'file_path': 'devtools/packages/devtools_shared/lib/src/devtools_api.dart', 'repo_id': 'devtools', 'token_count': 700}
// 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 'package:flutter/material.dart'; import 'missing_material_error.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: const MyHomePage(title: 'Flutter Demo Home Page'), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Card( child: Column( mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ makeDemoEntry( context, 'Missing Material Example', MissingMaterialError(), ), ], ), ), ), ); } Widget makeDemoEntry(BuildContext context, String title, Widget nextScreen) { final navigateToDemo = () async { await Navigator.push( context, MaterialPageRoute(builder: (context) => nextScreen), ); }; navigateCallbacks[title] = navigateToDemo; return Row( children: <Widget>[ const SizedBox( width: 50.0, ), const Icon(Icons.star), TextButton( child: Text(title), onPressed: navigateToDemo, ), ], ); } } Map<String, Function> navigateCallbacks = {}; // Hook to navigate to a specific screen. void navigateToScreen(String title) { navigateCallbacks[title](); }
devtools/packages/devtools_testing/fixtures/flutter_error_app/lib/main.dart/0
{'file_path': 'devtools/packages/devtools_testing/fixtures/flutter_error_app/lib/main.dart', 'repo_id': 'devtools', 'token_count': 883}
// Copyright 2020 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. // @dart=2.10 import 'package:args/command_runner.dart'; import 'commands/analyze.dart'; import 'commands/generate_changelog.dart'; import 'commands/list.dart'; import 'commands/packages_get.dart'; import 'commands/repo_check.dart'; import 'commands/rollback.dart'; class DevToolsCommandRunner extends CommandRunner { DevToolsCommandRunner() : super('repo_tool', 'A repo management tool for DevTools.') { addCommand(AnalyzeCommand()); addCommand(RepoCheckCommand()); addCommand(ListCommand()); addCommand(PackagesGetCommand()); addCommand(GenerateChangelogCommand()); addCommand(RollbackCommand()); } }
devtools/tool/lib/repo_tool.dart/0
{'file_path': 'devtools/tool/lib/repo_tool.dart', 'repo_id': 'devtools', 'token_count': 263}
import 'package:dio/dio.dart'; main() async { Dio dio = Dio( BaseOptions( baseUrl: "http://www.dtworkroom.com/doris/1/2.0.0", method: "GET", ), ); Response response; //No generic type, the ResponseType will work. response = await dio.get("/test"); print(response.data is Map); Response<Map<String,dynamic>> r0= await dio.get("/test"); print(r0.data.containsKey("errCode")); response = await dio.get<Map>("/test"); print(response.data is Map); response = await dio.get<String>("/test"); print(response.data is String); response = await dio.get("/test", options: Options(responseType: ResponseType.plain)); print(response.data is String); // the content of "https://baidu.com" is a html file, So it can't be convert to Map type, // it will cause a FormatException. response = await dio.get<Map>("https://baidu.com").catchError(print); // This works well. response = await dio.get("https://baidu.com"); // This works well too. response = await dio.get<String>("https://baidu.com"); // This is the recommended way. Response<String> r = await dio.get<String>("https://baidu.com"); print(r.data.length); }
dio/example/generic.dart/0
{'file_path': 'dio/example/generic.dart', 'repo_id': 'dio', 'token_count': 422}
export 'repositories/auth_impl.dart'; export 'repositories/items_impl.dart';
duck_duck_shop/lib/data/repositories.dart/0
{'file_path': 'duck_duck_shop/lib/data/repositories.dart', 'repo_id': 'duck_duck_shop', 'token_count': 30}
import 'package:flutter/material.dart'; class FilledButton extends StatelessWidget { const FilledButton({ Key key, @required this.child, @required this.onPressed, this.height, this.minWidth, this.heroTag, this.margin = EdgeInsets.zero, this.color = Colors.white, this.backgroundColor = Colors.blue, this.shape, }) : super(key: key); final Color color; final Color backgroundColor; final Widget child; final EdgeInsets margin; final double height; final double minWidth; final String heroTag; final VoidCallback onPressed; final ShapeBorder shape; @override Widget build(BuildContext context) { final buttonTheme = ButtonTheme.of(context); final button = TextButton( style: TextButton.styleFrom( primary: color, minimumSize: Size(minWidth ?? buttonTheme.minWidth, height ?? buttonTheme.height), backgroundColor: onPressed != null ? backgroundColor : backgroundColor.withOpacity(.75), shape: shape, ), onPressed: onPressed, child: child, ); return Padding( padding: margin, child: heroTag != null ? Hero(tag: heroTag, child: button) : button, ); } }
duck_duck_shop/lib/widgets/filled_button.dart/0
{'file_path': 'duck_duck_shop/lib/widgets/filled_button.dart', 'repo_id': 'duck_duck_shop', 'token_count': 436}
// 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 part of flutter_gpu; base class UniformSlot { UniformSlot._(this.shader, this.uniformName); final Shader shader; final String uniformName; /// The reflected total size of a shader's uniform struct by name. /// /// Returns [null] if the shader does not contain a uniform struct with the /// given name. int? get sizeInBytes { int size = shader._getUniformStructSize(uniformName); return size < 0 ? null : size; } /// Get the reflected offset of a named member in the uniform struct. /// /// Returns [null] if the shader does not contain a uniform struct with the /// given name, or if the uniform struct does not contain a member with the /// given name. int? getMemberOffsetInBytes(String memberName) { int offset = shader._getUniformMemberOffset(uniformName, memberName); return offset < 0 ? null : offset; } } base class Shader extends NativeFieldWrapperClass1 { // [Shader] handles are instantiated when interacting with a [ShaderLibrary]. Shader._(); UniformSlot getUniformSlot(String uniformName) { return UniformSlot._(this, uniformName); } @Native<Int Function(Pointer<Void>, Handle)>( symbol: 'InternalFlutterGpu_Shader_GetUniformStructSize') external int _getUniformStructSize(String uniformStructName); @Native<Int Function(Pointer<Void>, Handle, Handle)>( symbol: 'InternalFlutterGpu_Shader_GetUniformMemberOffset') external int _getUniformMemberOffset( String uniformStructName, String memberName); }
engine/lib/gpu/lib/src/shader.dart/0
{'file_path': 'engine/lib/gpu/lib/src/shader.dart', 'repo_id': 'engine', 'token_count': 506}
// 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:args/command_runner.dart'; import 'environment.dart'; import 'pipeline.dart'; import 'utils.dart'; class AnalyzeCommand extends Command<bool> with ArgUtils<bool> { @override String get name => 'analyze'; @override String get description => 'Analyze the Flutter web engine.'; @override FutureOr<bool> run() async { final Pipeline buildPipeline = Pipeline(steps: <PipelineStep>[ PubGetStep(), AnalyzeStep(), ]); await buildPipeline.run(); return true; } } /// Runs `dart pub get`. class PubGetStep extends ProcessStep { @override String get description => 'pub get'; @override bool get isSafeToInterrupt => true; @override Future<ProcessManager> createProcess() { print('Running `dart pub get`...'); return startProcess( environment.dartExecutable, <String>['pub', 'get'], workingDirectory: environment.webUiRootDir.path, ); } } /// Runs `dart analyze --fatal-infos`. class AnalyzeStep extends ProcessStep { @override String get description => 'analyze'; @override bool get isSafeToInterrupt => true; @override Future<ProcessManager> createProcess() { print('Running `dart analyze`...'); return startProcess( environment.dartExecutable, <String>['analyze', '--fatal-infos'], workingDirectory: environment.webUiRootDir.path, ); } }
engine/lib/web_ui/dev/analyze.dart/0
{'file_path': 'engine/lib/web_ui/dev/analyze.dart', 'repo_id': 'engine', 'token_count': 541}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. part of ui; enum PointerChange { cancel, add, remove, hover, down, move, up, panZoomStart, panZoomUpdate, panZoomEnd, } enum PointerDeviceKind { touch, mouse, stylus, invertedStylus, trackpad, unknown } enum PointerSignalKind { none, scroll, scrollInertiaCancel, scale, unknown } class PointerData { const PointerData({ this.viewId = 0, this.embedderId = 0, this.timeStamp = Duration.zero, this.change = PointerChange.cancel, this.kind = PointerDeviceKind.touch, this.signalKind, this.device = 0, this.pointerIdentifier = 0, this.physicalX = 0.0, this.physicalY = 0.0, this.physicalDeltaX = 0.0, this.physicalDeltaY = 0.0, this.buttons = 0, this.obscured = false, this.synthesized = false, this.pressure = 0.0, this.pressureMin = 0.0, this.pressureMax = 0.0, this.distance = 0.0, this.distanceMax = 0.0, this.size = 0.0, this.radiusMajor = 0.0, this.radiusMinor = 0.0, this.radiusMin = 0.0, this.radiusMax = 0.0, this.orientation = 0.0, this.tilt = 0.0, this.platformData = 0, this.scrollDeltaX = 0.0, this.scrollDeltaY = 0.0, this.panX = 0.0, this.panY = 0.0, this.panDeltaX = 0.0, this.panDeltaY = 0.0, this.scale = 0.0, this.rotation = 0.0, }); final int viewId; final int embedderId; final Duration timeStamp; final PointerChange change; final PointerDeviceKind kind; final PointerSignalKind? signalKind; final int device; final int pointerIdentifier; final double physicalX; final double physicalY; final double physicalDeltaX; final double physicalDeltaY; final int buttons; final bool obscured; final bool synthesized; final double pressure; final double pressureMin; final double pressureMax; final double distance; final double distanceMax; final double size; final double radiusMajor; final double radiusMinor; final double radiusMin; final double radiusMax; final double orientation; final double tilt; final int platformData; final double scrollDeltaX; final double scrollDeltaY; final double panX; final double panY; final double panDeltaX; final double panDeltaY; final double scale; final double rotation; @override String toString() => 'PointerData(x: $physicalX, y: $physicalY)'; String toStringFull() { return '$runtimeType(' 'embedderId: $embedderId, ' 'timeStamp: $timeStamp, ' 'change: $change, ' 'kind: $kind, ' 'signalKind: $signalKind, ' 'device: $device, ' 'pointerIdentifier: $pointerIdentifier, ' 'physicalX: $physicalX, ' 'physicalY: $physicalY, ' 'physicalDeltaX: $physicalDeltaX, ' 'physicalDeltaY: $physicalDeltaY, ' 'buttons: $buttons, ' 'synthesized: $synthesized, ' 'pressure: $pressure, ' 'pressureMin: $pressureMin, ' 'pressureMax: $pressureMax, ' 'distance: $distance, ' 'distanceMax: $distanceMax, ' 'size: $size, ' 'radiusMajor: $radiusMajor, ' 'radiusMinor: $radiusMinor, ' 'radiusMin: $radiusMin, ' 'radiusMax: $radiusMax, ' 'orientation: $orientation, ' 'tilt: $tilt, ' 'platformData: $platformData, ' 'scrollDeltaX: $scrollDeltaX, ' 'scrollDeltaY: $scrollDeltaY, ' 'panX: $panX, ' 'panY: $panY, ' 'panDeltaX: $panDeltaX, ' 'panDeltaY: $panDeltaY, ' 'scale: $scale, ' 'rotation: $rotation, ' 'viewId: $viewId' ')'; } } class PointerDataPacket { const PointerDataPacket({this.data = const <PointerData>[]}); final List<PointerData> data; }
engine/lib/web_ui/lib/pointer.dart/0
{'file_path': 'engine/lib/web_ui/lib/pointer.dart', 'repo_id': 'engine', 'token_count': 1733}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:typed_data'; import 'package:ui/src/engine/vector_math.dart'; import 'package:ui/ui.dart' as ui; import '../util.dart'; import 'canvaskit_api.dart'; import 'color_filter.dart'; import 'native_memory.dart'; typedef SkImageFilterBorrow = void Function(SkImageFilter); /// An [ImageFilter] that can create a managed skia [SkImageFilter] object. /// /// Concrete subclasses of this interface must provide efficient implementation /// of [operator==], to avoid re-creating the underlying skia filters /// whenever possible. /// /// Currently implemented by [CkImageFilter] and [CkColorFilter]. abstract class CkManagedSkImageFilterConvertible implements ui.ImageFilter { void imageFilter(SkImageFilterBorrow borrow); Matrix4 get transform; } /// The CanvasKit implementation of [ui.ImageFilter]. /// /// Currently only supports `blur`, `matrix`, and ColorFilters. abstract class CkImageFilter implements CkManagedSkImageFilterConvertible { factory CkImageFilter.blur( {required double sigmaX, required double sigmaY, required ui.TileMode tileMode}) = _CkBlurImageFilter; factory CkImageFilter.color({required CkColorFilter colorFilter}) = CkColorFilterImageFilter; factory CkImageFilter.matrix( {required Float64List matrix, required ui.FilterQuality filterQuality}) = _CkMatrixImageFilter; factory CkImageFilter.compose( {required CkImageFilter outer, required CkImageFilter inner}) = _CkComposeImageFilter; CkImageFilter._(); @override Matrix4 get transform => Matrix4.identity(); } class CkColorFilterImageFilter extends CkImageFilter { CkColorFilterImageFilter({required this.colorFilter}) : super._() { final SkImageFilter skImageFilter = colorFilter.initRawImageFilter(); _ref = UniqueRef<SkImageFilter>(this, skImageFilter, 'ImageFilter.color'); } final CkColorFilter colorFilter; late final UniqueRef<SkImageFilter> _ref; @override void imageFilter(SkImageFilterBorrow borrow) { borrow(_ref.nativeObject); } void dispose() { _ref.dispose(); } @override int get hashCode => colorFilter.hashCode; @override bool operator ==(Object other) { if (runtimeType != other.runtimeType) { return false; } return other is CkColorFilterImageFilter && other.colorFilter == colorFilter; } @override String toString() => colorFilter.toString(); } class _CkBlurImageFilter extends CkImageFilter { _CkBlurImageFilter( {required this.sigmaX, required this.sigmaY, required this.tileMode}) : super._() { /// Return the identity matrix when both sigmaX and sigmaY are 0. Replicates /// effect of applying no filter final SkImageFilter skImageFilter; if (sigmaX == 0 && sigmaY == 0) { skImageFilter = canvasKit.ImageFilter.MakeMatrixTransform( toSkMatrixFromFloat32(Matrix4.identity().storage), toSkFilterOptions(ui.FilterQuality.none), null ); } else { skImageFilter = canvasKit.ImageFilter.MakeBlur( sigmaX, sigmaY, toSkTileMode(tileMode), null, ); } _ref = UniqueRef<SkImageFilter>(this, skImageFilter, 'ImageFilter.blur'); } final double sigmaX; final double sigmaY; final ui.TileMode tileMode; late final UniqueRef<SkImageFilter> _ref; @override void imageFilter(SkImageFilterBorrow borrow) { borrow(_ref.nativeObject); } @override bool operator ==(Object other) { if (runtimeType != other.runtimeType) { return false; } return other is _CkBlurImageFilter && other.sigmaX == sigmaX && other.sigmaY == sigmaY && other.tileMode == tileMode; } @override int get hashCode => Object.hash(sigmaX, sigmaY, tileMode); @override String toString() { return 'ImageFilter.blur($sigmaX, $sigmaY, ${tileModeString(tileMode)})'; } } class _CkMatrixImageFilter extends CkImageFilter { _CkMatrixImageFilter( {required Float64List matrix, required this.filterQuality}) : matrix = Float64List.fromList(matrix), _transform = Matrix4.fromFloat32List(toMatrix32(matrix)), super._() { final SkImageFilter skImageFilter = canvasKit.ImageFilter.MakeMatrixTransform( toSkMatrixFromFloat64(matrix), toSkFilterOptions(filterQuality), null, ); _ref = UniqueRef<SkImageFilter>(this, skImageFilter, 'ImageFilter.matrix'); } final Float64List matrix; final ui.FilterQuality filterQuality; final Matrix4 _transform; late final UniqueRef<SkImageFilter> _ref; @override void imageFilter(SkImageFilterBorrow borrow) { borrow(_ref.nativeObject); } @override bool operator ==(Object other) { if (other.runtimeType != runtimeType) { return false; } return other is _CkMatrixImageFilter && other.filterQuality == filterQuality && listEquals<double>(other.matrix, matrix); } @override int get hashCode => Object.hash(filterQuality, Object.hashAll(matrix)); @override String toString() => 'ImageFilter.matrix($matrix, $filterQuality)'; @override Matrix4 get transform => _transform; } class _CkComposeImageFilter extends CkImageFilter { _CkComposeImageFilter({required this.outer, required this.inner}) : super._() { outer.imageFilter((SkImageFilter outerFilter) { inner.imageFilter((SkImageFilter innerFilter) { final SkImageFilter skImageFilter = canvasKit.ImageFilter.MakeCompose( outerFilter, innerFilter, ); _ref = UniqueRef<SkImageFilter>( this, skImageFilter, 'ImageFilter.compose'); }); }); } final CkImageFilter outer; final CkImageFilter inner; late final UniqueRef<SkImageFilter> _ref; @override void imageFilter(SkImageFilterBorrow borrow) { borrow(_ref.nativeObject); } @override bool operator ==(Object other) { if (runtimeType != other.runtimeType) { return false; } return other is _CkComposeImageFilter && other.outer == outer && other.inner == inner; } @override int get hashCode => Object.hash(outer, inner); @override String toString() { return 'ImageFilter.compose($outer, $inner)'; } }
engine/lib/web_ui/lib/src/engine/canvaskit/image_filter.dart/0
{'file_path': 'engine/lib/web_ui/lib/src/engine/canvaskit/image_filter.dart', 'repo_id': 'engine', 'token_count': 2253}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:typed_data'; // TODO(hterkelsen): Delete this once the slots change lands? class PlatformMessage { PlatformMessage(this.channel, this.data, this.response); final String channel; final ByteData data; final PlatformMessageResponse response; } class PlatformMessageResponse { void complete(Uint8List data) {} void completeEmpty() {} }
engine/lib/web_ui/lib/src/engine/canvaskit/platform_message.dart/0
{'file_path': 'engine/lib/web_ui/lib/src/engine/canvaskit/platform_message.dart', 'repo_id': 'engine', 'token_count': 145}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import '../engine.dart' show buildMode, renderer; import 'browser_detection.dart'; import 'configuration.dart'; import 'dom.dart'; import 'window.dart'; /// Controls the placement and lifecycle of a Flutter view on the web page. /// /// Manages several top-level elements that host Flutter-generated content, /// including: /// /// - [flutterViewElement], the root element of a Flutter view. /// - [glassPaneElement], the glass pane element that hosts the shadowDOM. /// - [glassPaneShadow], the shadow root used to isolate Flutter-rendered /// content from the surrounding page content, including from the platform /// views. /// - [sceneElement], the element that hosts Flutter layers and pictures, and /// projects platform views. /// - [sceneHostElement], the anchor that provides a stable location in the DOM /// tree for the [sceneElement]. /// - [semanticsHostElement], hosts the ARIA-annotated semantics tree. /// /// This class is currently a singleton, but it'll possibly need to morph to have /// multiple instances in a multi-view scenario. (One ViewEmbedder per FlutterView). class FlutterViewEmbedder { /// Creates a FlutterViewEmbedder. FlutterViewEmbedder() { reset(); } /// A child element of body outside the shadowroot that hosts /// global resources such svg filters and clip paths when using webkit. DomElement? _resourcesHost; DomElement get _flutterViewElement => window.dom.rootElement; DomShadowRoot get _glassPaneShadow => window.dom.renderingHost; void reset() { // How was the current renderer selected? const String rendererSelection = FlutterConfiguration.flutterWebAutoDetect ? 'auto-selected' : 'requested explicitly'; // Initializes the embeddingStrategy so it can host a single-view Flutter app. window.embeddingStrategy.initialize( hostElementAttributes: <String, String>{ 'flt-renderer': '${renderer.rendererTag} ($rendererSelection)', 'flt-build-mode': buildMode, // TODO(mdebbar): Disable spellcheck until changes in the framework and // engine are complete. 'spellcheck': 'false', }, ); renderer.reset(this); } /// Add an element as a global resource to be referenced by CSS. /// /// This call create a global resource host element on demand and either /// place it as first element of body(webkit), or as a child of /// glass pane element for other browsers to make sure url resolution /// works correctly when content is inside a shadow root. void addResource(DomElement element) { final bool isWebKit = browserEngine == BrowserEngine.webkit; if (_resourcesHost == null) { final DomElement resourcesHost = domDocument .createElement('flt-svg-filters') ..style.visibility = 'hidden'; if (isWebKit) { // The resourcesHost *must* be a sibling of the glassPaneElement. window.embeddingStrategy.attachResourcesHost(resourcesHost, nextTo: _flutterViewElement); } else { _glassPaneShadow.insertBefore(resourcesHost, _glassPaneShadow.firstChild); } _resourcesHost = resourcesHost; } _resourcesHost!.append(element); } /// Removes a global resource element. void removeResource(DomElement? element) { if (element == null) { return; } assert(element.parentNode == _resourcesHost); element.remove(); } } /// The embedder singleton. /// /// [ensureFlutterViewEmbedderInitialized] must be called prior to calling this /// getter. FlutterViewEmbedder get flutterViewEmbedder { final FlutterViewEmbedder? embedder = _flutterViewEmbedder; assert(() { if (embedder == null) { throw StateError( 'FlutterViewEmbedder not initialized. Call `ensureFlutterViewEmbedderInitialized()` ' 'prior to calling the `flutterViewEmbedder` getter.'); } return true; }()); return embedder!; } FlutterViewEmbedder? _flutterViewEmbedder; /// Initializes the [FlutterViewEmbedder], if it's not already initialized. FlutterViewEmbedder ensureFlutterViewEmbedderInitialized() { // FlutterViewEmbedder needs the implicit view to be initialized because it // uses some of its members e.g. `embeddingStrategy`, `onResize`. ensureImplicitViewInitialized(); return _flutterViewEmbedder ??= FlutterViewEmbedder(); }
engine/lib/web_ui/lib/src/engine/embedder.dart/0
{'file_path': 'engine/lib/web_ui/lib/src/engine/embedder.dart', 'repo_id': 'engine', 'token_count': 1420}
// 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:ui/ui.dart' as ui; import '../dom.dart'; import '../util.dart'; import '../vector_math.dart'; import 'surface.dart'; /// A surface that makes its children transparent. class PersistedOpacity extends PersistedContainerSurface implements ui.OpacityEngineLayer { PersistedOpacity(PersistedOpacity? super.oldLayer, this.alpha, this.offset); final int alpha; final ui.Offset offset; @override void recomputeTransformAndClip() { transform = parent!.transform; final double dx = offset.dx; final double dy = offset.dy; if (dx != 0.0 || dy != 0.0) { transform = transform!.clone(); transform!.translate(dx, dy); } projectedClip = null; } /// Cached inverse of transform on this node. Unlike transform, this /// Matrix only contains local transform (not chain multiplied since root). Matrix4? _localTransformInverse; @override Matrix4 get localTransformInverse => _localTransformInverse ??= Matrix4.translationValues(-offset.dx, -offset.dy, 0); @override DomElement createElement() { final DomElement element = domDocument.createElement('flt-opacity'); setElementStyle(element, 'position', 'absolute'); setElementStyle(element, 'transform-origin', '0 0 0'); return element; } @override void apply() { final DomElement element = rootElement!; setElementStyle(element, 'opacity', '${alpha / 255}'); element.style.transform = 'translate(${offset.dx}px, ${offset.dy}px)'; } @override void update(PersistedOpacity oldSurface) { super.update(oldSurface); if (alpha != oldSurface.alpha || offset != oldSurface.offset) { apply(); } } }
engine/lib/web_ui/lib/src/engine/html/opacity.dart/0
{'file_path': 'engine/lib/web_ui/lib/src/engine/html/opacity.dart', 'repo_id': 'engine', 'token_count': 602}
// 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:math' as math; import 'dart:typed_data'; import 'package:ui/ui.dart' as ui; import '../browser_detection.dart'; import '../dom.dart'; import '../safe_browser_api.dart'; import '../util.dart'; import '../vector_math.dart'; import 'painting.dart'; import 'shaders/image_shader.dart'; import 'shaders/normalized_gradient.dart'; import 'shaders/shader_builder.dart'; import 'shaders/vertex_shaders.dart'; GlRenderer? glRenderer; class SurfaceVertices implements ui.Vertices { SurfaceVertices( this.mode, List<ui.Offset> positions, { List<ui.Color>? colors, List<int>? indices, }) : colors = colors != null ? _int32ListFromColors(colors) : null, indices = indices != null ? Uint16List.fromList(indices) : null, positions = offsetListToFloat32List(positions) { initWebGl(); } SurfaceVertices.raw( this.mode, this.positions, { this.colors, this.indices, }) { initWebGl(); } final ui.VertexMode mode; final Float32List positions; final Int32List? colors; final Uint16List? indices; static Int32List _int32ListFromColors(List<ui.Color> colors) { final Int32List list = Int32List(colors.length); final int len = colors.length; for (int i = 0; i < len; i++) { list[i] = colors[i].value; } return list; } bool _disposed = false; @override void dispose() { _disposed = true; } @override bool get debugDisposed { bool? result; assert(() { result = _disposed; return true; }()); if (result != null) { return result!; } throw StateError('Vertices.debugDisposed is only available when asserts are enabled.'); } } /// Lazily initializes web gl. /// /// Used to treeshake WebGlRenderer when user doesn't create Vertices object /// to use the API. void initWebGl() { glRenderer ??= _WebGlRenderer(); } abstract class GlRenderer { void drawVertices( DomCanvasRenderingContext2D? context, int canvasWidthInPixels, int canvasHeightInPixels, Matrix4 transform, SurfaceVertices vertices, ui.BlendMode blendMode, SurfacePaintData paint); Object? drawRect(ui.Rect targetRect, GlContext gl, GlProgram glProgram, NormalizedGradient gradient, int widthInPixels, int heightInPixels); String drawRectToImageUrl( ui.Rect targetRect, GlContext gl, GlProgram glProgram, NormalizedGradient gradient, int widthInPixels, int heightInPixels); void drawHairline(DomCanvasRenderingContext2D? ctx, Float32List positions); } /// Treeshakeable backend for rendering webgl on canvas. /// /// This class gets instantiated on demand by Vertices constructor. For apps /// that don't use Vertices WebGlRenderer will be removed from release binary. class _WebGlRenderer implements GlRenderer { @override void drawVertices( DomCanvasRenderingContext2D? context, int canvasWidthInPixels, int canvasHeightInPixels, Matrix4 transform, SurfaceVertices vertices, ui.BlendMode blendMode, SurfacePaintData paint) { // Compute bounds of vertices. final Float32List positions = vertices.positions; final ui.Rect bounds = _computeVerticesBounds(positions, transform); final double minValueX = bounds.left; final double minValueY = bounds.top; final double maxValueX = bounds.right; final double maxValueY = bounds.bottom; double offsetX = 0; double offsetY = 0; int widthInPixels = canvasWidthInPixels; int heightInPixels = canvasHeightInPixels; // If vertices fall outside the bitmap area, cull. if (maxValueX < 0 || maxValueY < 0) { return; } if (minValueX > widthInPixels || minValueY > heightInPixels) { return; } // If Vertices are is smaller than hosting canvas, allocate minimal // offscreen canvas to reduce readPixels data size. if ((maxValueX - minValueX) < widthInPixels && (maxValueY - minValueY) < heightInPixels) { widthInPixels = maxValueX.ceil() - minValueX.floor(); heightInPixels = maxValueY.ceil() - minValueY.floor(); offsetX = minValueX.floor().toDouble(); offsetY = minValueY.floor().toDouble(); } if (widthInPixels == 0 || heightInPixels == 0) { return; } final bool isWebGl2 = webGLVersion == WebGLVersion.webgl2; final EngineImageShader? imageShader = paint.shader == null ? null : paint.shader! as EngineImageShader; final String vertexShader = imageShader == null ? VertexShaders.writeBaseVertexShader() : VertexShaders.writeTextureVertexShader(); final String fragmentShader = imageShader == null ? _writeVerticesFragmentShader() : FragmentShaders.writeTextureFragmentShader( isWebGl2, imageShader.tileModeX, imageShader.tileModeY); final GlContext gl = GlContextCache.createGlContext(widthInPixels, heightInPixels)!; final GlProgram glProgram = gl.cacheProgram(vertexShader, fragmentShader); gl.useProgram(glProgram); final Object positionAttributeLocation = gl.getAttributeLocation(glProgram.program, 'position'); setupVertexTransforms(gl, glProgram, offsetX, offsetY, widthInPixels.toDouble(), heightInPixels.toDouble(), transform); if (imageShader != null) { /// To map from vertex position to texture coordinate in 0..1 range, /// we setup scalar to be used in vertex shader. setupTextureTransform( gl, glProgram, 0.0, 0.0, 1.0 / imageShader.image.width.toDouble(), 1.0 / imageShader.image.height.toDouble()); } // Setup geometry. // // Create buffer for vertex coordinates. final Object positionsBuffer = gl.createBuffer()!; Object? vao; if (imageShader != null) { if (isWebGl2) { // Create a vertex array object. vao = gl.createVertexArray(); // Set vertex array object as active one. gl.bindVertexArray(vao!); } } // Turn on position attribute. gl.enableVertexAttribArray(positionAttributeLocation); // Bind buffer as position buffer and transfer data. gl.bindArrayBuffer(positionsBuffer); bufferVertexData(gl, positions, 1.0); // Setup data format for attribute. vertexAttribPointerGlContext( gl.glContext, positionAttributeLocation, 2, gl.kFloat, false, 0, 0, ); final int vertexCount = positions.length ~/ 2; Object? texture; if (imageShader == null) { // Setup color buffer. final Object? colorsBuffer = gl.createBuffer(); gl.bindArrayBuffer(colorsBuffer); // Buffer kBGRA_8888. if (vertices.colors == null) { final Uint32List vertexColors = Uint32List(vertexCount); for (int i = 0; i < vertexCount; i++) { vertexColors[i] = paint.color; } gl.bufferData(vertexColors, gl.kStaticDraw); } else { gl.bufferData(vertices.colors, gl.kStaticDraw); } final Object colorLoc = gl.getAttributeLocation(glProgram.program, 'color'); vertexAttribPointerGlContext( gl.glContext, colorLoc, 4, gl.kUnsignedByte, true, 0, 0, ); gl.enableVertexAttribArray(colorLoc); } else { // Copy image it to the texture. texture = gl.createTexture(); // Texture units are a global array of references to the textures. // By setting activeTexture, we associate the bound texture to a unit. // Every time we call a texture function such as texImage2D with a target // like TEXTURE_2D, it looks up texture by using the currently active // unit. // In our case we have a single texture unit 0. gl.activeTexture(gl.kTexture0); gl.bindTexture(gl.kTexture2D, texture); gl.texImage2D(gl.kTexture2D, 0, gl.kRGBA, gl.kRGBA, gl.kUnsignedByte, imageShader.image.imgElement); if (isWebGl2) { // Texture REPEAT and MIRROR is only supported in WebGL 2, for // WebGL 1.0 we let shader compute correct uv coordinates. gl.texParameteri(gl.kTexture2D, gl.kTextureWrapS, tileModeToGlWrapping(gl, imageShader.tileModeX)); gl.texParameteri(gl.kTexture2D, gl.kTextureWrapT, tileModeToGlWrapping(gl, imageShader.tileModeY)); // Mipmapping saves your texture in different resolutions // so the graphics card can choose which resolution is optimal // without artifacts. gl.generateMipmap(gl.kTexture2D); } else { // For webgl1, if a texture is not mipmap complete, then the return // value of a texel fetch is (0, 0, 0, 1), so we have to set // minifying function to filter. // See https://www.khronos.org/registry/webgl/specs/1.0.0/#5.13.8. gl.texParameteri(gl.kTexture2D, gl.kTextureWrapS, gl.kClampToEdge); gl.texParameteri(gl.kTexture2D, gl.kTextureWrapT, gl.kClampToEdge); gl.texParameteri(gl.kTexture2D, gl.kTextureMinFilter, gl.kLinear); } } // Finally render triangles. gl.clear(); final Uint16List? indices = vertices.indices; if (indices == null) { gl.drawTriangles(vertexCount, vertices.mode); } else { /// If indices are specified to use shared vertices to reduce vertex /// data transfer, use drawElements to map from vertex indices to /// triangles. final Object? indexBuffer = gl.createBuffer(); gl.bindElementArrayBuffer(indexBuffer); gl.bufferElementData(indices, gl.kStaticDraw); gl.drawElements(gl.kTriangles, indices.length, gl.kUnsignedShort); } if (vao != null) { gl.unbindVertexArray(); } context!.save(); context.resetTransform(); gl.drawImage(context, offsetX, offsetY); context.restore(); } /// Renders a rectangle using given program into an image resource. /// /// Browsers that support OffscreenCanvas and the transferToImageBitmap api /// will return ImageBitmap, otherwise will return CanvasElement. @override Object? drawRect(ui.Rect targetRect, GlContext gl, GlProgram glProgram, NormalizedGradient gradient, int widthInPixels, int heightInPixels) { drawRectToGl( targetRect, gl, glProgram, gradient, widthInPixels, heightInPixels); final Object? image = gl.readPatternData(gradient.isOpaque); gl.bindArrayBuffer(null); gl.bindElementArrayBuffer(null); return image; } /// Renders a rectangle using given program into an image resource and returns /// url. @override String drawRectToImageUrl( ui.Rect targetRect, GlContext gl, GlProgram glProgram, NormalizedGradient gradient, int widthInPixels, int heightInPixels) { drawRectToGl( targetRect, gl, glProgram, gradient, widthInPixels, heightInPixels); final String imageUrl = gl.toImageUrl(); // Cleanup buffers. gl.bindArrayBuffer(null); gl.bindElementArrayBuffer(null); return imageUrl; } /// Renders a rectangle using given program into [GlContext]. /// /// Caller has to cleanup gl array and element array buffers. void drawRectToGl(ui.Rect targetRect, GlContext gl, GlProgram glProgram, NormalizedGradient gradient, int widthInPixels, int heightInPixels) { // Setup rectangle coordinates. final double left = targetRect.left; final double top = targetRect.top; final double right = targetRect.right; final double bottom = targetRect.bottom; // Form 2 triangles for rectangle. final Float32List vertices = Float32List(8); vertices[0] = left; vertices[1] = top; vertices[2] = right; vertices[3] = top; vertices[4] = right; vertices[5] = bottom; vertices[6] = left; vertices[7] = bottom; final Object transformUniform = gl.getUniformLocation(glProgram.program, 'u_ctransform'); gl.setUniformMatrix4fv(transformUniform, false, Matrix4.identity().storage); // Set uniform to scale 0..width/height pixels coordinates to -1..1 // clipspace range and flip the Y axis. final Object resolution = gl.getUniformLocation(glProgram.program, 'u_scale'); gl.setUniform4f(resolution, 2.0 / widthInPixels.toDouble(), -2.0 / heightInPixels.toDouble(), 1, 1); final Object shift = gl.getUniformLocation(glProgram.program, 'u_shift'); gl.setUniform4f(shift, -1, 1, 0, 0); // Setup geometry. final Object positionsBuffer = gl.createBuffer()!; gl.bindArrayBuffer(positionsBuffer); gl.bufferData(vertices, gl.kStaticDraw); // Point an attribute to the currently bound vertex buffer object. vertexAttribPointerGlContext( gl.glContext, 0, 2, gl.kFloat, false, 0, 0, ); gl.enableVertexAttribArray(0); // Setup color buffer. final Object? colorsBuffer = gl.createBuffer(); gl.bindArrayBuffer(colorsBuffer); // Buffer kBGRA_8888. final Int32List colors = Int32List.fromList(<int>[ 0xFF00FF00, 0xFF0000FF, 0xFFFFFF00, 0xFF00FFFF, ]); gl.bufferData(colors, gl.kStaticDraw); vertexAttribPointerGlContext( gl.glContext, 1, 4, gl.kUnsignedByte, true, 0, 0, ); gl.enableVertexAttribArray(1); final Object? indexBuffer = gl.createBuffer(); gl.bindElementArrayBuffer(indexBuffer); gl.bufferElementData(VertexShaders.vertexIndicesForRect, gl.kStaticDraw); if (gl.containsUniform(glProgram.program, 'u_resolution')) { final Object uRes = gl.getUniformLocation(glProgram.program, 'u_resolution'); gl.setUniform2f( uRes, widthInPixels.toDouble(), heightInPixels.toDouble()); } gl.clear(); gl.viewport(0, 0, widthInPixels.toDouble(), heightInPixels.toDouble()); gl.drawElements( gl.kTriangles, VertexShaders.vertexIndicesForRect.length, gl.kUnsignedShort); } /// This fragment shader enables Int32List of colors to be passed directly /// to gl context buffer for rendering by decoding RGBA8888. /// #version 300 es /// precision mediump float; /// in vec4 vColor; /// out vec4 fragColor; /// void main() { /// fragColor = vColor; /// } String _writeVerticesFragmentShader() { final ShaderBuilder builder = ShaderBuilder.fragment(webGLVersion); builder.floatPrecision = ShaderPrecision.kMedium; builder.addIn(ShaderType.kVec4, name: 'v_color'); final ShaderMethod method = builder.addMethod('main'); method.addStatement('${builder.fragmentColor.name} = v_color;'); return builder.build(); } @override void drawHairline( DomCanvasRenderingContext2D? ctx, Float32List positions) { final int pointCount = positions.length ~/ 2; ctx!.lineWidth = 1.0; ctx.beginPath(); final int len = pointCount * 2; for (int i = 0; i < len;) { for (int triangleVertexIndex = 0; triangleVertexIndex < 3; triangleVertexIndex++, i += 2) { final double dx = positions[i]; final double dy = positions[i + 1]; switch (triangleVertexIndex) { case 0: ctx.moveTo(dx, dy); case 1: ctx.lineTo(dx, dy); case 2: ctx.lineTo(dx, dy); ctx.closePath(); ctx.stroke(); } } } } } ui.Rect _computeVerticesBounds(Float32List positions, Matrix4 transform) { double minValueX, maxValueX, minValueY, maxValueY; minValueX = maxValueX = positions[0]; minValueY = maxValueY = positions[1]; final int len = positions.length; for (int i = 2; i < len; i += 2) { final double x = positions[i]; final double y = positions[i + 1]; if (x.isNaN || y.isNaN) { // Follows skia implementation that sets bounds to empty // and aborts. return ui.Rect.zero; } minValueX = math.min(minValueX, x); maxValueX = math.max(maxValueX, x); minValueY = math.min(minValueY, y); maxValueY = math.max(maxValueY, y); } return _transformBounds( transform, minValueX, minValueY, maxValueX, maxValueY); } ui.Rect _transformBounds( Matrix4 transform, double left, double top, double right, double bottom) { final Float32List storage = transform.storage; final double m0 = storage[0]; final double m1 = storage[1]; final double m4 = storage[4]; final double m5 = storage[5]; final double m12 = storage[12]; final double m13 = storage[13]; final double x0 = (m0 * left) + (m4 * top) + m12; final double y0 = (m1 * left) + (m5 * top) + m13; final double x1 = (m0 * right) + (m4 * top) + m12; final double y1 = (m1 * right) + (m5 * top) + m13; final double x2 = (m0 * right) + (m4 * bottom) + m12; final double y2 = (m1 * right) + (m5 * bottom) + m13; final double x3 = (m0 * left) + (m4 * bottom) + m12; final double y3 = (m1 * left) + (m5 * bottom) + m13; return ui.Rect.fromLTRB( math.min(x0, math.min(x1, math.min(x2, x3))), math.min(y0, math.min(y1, math.min(y2, y3))), math.max(x0, math.max(x1, math.max(x2, x3))), math.max(y0, math.max(y1, math.max(y2, y3)))); } /// Converts from [VertexMode] triangleFan and triangleStrip to triangles. Float32List convertVertexPositions(ui.VertexMode mode, Float32List positions) { assert(mode != ui.VertexMode.triangles); if (mode == ui.VertexMode.triangleFan) { final int coordinateCount = positions.length ~/ 2; final int triangleCount = coordinateCount - 2; final Float32List triangleList = Float32List(triangleCount * 3 * 2); final double centerX = positions[0]; final double centerY = positions[1]; int destIndex = 0; int positionIndex = 2; for (int triangleIndex = 0; triangleIndex < triangleCount; triangleIndex++, positionIndex += 2) { triangleList[destIndex++] = centerX; triangleList[destIndex++] = centerY; triangleList[destIndex++] = positions[positionIndex]; triangleList[destIndex++] = positions[positionIndex + 1]; triangleList[destIndex++] = positions[positionIndex + 2]; triangleList[destIndex++] = positions[positionIndex + 3]; } return triangleList; } else { assert(mode == ui.VertexMode.triangleStrip); // Set of connected triangles. Each triangle shares 2 last vertices. final int vertexCount = positions.length ~/ 2; final int triangleCount = vertexCount - 2; double x0 = positions[0]; double y0 = positions[1]; double x1 = positions[2]; double y1 = positions[3]; final Float32List triangleList = Float32List(triangleCount * 3 * 2); int destIndex = 0; for (int i = 0, positionIndex = 4; i < triangleCount; i++) { final double x2 = positions[positionIndex++]; final double y2 = positions[positionIndex++]; triangleList[destIndex++] = x0; triangleList[destIndex++] = y0; triangleList[destIndex++] = x1; triangleList[destIndex++] = y1; triangleList[destIndex++] = x2; triangleList[destIndex++] = y2; x0 = x1; y0 = y1; x1 = x2; y1 = y2; } return triangleList; } }
engine/lib/web_ui/lib/src/engine/html/render_vertices.dart/0
{'file_path': 'engine/lib/web_ui/lib/src/engine/html/render_vertices.dart', 'repo_id': 'engine', 'token_count': 7563}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @JS() library js_app; import 'dart:js_interop'; import 'package:ui/src/engine.dart'; /// The JS bindings for the configuration object passed to [FlutterApp.addView]. @JS() @anonymous @staticInterop class JsFlutterViewOptions { external factory JsFlutterViewOptions(); } /// The attributes of the [JsFlutterViewOptions] object. extension JsFlutterViewOptionsExtension on JsFlutterViewOptions { @JS('hostElement') external DomElement? get _hostElement; DomElement get hostElement { assert (_hostElement != null, '`hostElement` passed to addView cannot be null.'); return _hostElement!; } external JSAny? get initialData; } /// The public JS API of a running Flutter Web App. @JS() @anonymous @staticInterop abstract class FlutterApp { factory FlutterApp({ required AddFlutterViewFn addView, required RemoveFlutterViewFn removeView, }) => FlutterApp._( addView: ((JsFlutterViewOptions options) => futureToPromise(addView(options) as Future<JSAny>)).toJS, removeView: ((int id) => futureToPromise(removeView(id) as Future<JSObject?>)).toJS, ); external factory FlutterApp._({ required JSFunction addView, required JSFunction removeView, }); } /// Typedef for the function that adds a new view to the app. /// /// Returns the ID of the newly created view. typedef AddFlutterViewFn = Future<int> Function(JsFlutterViewOptions); /// Typedef for the function that removes a view from the app. /// /// Returns the configuration used to create the view. typedef RemoveFlutterViewFn = Future<JsFlutterViewOptions?> Function(int);
engine/lib/web_ui/lib/src/engine/js_interop/js_app.dart/0
{'file_path': 'engine/lib/web_ui/lib/src/engine/js_interop/js_app.dart', 'repo_id': 'engine', 'token_count': 583}
// 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:ui/src/engine.dart'; import 'package:ui/ui.dart' as ui; const String kCanvasContainerTag = 'flt-canvas-container'; // This is an interface that renders a `ScenePicture` as a `DomImageBitmap`. // It is optionally asynchronous. It is required for the `EngineSceneView` to // composite pictures into the canvases in the DOM tree it builds. abstract class PictureRenderer { FutureOr<DomImageBitmap> renderPicture(ScenePicture picture); } class _SceneRender { _SceneRender(this.scene, this._completer) { scene.beginRender(); } final EngineScene scene; final Completer<void> _completer; void done() { scene.endRender(); _completer.complete(); } } // This class builds a DOM tree that composites an `EngineScene`. class EngineSceneView { factory EngineSceneView(PictureRenderer pictureRenderer) { final DomElement sceneElement = createDomElement('flt-scene'); return EngineSceneView._(pictureRenderer, sceneElement); } EngineSceneView._(this.pictureRenderer, this.sceneElement); final PictureRenderer pictureRenderer; final DomElement sceneElement; List<SliceContainer> containers = <SliceContainer>[]; _SceneRender? _currentRender; _SceneRender? _nextRender; Future<void> renderScene(EngineScene scene) { if (_currentRender != null) { // If a scene is already queued up, drop it and queue this one up instead // so that the scene view always displays the most recently requested scene. _nextRender?.done(); final Completer<void> completer = Completer<void>(); _nextRender = _SceneRender(scene, completer); return completer.future; } final Completer<void> completer = Completer<void>(); _currentRender = _SceneRender(scene, completer); _kickRenderLoop(); return completer.future; } Future<void> _kickRenderLoop() async { final _SceneRender current = _currentRender!; await _renderScene(current.scene); current.done(); _currentRender = _nextRender; _nextRender = null; if (_currentRender == null) { return; } else { return _kickRenderLoop(); } } Future<void> _renderScene(EngineScene scene) async { final List<LayerSlice> slices = scene.rootLayer.slices; final Iterable<Future<DomImageBitmap?>> renderFutures = slices.map( (LayerSlice slice) async => switch (slice) { PlatformViewSlice() => null, PictureSlice() => pictureRenderer.renderPicture(slice.picture), } ); final List<DomImageBitmap?> renderedBitmaps = await Future.wait(renderFutures); final List<SliceContainer?> reusableContainers = List<SliceContainer?>.from(containers); final List<SliceContainer> newContainers = <SliceContainer>[]; for (int i = 0; i < slices.length; i++) { final LayerSlice slice = slices[i]; switch (slice) { case PictureSlice(): PictureSliceContainer? container; for (int j = 0; j < reusableContainers.length; j++) { final SliceContainer? candidate = reusableContainers[j]; if (candidate is PictureSliceContainer) { container = candidate; reusableContainers[j] = null; break; } } if (container != null) { container.bounds = slice.picture.cullRect; } else { container = PictureSliceContainer(slice.picture.cullRect); } container.updateContents(); container.renderBitmap(renderedBitmaps[i]!); newContainers.add(container); case PlatformViewSlice(): for (final PlatformView view in slice.views) { // TODO(harryterkelsen): Inject the FlutterView instance from `renderScene`, // instead of using `EnginePlatformDispatcher...implicitView` directly, // or make the FlutterView "register" like in canvaskit. // Ensure the platform view contents are injected in the DOM. EnginePlatformDispatcher.instance.implicitView?.dom.injectPlatformView(view.viewId); // Attempt to reuse a container for the existing view PlatformViewContainer? container; for (int j = 0; j < reusableContainers.length; j++) { final SliceContainer? candidate = reusableContainers[j]; if (candidate is PlatformViewContainer && candidate.viewId == view.viewId) { container = candidate; reusableContainers[j] = null; break; } } container ??= PlatformViewContainer(view.viewId); container.size = view.size; container.styling = view.styling; container.updateContents(); newContainers.add(container); } } } containers = newContainers; DomElement? currentElement = sceneElement.firstElementChild; for (final SliceContainer container in containers) { if (currentElement == null) { sceneElement.appendChild(container.container); } else if (currentElement == container.container) { currentElement = currentElement.nextElementSibling; } else { sceneElement.insertBefore(container.container, currentElement); } } // Remove any other unused containers while (currentElement != null) { final DomElement? sibling = currentElement.nextElementSibling; sceneElement.removeChild(currentElement); currentElement = sibling; } } } sealed class SliceContainer { DomElement get container; void updateContents(); } final class PictureSliceContainer extends SliceContainer { factory PictureSliceContainer(ui.Rect bounds) { final DomElement container = domDocument.createElement(kCanvasContainerTag); final DomCanvasElement canvas = createDomCanvasElement( width: bounds.width.toInt(), height: bounds.height.toInt() ); container.appendChild(canvas); return PictureSliceContainer._(bounds, container, canvas); } PictureSliceContainer._(this._bounds, this.container, this.canvas); ui.Rect _bounds; bool _dirty = true; ui.Rect get bounds => _bounds; set bounds(ui.Rect bounds) { if (_bounds != bounds) { _bounds = bounds; _dirty = true; } } @override void updateContents() { if (_dirty) { _dirty = false; final ui.Rect roundedOutBounds = ui.Rect.fromLTRB( bounds.left.floorToDouble(), bounds.top.floorToDouble(), bounds.right.ceilToDouble(), bounds.bottom.ceilToDouble() ); final DomCSSStyleDeclaration style = canvas.style; final double devicePixelRatio = EngineFlutterDisplay.instance.devicePixelRatio; final double logicalWidth = roundedOutBounds.width / devicePixelRatio; final double logicalHeight = roundedOutBounds.height / devicePixelRatio; final double logicalLeft = roundedOutBounds.left / devicePixelRatio; final double logicalTop = roundedOutBounds.top / devicePixelRatio; style.width = '${logicalWidth}px'; style.height = '${logicalHeight}px'; style.position = 'absolute'; style.left = '${logicalLeft}px'; style.top = '${logicalTop}px'; canvas.width = roundedOutBounds.width.ceilToDouble(); canvas.height = roundedOutBounds.height.ceilToDouble(); } } void renderBitmap(DomImageBitmap bitmap) { final DomCanvasRenderingContextBitmapRenderer ctx = canvas.contextBitmapRenderer; ctx.transferFromImageBitmap(bitmap); } @override final DomElement container; final DomCanvasElement canvas; } final class PlatformViewContainer extends SliceContainer { PlatformViewContainer(this.viewId) : container = createPlatformViewSlot(viewId); final int viewId; PlatformViewStyling? _styling; ui.Size? _size; bool _dirty = false; @override final DomElement container; set styling(PlatformViewStyling styling) { if (_styling != styling) { _styling = styling; _dirty = true; } } set size(ui.Size size) { if (_size != size) { _size = size; _dirty = true; } } @override void updateContents() { assert(_styling != null); assert(_size != null); if (_dirty) { final DomCSSStyleDeclaration style = container.style; final double devicePixelRatio = EngineFlutterDisplay.instance.devicePixelRatio; final double logicalWidth = _size!.width / devicePixelRatio; final double logicalHeight = _size!.height / devicePixelRatio; style.width = '${logicalWidth}px'; style.height = '${logicalHeight}px'; style.position = 'absolute'; final ui.Offset? offset = _styling!.position.offset; final double logicalLeft = (offset?.dx ?? 0) / devicePixelRatio; final double logicalTop = (offset?.dy ?? 0) / devicePixelRatio; style.left = '${logicalLeft}px'; style.top = '${logicalTop}px'; final Matrix4? transform = _styling!.position.transform; style.transform = transform != null ? float64ListToCssTransform3d(transform.storage) : ''; style.opacity = _styling!.opacity != 1.0 ? '${_styling!.opacity}' : ''; // TODO(jacksongardner): Implement clip styling for platform views _dirty = false; } } }
engine/lib/web_ui/lib/src/engine/scene_view.dart/0
{'file_path': 'engine/lib/web_ui/lib/src/engine/scene_view.dart', 'repo_id': 'engine', 'token_count': 3471}