code
stringlengths
8
3.25M
repository
stringlengths
15
175
metadata
stringlengths
66
249
import 'dart:async'; import 'package:bloc/bloc.dart'; import 'package:equatable/equatable.dart'; abstract class MyEvent extends Equatable { @override List<Object> get props => []; } class Event extends MyEvent { @override String toString() => 'Event'; } abstract class MyState extends Equatable { @override List<Object> get props => []; } class InitialState extends MyState { @override String toString() => 'InitialState'; } class Loading extends MyState { @override String toString() => 'Loading'; } class Success extends MyState { @override String toString() => 'Success'; } class Failure extends MyState { @override String toString() => 'Failure'; } class MyBloc extends Bloc<MyEvent, MyState> { @override MyState get initialState => InitialState(); @override void onEvent(MyEvent event) { super.onEvent(event); print('$event'); } @override void onTransition(Transition<MyEvent, MyState> transition) { print('$transition'); super.onTransition(transition); } @override void onError(Object error, StackTrace stacktrace) { super.onError(error, stacktrace); print('$error, $stacktrace'); } @override Stream<MyState> mapEventToState( MyEvent event, ) async* { if (event is Event) { yield Loading(); try { await _foo(); yield Success(); } catch (e) { yield Failure(); } } } Future<String> _foo() async { throw Exception('oops'); } } void main() async { MyBloc bloc = MyBloc(); bloc.add(Event()); await Future.delayed(Duration(seconds: 1)); bloc.add(Event()); }
dartdevc_exception_bug/lib/main.dart/0
{'file_path': 'dartdevc_exception_bug/lib/main.dart', 'repo_id': 'dartdevc_exception_bug', 'token_count': 588}
import 'package:analyzer/dart/ast/ast.dart'; import 'package:dartdoc_json/src/combinators.dart'; import 'package:dartdoc_json/src/utils.dart'; Map<String, dynamic> serializeExportDirective(ExportDirective export_) { final shows = serializeCombinators<ShowCombinator>(export_.combinators); final hides = serializeCombinators<HideCombinator>(export_.combinators); return filterMap(<String, dynamic>{ 'kind': 'export', 'uri': export_.uri.stringValue, 'show': shows.isEmpty ? null : shows, 'hide': hides.isEmpty ? null : hides, }); }
dartdoc_json/lib/src/export_directive.dart/0
{'file_path': 'dartdoc_json/lib/src/export_directive.dart', 'repo_id': 'dartdoc_json', 'token_count': 190}
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/utils.dart'; /// Converts a TopLevelVariableDeclaration into a json-compatible object. Map<String, dynamic>? serializeTopLevelVariableDeclaration( TopLevelVariableDeclaration variableDeclaration, ) { final annotations = serializeAnnotations(variableDeclaration.metadata); if (hasPrivateAnnotation(annotations)) { return null; } final variableList = variableDeclaration.variables; final names = <String>[]; for (final variable in variableList.variables) { if (variable.name.lexeme.startsWith('_')) { continue; } names.add(variable.name.lexeme); } if (names.isEmpty) { return null; } return filterMap(<String, dynamic>{ 'kind': 'variable', 'name': names.first, 'extraNames': names.length > 1 ? names.sublist(1) : null, 'type': variableList.type?.toString(), 'description': serializeComment(variableDeclaration.documentationComment), 'annotations': annotations, 'final': variableList.isFinal ? true : null, 'const': variableList.isConst ? true : null, 'late': variableList.isLate ? true : null, }); }
dartdoc_json/lib/src/top_level_variable_declaration.dart/0
{'file_path': 'dartdoc_json/lib/src/top_level_variable_declaration.dart', 'repo_id': 'dartdoc_json', 'token_count': 426}
import 'package:test/test.dart'; import 'utils.dart'; void main() { group('MethodDeclaration', () { test('simple method', () { expect( parseMethods(''' abstract class X { void foo(); } '''), [ {'kind': 'method', 'name': 'foo', 'returns': 'void'}, ], ); }); test('hidden methods', () { expect( parseMethods(''' abstract class X { void _first(); @internal void second(); @visibleForTesting void third(); } '''), isEmpty, ); }); test('template method', () { expect( parseMethods(''' abstract class X { int flame<T>(); } '''), [ { 'kind': 'method', 'name': 'flame', 'returns': 'int', 'typeParameters': [ {'name': 'T'}, ], }, ], ); }); test('method with arguments', () { expect( parseMethods(''' abstract class X { int orange(bool a, int b); } '''), [ { 'kind': 'method', 'name': 'orange', 'returns': 'int', 'parameters': { 'all': [ {'name': 'a', 'type': 'bool'}, {'name': 'b', 'type': 'int'}, ], }, }, ], ); }); test('method with doc-comment', () { expect( parseMethods(''' abstract class X { /// Absence of color void white(); } '''), [ { 'kind': 'method', 'name': 'white', 'returns': 'void', 'description': 'Absence of color\n', }, ], ); }); test('annotations on a method', () { expect( parseMethods(''' abstract class X { @mustCallSuper @protected void black(); } '''), [ { 'kind': 'method', 'name': 'black', 'returns': 'void', 'annotations': [ {'name': '@mustCallSuper'}, {'name': '@protected'}, ], }, ], ); }); test('getter/setter', () { expect( parseMethods(''' abstract class X { int get xyz => 3; set xyz(int value) {} } '''), [ { 'kind': 'getter', 'name': 'xyz', 'returns': 'int', }, { 'kind': 'setter', 'name': 'xyz', 'parameters': { 'all': [ {'name': 'value', 'type': 'int'}, ], }, }, ], ); }); test('static method', () { expect( parseMethods(''' abstract class X { static void magenta() {} } '''), [ { 'kind': 'method', 'name': 'magenta', 'returns': 'void', 'static': true, }, ], ); }); test('operator', () { expect( parseMethods(''' abstract class X { bool operator==(Object other) => false; } '''), [ { 'kind': 'method', 'name': 'operator==', 'parameters': { 'all': [ {'name': 'other', 'type': 'Object'}, ], }, 'returns': 'bool', }, ], ); }); }); } List parseMethods(String input) { final json = parseAsJson(input) as Map<String, dynamic>; return (json['members']! as List).where((dynamic record) { final kind = (record as Map<String, dynamic>)['kind'] as String; return {'method', 'getter', 'setter'}.contains(kind); }).toList(); }
dartdoc_json/test/method_declaration_test.dart/0
{'file_path': 'dartdoc_json/test/method_declaration_test.dart', 'repo_id': 'dartdoc_json', 'token_count': 2454}
part of dartx_io; extension FileSystemEntityX on FileSystemEntity { /// Gets the part of [path] after the last separator. /// ```dart /// File('path/to/foo.dart').name; // -> 'foo.dart' /// Directory('path/to').name; // -> 'to' /// ``` /// /// Trailing separators are ignored. /// ```dart /// Directory('path/to/').name; // -> 'to' /// ``` String get name => path_helper.basename(path); /// Gets the part of [path] after the last separator, and without any trailing /// file extension. /// ```dart /// File('path/to/foo.dart').nameWithoutExtension; // -> 'foo' /// ``` /// /// Trailing separators are ignored. /// ```dart /// File('path/to/foo.dart/').nameWithoutExtension; // -> 'foo' /// ``` String get nameWithoutExtension => path_helper.basenameWithoutExtension(path); /// Gets the part of [path] before the last separator. /// ```dart /// File().dirname('path/to/foo.dart'); // -> 'path/to' /// Directory('path/to').dirName; // -> 'path' /// ``` /// /// Trailing separators are ignored. /// ```dart /// Directory('path/to/').dirName; // -> 'path' /// ``` /// /// If an absolute path contains no directories, only a root, then the root /// is returned. /// ```dart /// Directory('/').dirName; // -> '/' (posix) /// Directory('c:\').dirName; // -> 'c:\' (windows) /// ``` /// /// If a relative path has no directories, then '.' is returned. /// ```dart /// Directory('foo').dirName; // -> '.' /// Directory('').dirName; // -> '.' /// ``` String get dirName => path_helper.dirname(path); /// Returns `true` if this entity is a path beneath `parent`, and `false` /// otherwise. /// ```dart /// Directory('/root/path/foo.dart').isWithin(Directory('/root/path')); // -> true /// Directory('/root/path').isWithin(Directory('/root/other')); // -> false /// Directory('/root/path').isWithin(Directory('/root/path')) // -> false /// ``` bool isWithin(Directory parent) => path_helper.isWithin(parent.path, path); ///Returns a new [File] with the `name` part changed ///```dart ///File('path/to/foo.dart').withName('bar.txt'); // -> File('path/to/bar.txt') ///File('path/to/foo').withName('bar') // -> File('path/to/bar') ///``` FileSystemEntity withName(String newName) { return File('$dirName${Platform.pathSeparator}$newName'); } ///Returns the file extension of the [path], the portion of the `name` ///from the last '.' to the end (including the '.' itself). ///```dart ///File('path/to/foo.dart').extension; // -> '.dart' ///File('path/to/foo').extension; // -> '' ///File('path.to/foo').extension; // -> '' ///File('path/to/foo.dart.js').extension; // -> '.js' ///``` ///If the filename starts with a '.', then that is not considered an ///extension. ///```Dart ///File('~/.profile').extension; // -> '' ///File('~/.notes.txt').extension; // -> '.txt' ///``` String get extension => path_helper.extension(path); }
dartx/lib/src/io/file_system_entity.dart/0
{'file_path': 'dartx/lib/src/io/file_system_entity.dart', 'repo_id': 'dartx', 'token_count': 1061}
import 'dart:math' as math; import 'package:dartx/dartx.dart'; import 'package:test/test.dart'; List<int> get _sortedList => [4, 2, 1, 3].sortedBy((it) => it); void main() { test('sort', () { expect([4, 2, 1, 3].sortedBy((it) => it), [1, 2, 3, 4]); }); group('_DelegatingIterable', () { test('any', () { expect(_sortedList.any((it) => it > 2), isTrue); }); test('cast', () { expect(_sortedList.cast<num>(), isA<Iterable<num>>()); }); test('contains', () { expect(_sortedList.contains(2), isTrue); expect(_sortedList.contains(5), isFalse); }); test('elementAt', () { expect(_sortedList.elementAt(0), 1); }); test('every', () { expect(_sortedList.every((it) => it is num), isTrue); expect(_sortedList.every((it) => it is String), isFalse); }); test('expand', () { expect(_sortedList.expand((it) => [it, it]), [1, 1, 2, 2, 3, 3, 4, 4]); }); test('first', () { expect(_sortedList.first, 1); }); test('firstWhere', () { expect(_sortedList.firstWhere((it) => it.isEven), 2); }); test('fold', () { expect(_sortedList.fold(0, (a, b) => a + b), 10); }); test('followedBy', () { expect(_sortedList.followedBy([2]), [1, 2, 3, 4, 2]); }); test('forEach', () { final list = []; _sortedList.forEach(list.add); expect(list, [1, 2, 3, 4]); }); test('isEmpty', () { expect(_sortedList.isEmpty, isFalse); }); test('isNotEmpty', () { expect(_sortedList.isNotEmpty, isTrue); }); test('iterator', () { expect(_sortedList.iterator, isA<Iterator<int>>()); var iterator = _sortedList.iterator; expect(iterator.moveNext(), isTrue); expect(iterator.current, 1); }); test('join', () { expect(_sortedList.join(','), '1,2,3,4'); }); test('last', () { expect(_sortedList.last, 4); }); test('lastWhere', () { expect(_sortedList.lastWhere((it) => it < 3), 2); }); test('length', () { expect(_sortedList.length, 4); }); test('map', () { expect(_sortedList.map((it) => it.isEven), [false, true, false, true]); }); test('reduce', () { expect(_sortedList.reduce((a, b) => a + b), 10); }); test('single', () { expect(() => _sortedList.single, throwsA(isA<StateError>())); }); test('singleWhere', () { expect(_sortedList.singleWhere((it) => it == 3), 3); }); test('skip', () { expect(_sortedList.skip(1), [2, 3, 4]); }); test('skipWhile', () { expect(_sortedList.skipWhile((it) => it < 3), [3, 4]); }); test('take', () { expect(_sortedList.take(2), [1, 2]); }); test('takeWhile', () { expect(_sortedList.takeWhile((_) => true), [1, 2, 3, 4]); }); test('toList', () { expect(_sortedList.toList(), [1, 2, 3, 4]); }); test('toSet', () { expect(_sortedList.toSet(), {1, 2, 3, 4}); }); test('where', () { expect(_sortedList.where((it) => it % 2 == 0), [2, 4]); }); test('whereType', () { expect(_sortedList.whereType<int>(), [1, 2, 3, 4]); }); }); group('_DelegatingList', () { test('operator []', () { expect(_sortedList[2], 3); }); test('operator =[]', () { final list = _sortedList; list[2] = 5; expect(list, [1, 2, 5, 4]); }); test('operator +', () { expect(_sortedList + [1, 2], [1, 2, 3, 4, 1, 2]); }); test('add', () { final list = _sortedList; list.add(1); expect(list, [1, 2, 3, 4, 1]); }); test('addAll', () { final list = _sortedList; list.addAll([1, 2]); expect(list, [1, 2, 3, 4, 1, 2]); }); test('asMap', () { expect(_sortedList.asMap(), {0: 1, 1: 2, 2: 3, 3: 4}); }); test('clear', () { final list = _sortedList; list.clear(); expect(list, isEmpty); }); test('fillRange', () { final list = _sortedList; list.fillRange(0, 2, 6); expect(list, [6, 6, 3, 4]); }); test('set first', () { final list = _sortedList; list.first = 6; expect(list, [6, 2, 3, 4]); }); test('getRange', () { expect(_sortedList.getRange(0, 2), [1, 2]); }); test('indexOf', () { expect(_sortedList.indexOf(2), 1); }); test('indexWhere', () { expect(_sortedList.indexWhere((it) => it == 2), 1); }); test('insert', () { final list = _sortedList; list.insert(3, 6); expect(list, [1, 2, 3, 6, 4]); }); test('insertAll', () { final list = _sortedList; list.insertAll(3, [6, 7]); expect(list, [1, 2, 3, 6, 7, 4]); }); test('set last', () { final list = _sortedList; list.last = 5; expect(list, [1, 2, 3, 5]); }); test('lastIndexOf', () { expect(_sortedList.lastIndexOf(3), 2); }); test('lastIndexWhere', () { expect(_sortedList.lastIndexWhere((it) => it == 3), 2); }); test('set length', () { final list = _sortedList; list.length = 5; expect(list, [1, 2, 3, 4, null]); }); test('remove', () { final list = _sortedList; list.remove(3); expect(list, [1, 2, 4]); }); test('removeAt', () { final list = _sortedList; list.removeAt(2); expect(list, [1, 2, 4]); }); test('removeLast', () { final list = _sortedList; list.removeLast(); expect(list, [1, 2, 3]); }); test('removeRange', () { final list = _sortedList; list.removeRange(1, 3); expect(list, [1, 4]); }); test('removeWhere', () { final list = _sortedList; list.removeWhere((it) => it % 2 == 0); expect(list, [1, 3]); }); test('replaceRange', () { final list = _sortedList; list.replaceRange(1, 2, [6, 6]); expect(list, [1, 6, 6, 3, 4]); }); test('retainWhere', () { final list = _sortedList; list.retainWhere((it) => it % 2 == 0); expect(list, [2, 4]); }); test('reversed', () { expect(_sortedList.reversed, [4, 3, 2, 1]); }); test('setAll', () { final list = _sortedList; list.setAll(1, [6, 6]); expect(list, [1, 6, 6, 4]); }); test('setRange', () { final list = _sortedList; list.setRange(1, 3, [6, 7]); expect(list, [1, 6, 7, 4]); }); test('random', () { final r = math.Random(42); final list = _sortedList; list.shuffle(r); expect(list, [2, 3, 1, 4]); }); test('sort', () { final list = _sortedList; list.sort((a, b) => a - b); expect(list, [1, 2, 3, 4]); }); test('sublist', () { expect(_sortedList.sublist(1, 2), [2]); }); test('can sort items by 3 comparators', () { const itemList = [ Item(0, 1, 2), Item(2, 1, 0), Item(1, 2, 0), ]; final sorted = itemList .sortedBy((item) => item.a) .thenBy((item) => item.b) .thenBy((item) => item.c); expect( sorted.toList(), equals(const [ Item(0, 1, 2), Item(1, 2, 0), Item(2, 1, 0), ])); }); }); } class Item { final int a; final int b; final int c; const Item(this.a, this.b, this.c); @override String toString() { return 'Item{a: $a, b: $b, c: $c}'; } @override bool operator ==(Object other) => identical(this, other) || other is Item && runtimeType == other.runtimeType && a == other.a && b == other.b && c == other.c; @override int get hashCode => a.hashCode ^ b.hashCode ^ c.hashCode; }
dartx/test/sorted_list_test.dart/0
{'file_path': 'dartx/test/sorted_list_test.dart', 'repo_id': 'dartx', 'token_count': 3692}
export 'text.dart';
dashbook/bricks/dashbook_gallery/__brick__/gallery/lib/widgets/widgets.dart/0
{'file_path': 'dashbook/bricks/dashbook_gallery/__brick__/gallery/lib/widgets/widgets.dart', 'repo_id': 'dashbook', 'token_count': 8}
import 'package:flutter/material.dart'; bool isLargeScreen(BuildContext context) => MediaQuery.of(context).size.width > 768; double iconSize(BuildContext context) => isLargeScreen(context) ? 24.0 : 48.0; double sideBarSizeStory(BuildContext context) { final screenWidth = MediaQuery.of(context).size.width; final factor = isLargeScreen(context) ? 0.25 : 1; return screenWidth * factor; } double sideBarSizeProperties(BuildContext context) { final screenWidth = MediaQuery.of(context).size.width; final factor = isLargeScreen(context) ? 0.5 : 1; return screenWidth * factor; } Future<void> showPopup({ required BuildContext context, required WidgetBuilder builder, }) async { return showDialog<void>( context: context, builder: builder, useRootNavigator: false, ); }
dashbook/lib/src/widgets/helpers.dart/0
{'file_path': 'dashbook/lib/src/widgets/helpers.dart', 'repo_id': 'dashbook', 'token_count': 254}
import 'package:flutter/material.dart'; class PropertyDialog extends StatelessWidget { final String title; final Widget content; final List<Widget> actions; const PropertyDialog({ Key? key, required this.title, required this.content, required this.actions, }) : super(key: key); @override Widget build(BuildContext context) { return AlertDialog( title: Text(title), content: SingleChildScrollView(child: content), actions: actions, ); } }
dashbook/lib/src/widgets/property_widgets/widgets/property_dialog.dart/0
{'file_path': 'dashbook/lib/src/widgets/property_widgets/widgets/property_dialog.dart', 'repo_id': 'dashbook', 'token_count': 169}
import 'package:dashtronaut/presentation/background/utils/background_layers.dart'; import 'package:dashtronaut/presentation/background/widgets/animated_background_layer.dart'; import 'package:dashtronaut/presentation/background/widgets/stars.dart'; import 'package:dashtronaut/presentation/layout/background_layer_layout.dart'; import 'package:dashtronaut/presentation/styles/app_colors.dart'; import 'package:flutter/material.dart'; class BackgroundStack extends StatelessWidget { const BackgroundStack({Key? key}) : super(key: key); @override Widget build(BuildContext context) { Size screenSize = MediaQuery.of(context).size; List<BackgroundLayerLayout> backgroundLayers = BackgroundLayers()(context); return Positioned.fill( child: Container( height: screenSize.height, width: screenSize.width, decoration: const BoxDecoration( gradient: RadialGradient( colors: [AppColors.primaryAccent, AppColors.primary], stops: [0, 1], radius: 1.1, center: Alignment.centerLeft, ), ), child: Stack( children: [ const Positioned.fill(child: Stars()), ...List.generate( backgroundLayers.length, (i) => AnimatedBackgroundLayer(layer: backgroundLayers[i]), ), ], ), ), ); } }
dashtronaut/lib/presentation/background/widgets/background_stack.dart/0
{'file_path': 'dashtronaut/lib/presentation/background/widgets/background_stack.dart', 'repo_id': 'dashtronaut', 'token_count': 571}
import 'package:dashtronaut/models/puzzle.dart'; import 'package:dashtronaut/presentation/drawer/puzzle_size_item.dart'; import 'package:dashtronaut/presentation/layout/spacing.dart'; import 'package:dashtronaut/presentation/styles/app_text_styles.dart'; import 'package:flutter/material.dart'; class PuzzleSizeSettings extends StatelessWidget { const PuzzleSizeSettings({Key? key}) : super(key: key); @override Widget build(BuildContext context) { double drawerStartPadding = MediaQuery.of(context).padding.left == 0 ? Spacing.md : MediaQuery.of(context).padding.left; return Container( padding: EdgeInsets.only( right: Spacing.md, left: drawerStartPadding, bottom: Spacing.md), decoration: const BoxDecoration( border: Border(bottom: BorderSide(color: Colors.white, width: 2)), ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const Text('Puzzle Size', style: AppTextStyles.h2), const SizedBox(height: 5), const Text('Select the size of your puzzle'), const SizedBox(height: 2), Text( '(This will reset your progress!)', style: AppTextStyles.bodyXs.copyWith(fontStyle: FontStyle.italic), ), const SizedBox(height: 10), Row( children: List.generate( Puzzle.supportedPuzzleSizes.length, (index) => Expanded( child: Padding( padding: EdgeInsetsDirectional.only( end: index < Puzzle.supportedPuzzleSizes.length - 1 ? Spacing.xs / 2 : 0, start: index > 0 ? Spacing.xs / 2 : 0, ), child: PuzzleSizeItem( size: Puzzle.supportedPuzzleSizes[index], ), ), ), ), ) ], ), ); } }
dashtronaut/lib/presentation/drawer/puzzle_size_settings.dart/0
{'file_path': 'dashtronaut/lib/presentation/drawer/puzzle_size_settings.dart', 'repo_id': 'dashtronaut', 'token_count': 956}
import 'package:dashtronaut/presentation/styles/app_text_styles.dart'; import 'package:dashtronaut/providers/puzzle_provider.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; class MovesCount extends StatelessWidget { const MovesCount({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Selector<PuzzleProvider, int>( selector: (c, puzzleProvider) => puzzleProvider.movesCount, builder: (c, int movesCount, _) => RichText( text: TextSpan( text: 'Moves: ', style: AppTextStyles.body.copyWith(color: Colors.white), children: <TextSpan>[ TextSpan( text: '$movesCount', style: AppTextStyles.bodyBold.copyWith(color: Colors.white), ), ], ), ), ); } }
dashtronaut/lib/presentation/puzzle/ui/moves_count.dart/0
{'file_path': 'dashtronaut/lib/presentation/puzzle/ui/moves_count.dart', 'repo_id': 'dashtronaut', 'token_count': 371}
class StorageKey { static const String puzzle = 'puzzle'; static const String secondsElapsed = 'secondsElapsed'; static const String scores = 'scores'; } abstract class StorageService { Future<void> init(); Future<void> remove(String key); dynamic get(String key); Future<void> clear(); bool has(String key); Future<void> set(String? key, dynamic data); }
dashtronaut/lib/services/storage/storage_service.dart/0
{'file_path': 'dashtronaut/lib/services/storage/storage_service.dart', 'repo_id': 'dashtronaut', 'token_count': 111}
import 'package:intl/intl.dart'; import 'package:daylight/daylight.dart'; void main() { const berlin = const DaylightLocation(52.518611, 13.408056); final october = DateTime(2020, 10, 15); // Create berlin calculator const berlinSunCalculator = const DaylightCalculator(berlin); // calculate for sunrise on civil twilight final civilSunrise = berlinSunCalculator.calculateEvent( october, Zenith.civil, EventType.sunrise, ); print(civilSunrise?.formatStandard()); // utc: 04:58:18 // calculate for sunrise and sunset on astronomical twilight final astronomicalEvents = berlinSunCalculator.calculateForDay( october, Zenith.astronomical, ); print(astronomicalEvents.sunset?.formatStandard()); // utc: 18:03:55 print(astronomicalEvents.sunrise?.formatStandard()); // utc: 03:39:09 print(astronomicalEvents.type); // DayType.sunriseAndSunset } extension on DateTime { String formatStandard() { return DateFormat("HH:mm:ss").format(this); } }
daylight/example/example.dart/0
{'file_path': 'daylight/example/example.dart', 'repo_id': 'daylight', 'token_count': 336}
import 'package:declarative_reactivity_workshop/async_state.dart'; import 'package:declarative_reactivity_workshop/log.dart'; import 'package:declarative_reactivity_workshop/src/async_atom.dart'; import 'package:declarative_reactivity_workshop/src/atom.dart'; void main() async { final container = AtomContainer() // ..onDispose(() => log('on-dispose-container', 0)); container.listen(delayedStreamByTen, (previous, next) { log('listen-delayed-stream-by-ten', (previous, next)); }); log('await-delayed-stream-by-ten', await container.async(delayedStreamByTen)); log('await-delayed-stream', await container.async(delayedStream)); container.invalidate(delayed); log('await-delayed-stream-by-ten', await container.async(delayedStreamByTen)); log('await-delayed-stream', await container.async(delayedStream)); log('await-delayed', await container.async(delayed)); container.dispose(); }
declarative_reactivity_workshop/bin/stream_async.dart/0
{'file_path': 'declarative_reactivity_workshop/bin/stream_async.dart', 'repo_id': 'declarative_reactivity_workshop', 'token_count': 310}
import 'package:flutter/material.dart'; class CounterVisual extends StatelessWidget { final int counter; final VoidCallback onPressed; const CounterVisual(this.counter, {Key key, this.onPressed}) : super(key: key); @override Widget build(BuildContext context) { return Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text(counter.toString()), Padding( padding: const EdgeInsets.all(8.0), child: RaisedButton( color: Colors.blue, child: Text('+'), onPressed: onPressed, ), ), ], ); } }
demo_21-01-2019/lib/countervisual.dart/0
{'file_path': 'demo_21-01-2019/lib/countervisual.dart', 'repo_id': 'demo_21-01-2019', 'token_count': 284}
export 'src/adapters/adapters.dart'; export 'src/deposit.dart'; export 'src/deposit_adapter.dart'; export 'src/entity.dart'; export 'src/operators/operators.dart';
deposit/packages/deposit/lib/deposit.dart/0
{'file_path': 'deposit/packages/deposit/lib/deposit.dart', 'repo_id': 'deposit', 'token_count': 63}
name: deposit_supabase description: Provides a Supabase adapter for the deposit package version: 0.0.2 repository: https://github.com/bluefireteam/deposit/tree/main/packages/deposit_supabase issue_tracker: https://github.com/bluefireteam/deposit homepage: https://github.com/bluefireteam/deposit environment: sdk: '>=2.15.1 <3.0.0' dependencies: deposit: ^0.0.2 supabase: ^0.2.13 dev_dependencies: test: ^1.20.1 very_good_analysis: ^2.4.0
deposit/packages/deposit_supabase/pubspec.yaml/0
{'file_path': 'deposit/packages/deposit_supabase/pubspec.yaml', 'repo_id': 'deposit', 'token_count': 173}
name: Scrape on: workflow_dispatch: pull_request: branches: - master schedule: # runs the CI weekly - cron: "0 0 * * 0" env: branch: "master" jobs: scrape: name: Scrape runs-on: ubuntu-latest steps: - uses: actions/checkout@v1 with: ref: ${{ env.branch }} token: ${{ secrets.REPO_TOKEN }} - name: Scrape id: scrape uses: actions/github-script@v4 with: script: | const script = require('./.github/scripts/scrape.js') await script({github, context, core}) - name: Commit Changes working-directory: .github/scripts run: sh ./commit_changes.sh env: TOKEN: ${{ secrets.REPO_TOKEN }} BRANCH: ${{ env.branch }}
developer-story/.github/workflows/scrape.yml/0
{'file_path': 'developer-story/.github/workflows/scrape.yml', 'repo_id': 'developer-story', 'token_count': 386}
import 'dart:convert'; import 'dart:typed_data'; import 'package:flutter/material.dart'; import 'package:steel_crypt/steel_crypt.dart' as encrypt; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Unoptimized Encryption Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: const MyHomePage(title: 'Unoptimized Encryption Demo'), ); } } 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> { TextEditingController textEditingController; String encryptedText; @override void initState() { super.initState(); encryptedText = ''; textEditingController = TextEditingController( text: 'Lorem ipsum dolor sit amet', ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Padding( padding: const EdgeInsets.all(16.0), child: Column( mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[ TextField( controller: textEditingController, ), Column( children: [ ElevatedButton( child: const Text('Encrypt'), onPressed: () { setState(() { encryptedText = encryptText(textEditingController.text); }); }, ), TextButton( child: const Text( 'Clear', style: TextStyle(color: Colors.black54), ), onPressed: () { textEditingController.clear(); setState(() { encryptedText = ''; }); }, ), ], ), Column( children: [ const Text( 'Encrypted Text:', style: TextStyle(fontWeight: FontWeight.bold), ), Text(encryptedText), ], ), ], ), ), ); } String encryptText(String stringToEncrypt) { final key = base64.encode(Uint8List.fromList( utf8.encode('my 32 length key................'), )); final iv = base64.encode(Uint8List(16)); final aesEncrypter = encrypt.AesCrypt(key: key, padding: encrypt.PaddingAES.pkcs7); final encryptedText = aesEncrypter.ctr.encrypt( inp: stringToEncrypt, iv: iv, ); return encryptedText; } }
devtools/case_study/code_size/optimized/code_size_package/lib/main.dart/0
{'file_path': 'devtools/case_study/code_size/optimized/code_size_package/lib/main.dart', 'repo_id': 'devtools', 'token_count': 1456}
// 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 'provider.dart'; class _StubProvider implements AnalyticsProvider { @override bool get isEnabled => false; @override bool get shouldPrompt => false; @override bool get isGtagsEnabled => false; @override void setAllowAnalytics() {} @override void setDontAllowAnalytics() {} @override void setUpAnalytics() {} } Future<AnalyticsProvider> get analyticsProvider async => _provider; AnalyticsProvider _provider = _StubProvider();
devtools/packages/devtools_app/lib/src/analytics/stub_provider.dart/0
{'file_path': 'devtools/packages/devtools_app/lib/src/analytics/stub_provider.dart', 'repo_id': 'devtools', 'token_count': 182}
// 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:html' hide Storage; import '../../globals.dart'; import '../../server_api_client.dart'; import '../../storage.dart'; /// Return the url the application is launched from. Future<String> initializePlatform() async { // Clear out the unneeded HTML from index.html. for (var element in document.body.querySelectorAll('.legacy-dart')) { element.remove(); } // Here, we try and initialize the connection between the DevTools web app and // its local server. DevTools can be launched without the server however, so // establishing this connection is a best-effort. final connection = await DevToolsServerConnection.connect(); if (connection != null) { setGlobal(Storage, ServerConnectionStorage(connection)); } else { setGlobal(Storage, BrowserStorage()); } // Prevent the browser default behavior for specific keybindings we'll later // handle in the app. This is a workaround for // https://github.com/flutter/flutter/issues/58119. window.onKeyDown.listen((event) { _sendKeyPressToParent(event); // Here, we're just trying to match the '⌘P' keybinding on macos. if (!event.metaKey) { return; } if (!window.navigator.userAgent.contains('Macintosh')) { return; } if (event.key == 'p') { event.preventDefault(); } }); return '${window.location}'; } void _sendKeyPressToParent(KeyboardEvent event) { // When DevTools is embedded inside IDEs in iframes, it will capture all // keypresses, preventing IDE shortcuts from working. To fix this, keypresses // will need to be posted up to the parent // https://github.com/flutter/devtools/issues/2775 // Check we have a connection and we appear to be embedded somewhere expected // because we can't use targetOrigin in postMessage as only the scheme is fixed // for VS Code (vscode-webview://[some guid]). if (serviceManager == null || !serviceManager.hasConnection) return; if (!window.navigator.userAgent.contains('Electron')) return; final data = { 'altKey': event.altKey, 'code': event.code, 'ctrlKey': event.ctrlKey, 'isComposing': event.isComposing, 'key': event.key, 'location': event.location, 'metaKey': event.metaKey, 'repeat': event.repeat, 'shiftKey': event.shiftKey }; window.parent?.postMessage({'command': 'keydown', 'data': data}, '*'); } class ServerConnectionStorage implements Storage { ServerConnectionStorage(this.connection); final DevToolsServerConnection connection; @override Future<String> getValue(String key) async { return connection.getPreferenceValue(key); } @override Future setValue(String key, String value) async { await connection.setPreferenceValue(key, value); } } class BrowserStorage implements Storage { @override Future<String> getValue(String key) async { return window.localStorage[key]; } @override Future setValue(String key, String value) async { window.localStorage[key] = value; } }
devtools/packages/devtools_app/lib/src/config_specific/framework_initialize/_framework_initialize_web.dart/0
{'file_path': 'devtools/packages/devtools_app/lib/src/config_specific/framework_initialize/_framework_initialize_web.dart', 'repo_id': 'devtools', 'token_count': 985}
// 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 'dart:async'; import 'dart:math' as math; import 'package:flutter/cupertino.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import '../eval_on_dart_library.dart'; import '../theme.dart'; import '../ui/utils.dart'; /// Regex for valid Dart identifiers. final _identifier = RegExp(r'^[a-zA-Z0-9]|_|\$'); /// Returns the word in the [line] for the provided hover [dx] offset given /// the [line]'s [textStyle]. String wordForHover(double dx, TextSpan line) { String word = ''; final hoverIndex = _hoverIndexFor(dx, line); final lineText = line.toPlainText(); if (hoverIndex >= 0 && hoverIndex < lineText.length) { final hoverChar = lineText[hoverIndex]; word = '$word$hoverChar'; if (_identifier.hasMatch(hoverChar) || hoverChar == '.') { // Merge trailing valid identifiers. int charIndex = hoverIndex + 1; while (charIndex < lineText.length) { final character = lineText[charIndex]; if (_identifier.hasMatch(character)) { word = '$word$character'; } else { break; } charIndex++; } // Merge preceding characters including those linked by a `.`. charIndex = hoverIndex - 1; while (charIndex >= 0) { final character = lineText[charIndex]; if (_identifier.hasMatch(character) || character == '.') { word = '$character$word'; } else { break; } charIndex--; } } } return word; } /// Returns the index in the Textspan's plainText for which the hover offset is /// located. int _hoverIndexFor(double dx, TextSpan line) { int hoverIndex = -1; final length = line.toPlainText().length; for (var i = 0; i < length; i++) { final painter = TextPainter( text: truncateTextSpan(line, i + 1), textDirection: TextDirection.ltr, )..layout(); if (dx <= painter.width) { hoverIndex = i; break; } } return hoverIndex; } const _hoverCardBorderWidth = 2.0; const _hoverYOffset = 10; class HoverCardData { HoverCardData({ @required this.title, @required this.contents, this.width = HoverCardTooltip.defaultHoverWidth, }); final String title; final Widget contents; final double width; } /// A card to display content while hovering over a widget. /// /// This widget will automatically remove itself after the mouse has entered /// and left its region. /// /// Note that if a mouse has never entered, it will not remove itself. class HoverCard { HoverCard({ @required BuildContext context, @required PointerHoverEvent event, @required String title, @required Widget contents, @required double width, }) { final overlayState = Overlay.of(context); final colorScheme = Theme.of(context).colorScheme; final focusColor = Theme.of(context).focusColor; final hoverHeading = colorScheme.hoverTitleTextStyle; final position = event.position; _overlayEntry = OverlayEntry(builder: (context) { return Positioned( left: math.max(0, position.dx - (width / 2.0)), top: position.dy + _hoverYOffset, child: MouseRegion( onExit: (_) { remove(); }, onEnter: (_) { _hasMouseEntered = true; }, child: Container( padding: const EdgeInsets.all(denseSpacing), decoration: BoxDecoration( color: colorScheme.defaultBackgroundColor, border: Border.all( color: focusColor, width: _hoverCardBorderWidth, ), borderRadius: BorderRadius.circular(defaultBorderRadius), ), width: width, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox( width: width, child: Text( title, overflow: TextOverflow.ellipsis, style: hoverHeading, textAlign: TextAlign.center, ), ), Divider(color: colorScheme.hoverTextStyle.color), contents, ], ), ), ), ); }); overlayState.insert(_overlayEntry); } OverlayEntry _overlayEntry; bool _isRemoved = false; bool _hasMouseEntered = false; /// Attempts to remove the HoverCard from the screen. /// /// The HoverCard will not be removed if the mouse is currently inside the /// widget. void maybeRemove() { if (!_hasMouseEntered) remove(); } /// Removes the HoverCard even if the mouse is in the corresponding mouse /// region. void remove() { if (!_isRemoved) _overlayEntry.remove(); _isRemoved = true; } } /// A hover card based tooltip. class HoverCardTooltip extends StatefulWidget { const HoverCardTooltip({ @required this.enabled, @required this.onHover, @required this.child, this.disposable, }); static const _hoverDelay = Duration(milliseconds: 500); static const defaultHoverWidth = 450.0; /// Whether the tooltip is currently enabled. final bool Function() enabled; /// Data to display when hovering over a particular point. final Future<HoverCardData> Function(PointerHoverEvent event) onHover; final Widget child; /// Disposable object to be disposed when the group is closed. final Disposable disposable; @override _HoverCardTooltipState createState() => _HoverCardTooltipState(); } class _HoverCardTooltipState extends State<HoverCardTooltip> { /// A timer that shows a [HoverCard] with an evaluation result when completed. Timer _showTimer; /// A timer that removes a [HoverCard] when completed. Timer _removeTimer; /// Displays the evaluation result of a source code item. HoverCard _hoverCard; void _onHoverExit() { _showTimer?.cancel(); _removeTimer = Timer(HoverCardTooltip._hoverDelay, () { _hoverCard?.maybeRemove(); }); } void _onHover(PointerHoverEvent event) { _showTimer?.cancel(); _showTimer = null; _removeTimer?.cancel(); _removeTimer = null; if (!widget.enabled()) return; _showTimer = Timer(HoverCardTooltip._hoverDelay, () async { _hoverCard?.remove(); _hoverCard = null; final hoverCardData = await widget.onHover(event); if (hoverCardData != null) { _hoverCard = HoverCard( context: context, event: event, title: hoverCardData.title, contents: hoverCardData.contents, width: hoverCardData.width, ); } }); } @override void dispose() { _showTimer?.cancel(); _removeTimer?.cancel(); _hoverCard?.remove(); widget.disposable?.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return MouseRegion( onExit: (_) => _onHoverExit(), onHover: _onHover, child: widget.child, ); } }
devtools/packages/devtools_app/lib/src/debugger/hover.dart/0
{'file_path': 'devtools/packages/devtools_app/lib/src/debugger/hover.dart', 'repo_id': 'devtools', 'token_count': 2881}
// 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:flutter/rendering.dart'; // This file was originally forked from package:flutter_widgets. Note that the // source may diverge over time. /// Sets up a collection of scroll controllers that mirror their movements to /// each other. /// /// Controllers are added and returned via [addAndGet]. The initial offset /// of the newly created controller is synced to the current offset. /// Controllers must be `dispose`d when no longer in use to prevent memory /// leaks and performance degradation. /// /// If controllers are disposed over the course of the lifetime of this /// object the corresponding scrollables should be given unique keys. /// Without the keys, Flutter may reuse a controller after it has been disposed, /// which can cause the controller offsets to fall out of sync. class LinkedScrollControllerGroup { LinkedScrollControllerGroup() { _offsetNotifier = _LinkedScrollControllerGroupOffsetNotifier(this); } final _allControllers = <_LinkedScrollController>[]; ChangeNotifier get offsetNotifier => _offsetNotifier; _LinkedScrollControllerGroupOffsetNotifier _offsetNotifier; bool get hasAttachedControllers => _attachedControllers.isNotEmpty; /// The current scroll offset of the group. double get offset { assert( _attachedControllers.isNotEmpty, 'LinkedScrollControllerGroup does not have any scroll controllers ' 'attached.', ); return _attachedControllers.first.offset; } /// The current scroll position of the group. ScrollPosition get position { assert( _attachedControllers.isNotEmpty, 'LinkedScrollControllerGroup does not have any scroll controllers ' 'attached.', ); return _attachedControllers.first.position; } /// Creates a new controller that is linked to any existing ones. ScrollController addAndGet() { final initialScrollOffset = _attachedControllers.isEmpty ? 0.0 : _attachedControllers.first.position.pixels; final controller = _LinkedScrollController(this, initialScrollOffset: initialScrollOffset); _allControllers.add(controller); controller.addListener(_offsetNotifier.notifyListeners); return controller; } /// Adds a callback that will be called when the value of [offset] changes. void addOffsetChangedListener(VoidCallback onChanged) { _offsetNotifier.addListener(onChanged); } /// Removes the specified offset changed listener. void removeOffsetChangedListener(VoidCallback listener) { _offsetNotifier.removeListener(listener); } Iterable<_LinkedScrollController> get _attachedControllers => _allControllers.where((controller) => controller.hasClients); /// Animates the scroll position of all linked controllers to [offset]. Future<void> animateTo( double offset, { @required Curve curve, @required Duration duration, }) async { // All scroll controllers are already linked with their peers, so we only // need to interact with one controller to mirror the interaction with all // other controllers. if (_attachedControllers.isNotEmpty) { await _attachedControllers.first.animateTo( offset, duration: duration, curve: curve, ); } } /// Jumps the scroll position of all linked controllers to [value]. void jumpTo(double value) { // All scroll controllers are already linked with their peers, so we only // need to interact with one controller to mirror the interaction with all // other controllers. if (_attachedControllers.isNotEmpty) { _attachedControllers.first.jumpTo(value); } } /// Resets the scroll position of all linked controllers to 0. void resetScroll() { jumpTo(0.0); } } /// This class provides change notification for [LinkedScrollControllerGroup]'s /// scroll offset. /// /// This change notifier de-duplicates change events by only firing listeners /// when the scroll offset of the group has changed. class _LinkedScrollControllerGroupOffsetNotifier extends ChangeNotifier { _LinkedScrollControllerGroupOffsetNotifier(this.controllerGroup); final LinkedScrollControllerGroup controllerGroup; /// The cached offset for the group. /// /// This value will be used in determining whether to notify listeners. double _cachedOffset; @override void notifyListeners() { final currentOffset = controllerGroup.offset; if (currentOffset != _cachedOffset) { _cachedOffset = currentOffset; super.notifyListeners(); } } } /// A scroll controller that mirrors its movements to a peer, which must also /// be a [_LinkedScrollController]. class _LinkedScrollController extends ScrollController { _LinkedScrollController(this._controllers, {double initialScrollOffset}) : super(initialScrollOffset: initialScrollOffset); final LinkedScrollControllerGroup _controllers; @override void dispose() { _controllers._allControllers.remove(this); super.dispose(); } @override void attach(ScrollPosition position) { assert( position is _LinkedScrollPosition, '_LinkedScrollControllers can only be used with' ' _LinkedScrollPositions.'); final _LinkedScrollPosition linkedPosition = position; assert(linkedPosition.owner == this, '_LinkedScrollPosition cannot change controllers once created.'); super.attach(position); } @override _LinkedScrollPosition createScrollPosition(ScrollPhysics physics, ScrollContext context, ScrollPosition oldPosition) { return _LinkedScrollPosition( this, physics: physics, context: context, initialPixels: initialScrollOffset, oldPosition: oldPosition, ); } @override _LinkedScrollPosition get position => super.position; Iterable<_LinkedScrollController> get _allPeersWithClients => _controllers._attachedControllers.where((peer) => peer != this); bool get canLinkWithPeers => _allPeersWithClients.isNotEmpty; Iterable<_LinkedScrollActivity> linkWithPeers(_LinkedScrollPosition driver) { assert(canLinkWithPeers); return _allPeersWithClients .map((peer) => peer.link(driver)) .expand((e) => e); } Iterable<_LinkedScrollActivity> link(_LinkedScrollPosition driver) { assert(hasClients); final activities = <_LinkedScrollActivity>[]; for (_LinkedScrollPosition position in positions) { activities.add(position.link(driver)); } return activities; } } // Implementation details: Whenever position.setPixels or position.forcePixels // is called on a _LinkedScrollPosition (which may happen programmatically, or // as a result of a user action), the _LinkedScrollPosition creates a // _LinkedScrollActivity for each linked position and uses it to move to or jump // to the appropriate offset. // // When a new activity begins, the set of peer activities is cleared. class _LinkedScrollPosition extends ScrollPositionWithSingleContext { _LinkedScrollPosition( this.owner, { ScrollPhysics physics, ScrollContext context, double initialPixels, ScrollPosition oldPosition, }) : assert(owner != null), super( physics: physics, context: context, initialPixels: initialPixels, oldPosition: oldPosition, ); final _LinkedScrollController owner; final Set<_LinkedScrollActivity> _peerActivities = <_LinkedScrollActivity>{}; // We override hold to propagate it to all peer controllers. @override ScrollHoldController hold(VoidCallback holdCancelCallback) { for (final controller in owner._allPeersWithClients) { controller.position._holdInternal(); } return super.hold(holdCancelCallback); } // Calls hold without propagating to peers. void _holdInternal() { // TODO: passing null to hold seems fishy, but it doesn't // appear to hurt anything. Revisit this if bad things happen. super.hold(null); } @override void beginActivity(ScrollActivity newActivity) { if (newActivity == null) { return; } for (var activity in _peerActivities) { activity.unlink(this); } _peerActivities.clear(); super.beginActivity(newActivity); } @override double setPixels(double newPixels) { if (newPixels == pixels) { return 0.0; } updateUserScrollDirection(newPixels - pixels > 0.0 ? ScrollDirection.forward : ScrollDirection.reverse); if (owner.canLinkWithPeers) { _peerActivities.addAll(owner.linkWithPeers(this)); for (var activity in _peerActivities) { activity.moveTo(newPixels); } } return setPixelsInternal(newPixels); } double setPixelsInternal(double newPixels) { return super.setPixels(newPixels); } @override void forcePixels(double value) { if (value == pixels) { return; } updateUserScrollDirection(value - pixels > 0.0 ? ScrollDirection.forward : ScrollDirection.reverse); if (owner.canLinkWithPeers) { _peerActivities.addAll(owner.linkWithPeers(this)); for (var activity in _peerActivities) { activity.jumpTo(value); } } forcePixelsInternal(value); } void forcePixelsInternal(double value) { super.forcePixels(value); } _LinkedScrollActivity link(_LinkedScrollPosition driver) { if (this.activity is! _LinkedScrollActivity) { beginActivity(_LinkedScrollActivity(this)); } final _LinkedScrollActivity activity = this.activity; activity.link(driver); return activity; } void unlink(_LinkedScrollActivity activity) { _peerActivities.remove(activity); } // We override this method to make it public (overridden method is protected) @override // ignore: unnecessary_overrides void updateUserScrollDirection(ScrollDirection value) { super.updateUserScrollDirection(value); } @override void debugFillDescription(List<String> description) { super.debugFillDescription(description); description.add('owner: $owner'); } } class _LinkedScrollActivity extends ScrollActivity { _LinkedScrollActivity(_LinkedScrollPosition delegate) : super(delegate); @override _LinkedScrollPosition get delegate => super.delegate; final Set<_LinkedScrollPosition> drivers = <_LinkedScrollPosition>{}; void link(_LinkedScrollPosition driver) { drivers.add(driver); } void unlink(_LinkedScrollPosition driver) { drivers.remove(driver); if (drivers.isEmpty) { delegate?.goIdle(); } } @override bool get shouldIgnorePointer => true; @override bool get isScrolling => true; // _LinkedScrollActivity is not self-driven but moved by calls to the [moveTo] // method. @override double get velocity => 0.0; void moveTo(double newPixels) { _updateUserScrollDirection(); delegate.setPixelsInternal(newPixels); } void jumpTo(double newPixels) { _updateUserScrollDirection(); delegate.forcePixelsInternal(newPixels); } void _updateUserScrollDirection() { assert(drivers.isNotEmpty); ScrollDirection commonDirection; for (var driver in drivers) { commonDirection ??= driver.userScrollDirection; if (driver.userScrollDirection != commonDirection) { commonDirection = ScrollDirection.idle; } } delegate.updateUserScrollDirection(commonDirection); } @override void dispose() { for (var driver in drivers) { driver.unlink(this); } super.dispose(); } }
devtools/packages/devtools_app/lib/src/flutter_widgets/linked_scroll_controller.dart/0
{'file_path': 'devtools/packages/devtools_app/lib/src/flutter_widgets/linked_scroll_controller.dart', 'repo_id': 'devtools', 'token_count': 3722}
import 'package:flutter/material.dart'; import 'theme.dart'; /// Text widget for displaying width / height. Widget dimensionDescription( TextSpan description, bool overflow, ColorScheme colorScheme, ) { final text = Text.rich( description, textAlign: TextAlign.center, style: overflow ? overflowingDimensionIndicatorTextStyle(colorScheme) : dimensionIndicatorTextStyle, overflow: TextOverflow.ellipsis, ); if (overflow) { return Container( padding: const EdgeInsets.symmetric( vertical: minPadding, horizontal: overflowTextHorizontalPadding, ), decoration: BoxDecoration( color: colorScheme.overflowBackgroundColor, borderRadius: BorderRadius.circular(4.0), ), child: Center(child: text), ); } return text; }
devtools/packages/devtools_app/lib/src/inspector/layout_explorer/ui/dimension.dart/0
{'file_path': 'devtools/packages/devtools_app/lib/src/inspector/layout_explorer/ui/dimension.dart', 'repo_id': 'devtools', 'token_count': 311}
// 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:devtools_shared/devtools_shared.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import '../auto_dispose_mixin.dart'; import '../charts/chart.dart'; import '../charts/chart_controller.dart'; import '../charts/chart_trace.dart' as trace; import '../theme.dart'; import 'memory_controller.dart'; import 'memory_timeline.dart'; class AndroidChartController extends ChartController { AndroidChartController(this._memoryController, {List<int> sharedLabels}) : super( displayTopLine: false, name: 'Android', sharedLabelimestamps: sharedLabels, ); final MemoryController _memoryController; // TODO(terry): Only load max visible data collected, when pruning of data // charted is added. /// Preload any existing data collected but not in the chart. @override void setupData() { // Only display if traces have been created. Android memory may not // have been toggled to be displayed - yet. if (traces.isNotEmpty) { final chartDataLength = timestampsLength; final dataLength = _memoryController.memoryTimeline.data.length; final dataRange = _memoryController.memoryTimeline.data.getRange( chartDataLength, dataLength, ); dataRange.forEach(addSample); } } /// Loads all heap samples (live data or offline). void addSample(HeapSample sample) { // If paused don't update the chart (data is still collected). if (_memoryController.isPaused) return; addTimestamp(sample.timestamp); final timestamp = sample.timestamp; final adb = sample.adbMemoryInfo; final stackValue = adb.stack.toDouble(); addDataToTrace(TraceName.stack.index, trace.Data(timestamp, stackValue)); final graphicValue = adb.graphics.toDouble(); addDataToTrace( TraceName.graphics.index, trace.Data( timestamp, graphicValue, )); final nativeHeapValue = adb.nativeHeap.toDouble(); addDataToTrace( TraceName.nativeHeap.index, trace.Data( timestamp, nativeHeapValue, )); final javaHeapValue = adb.javaHeap.toDouble(); addDataToTrace( TraceName.javaHeap.index, trace.Data(timestamp, javaHeapValue), ); final codeValue = adb.code.toDouble(); addDataToTrace(TraceName.code.index, trace.Data(timestamp, codeValue)); final otherValue = adb.other.toDouble(); addDataToTrace(TraceName.other.index, trace.Data(timestamp, otherValue)); final systemValue = adb.system.toDouble(); addDataToTrace(TraceName.system.index, trace.Data(timestamp, systemValue)); final totalValue = adb.total.toDouble(); addDataToTrace(TraceName.total.index, trace.Data(timestamp, totalValue)); } void addDataToTrace(int traceIndex, trace.Data data) { this.trace(traceIndex).addDatum(data); } } class MemoryAndroidChart extends StatefulWidget { const MemoryAndroidChart(this.chartController, {Key key}) : super(key: key); final AndroidChartController chartController; @override MemoryAndroidChartState createState() => MemoryAndroidChartState(); } /// Name of each trace being charted, index order is the trace index /// too (order of trace creation top-down order). enum TraceName { stack, javaHeap, code, graphics, nativeHeap, other, system, total, } class MemoryAndroidChartState extends State<MemoryAndroidChart> with AutoDisposeMixin { /// Controller attached to the chart. AndroidChartController get _chartController => widget.chartController; /// Controller for managing memory collection. MemoryController _memoryController; MemoryTimeline get _memoryTimeline => _memoryController.memoryTimeline; ColorScheme colorScheme; @override void initState() { super.initState(); } @override void didChangeDependencies() { super.didChangeDependencies(); _memoryController = Provider.of<MemoryController>(context); colorScheme = Theme.of(context).colorScheme; cancel(); setupTraces(); _chartController.setupData(); addAutoDisposeListener(_memoryTimeline.sampleAddedNotifier, () { _processHeapSample(_memoryTimeline.sampleAddedNotifier.value); }); } @override Widget build(BuildContext context) { if (_chartController != null) { if (_chartController.timestamps.isNotEmpty) { return Container( child: Chart(_chartController), height: defaultChartHeight, ); } } return const SizedBox(width: denseSpacing); } /// TODO(terry): Colors used in charts (move to theme). static const otherColor = Color(0xffff8800); // HoloOrangeDark; static const nativeHeapColor = Color(0xff33b5e5); // HoloBlueLight final graphicColor = Colors.greenAccent.shade400; static const codeColor = Color(0xffaa66cc); // HoloPurple static const javaColor = Colors.yellow; static const stackColor = Colors.tealAccent; static const systemColor = Color(0xff669900); // HoloGreenDark final totalColor = Colors.blueGrey.shade100; void setupTraces() { if (_chartController.traces.isNotEmpty) { assert(_chartController.traces.length == TraceName.values.length); final stackIndex = TraceName.stack.index; assert(_chartController.trace(stackIndex).name == TraceName.values[stackIndex].toString()); final graphicsIndex = TraceName.graphics.index; assert(_chartController.trace(graphicsIndex).name == TraceName.values[graphicsIndex].toString()); final nativeHeapIndex = TraceName.nativeHeap.index; assert(_chartController.trace(nativeHeapIndex).name == TraceName.values[nativeHeapIndex].toString()); final javaHeapIndex = TraceName.javaHeap.index; assert(_chartController.trace(javaHeapIndex).name == TraceName.values[javaHeapIndex].toString()); final codeIndex = TraceName.code.index; assert(_chartController.trace(codeIndex).name == TraceName.values[codeIndex].toString()); final otherIndex = TraceName.other.index; assert(_chartController.trace(otherIndex).name == TraceName.values[otherIndex].toString()); final systemIndex = TraceName.system.index; assert(_chartController.trace(systemIndex).name == TraceName.values[systemIndex].toString()); final totalIndex = TraceName.total.index; assert(_chartController.trace(totalIndex).name == TraceName.values[totalIndex].toString()); return; } // Need to create the trace first time. // Stack trace final stackIndex = _chartController.createTrace( trace.ChartType.line, trace.PaintCharacteristics( color: stackColor, symbol: trace.ChartSymbol.disc, diameter: 1.5, ), stacked: true, name: TraceName.stack.toString(), ); assert(stackIndex == TraceName.stack.index); assert(_chartController.trace(stackIndex).name == TraceName.values[stackIndex].toString()); // Java heap trace. final javaHeapIndex = _chartController.createTrace( trace.ChartType.line, trace.PaintCharacteristics( color: javaColor, symbol: trace.ChartSymbol.disc, diameter: 1.5, ), stacked: true, name: TraceName.javaHeap.toString(), ); assert(javaHeapIndex == TraceName.javaHeap.index); assert(_chartController.trace(javaHeapIndex).name == TraceName.values[javaHeapIndex].toString()); // Code trace final codeIndex = _chartController.createTrace( trace.ChartType.line, trace.PaintCharacteristics( color: codeColor, symbol: trace.ChartSymbol.disc, diameter: 1.5, ), stacked: true, name: TraceName.code.toString(), ); assert(codeIndex == TraceName.code.index); assert(_chartController.trace(codeIndex).name == TraceName.values[codeIndex].toString()); // Graphics Trace final graphicIndex = _chartController.createTrace( trace.ChartType.line, trace.PaintCharacteristics( color: graphicColor, symbol: trace.ChartSymbol.disc, diameter: 1.5, ), stacked: true, name: TraceName.graphics.toString(), ); assert(graphicIndex == TraceName.graphics.index); assert(_chartController.trace(graphicIndex).name == TraceName.values[graphicIndex].toString()); // Native heap trace. final nativeHeapIndex = _chartController.createTrace( trace.ChartType.line, trace.PaintCharacteristics( color: nativeHeapColor, symbol: trace.ChartSymbol.disc, diameter: 1.5, ), stacked: true, name: TraceName.nativeHeap.toString(), ); assert(nativeHeapIndex == TraceName.nativeHeap.index); assert(_chartController.trace(nativeHeapIndex).name == TraceName.values[nativeHeapIndex].toString()); // Other trace final otherIndex = _chartController.createTrace( trace.ChartType.line, trace.PaintCharacteristics( color: otherColor, symbol: trace.ChartSymbol.disc, diameter: 1.5, ), stacked: true, name: TraceName.other.toString(), ); assert(otherIndex == TraceName.other.index); assert(_chartController.trace(otherIndex).name == TraceName.values[otherIndex].toString()); // System trace final systemIndex = _chartController.createTrace( trace.ChartType.line, trace.PaintCharacteristics( color: systemColor, symbol: trace.ChartSymbol.disc, diameter: 1.5, ), stacked: true, name: TraceName.system.toString(), ); assert(systemIndex == TraceName.system.index); assert(_chartController.trace(systemIndex).name == TraceName.values[systemIndex].toString()); // Total trace. final totalIndex = _chartController.createTrace( trace.ChartType.line, trace.PaintCharacteristics( color: totalColor, symbol: trace.ChartSymbol.dashedLine, strokeWidth: 2, ), name: TraceName.total.toString(), ); assert(totalIndex == TraceName.total.index); assert(_chartController.trace(totalIndex).name == TraceName.values[totalIndex].toString()); assert(_chartController.traces.length == TraceName.values.length); } /// Loads all heap samples (live data or offline). void _processHeapSample(HeapSample sample) { // If paused don't update the chart (data is still collected). if (_memoryController.paused.value) return; _chartController.addSample(sample); } }
devtools/packages/devtools_app/lib/src/memory/memory_android_chart.dart/0
{'file_path': 'devtools/packages/devtools_app/lib/src/memory/memory_android_chart.dart', 'repo_id': 'devtools', 'token_count': 3949}
// 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 'theme.dart'; /// Returns [routeName] with [queryParameters] appended as [Uri] query /// parameters. /// /// If not overridden, this will preserve the theme parameter across /// navigations. /// /// /// This will fail because we can't determine what the theme value for the app /// is. String routeNameWithQueryParams(BuildContext context, String routeName, [Map<String, String> queryParameters]) { final newQueryParams = queryParameters == null ? null : Map.of(queryParameters); String previousQuery; if (context == null) { // We allow null context values to make easy pure-VM tests. previousQuery = ''; } else { previousQuery = ModalRoute.of(context).settings.name; // When this function is invoked from an unnamed context, // infer from the global theme configuration. previousQuery ??= _inferThemeParameter(Theme.of(context).colorScheme); } final previousQueryParams = Uri.parse(previousQuery).queryParameters; // Preserve the theme across app-triggered navigations. if (newQueryParams != null && !newQueryParams.containsKey('theme') && previousQueryParams['theme'] == 'dark') { newQueryParams['theme'] = 'dark'; } return Uri.parse(routeName) .replace(queryParameters: newQueryParams) .toString(); } /// Infers the app's theme from a global constant. /// /// When calling from an unnamed route, we can't infer the theme /// value from the Uri. For example, /// /// ```dart /// Navigator.of(context).push(MaterialPageRoute(builder: (innerContext) { /// routeNameWithQueryParams(innerContext, '/foo'); /// })); /// ``` /// /// ModalRoute.of`(innerContext)` returns the unnamed page route. String _inferThemeParameter(ColorScheme colorScheme) => // ignore: deprecated_member_use_from_same_package colorScheme.isDark ? '/unnamedRoute?theme=dark' : '/unnamedRoute';
devtools/packages/devtools_app/lib/src/navigation.dart/0
{'file_path': 'devtools/packages/devtools_app/lib/src/navigation.dart', 'repo_id': 'devtools', 'token_count': 632}
// 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. // TODO(kenz): delete this legacy implementation after // https://github.com/flutter/flutter/commit/78a96b09d64dc2a520e5b269d5cea1b9dde27d3f // hits flutter stable. import 'performance_model.dart'; String legacyComputeEventGroupKey( LegacyTimelineEvent 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 LegacyPerformanceData.uiKey; } else if (event.isRasterEvent) { return LegacyPerformanceData.rasterKey; } else if (threadNamesById[event.threadId] != null) { return threadNamesById[event.threadId]; } else { return LegacyPerformanceData.unknownKey; } }
devtools/packages/devtools_app/lib/src/performance/legacy/performance_utils.dart/0
{'file_path': 'devtools/packages/devtools_app/lib/src/performance/legacy/performance_utils.dart', 'repo_id': 'devtools', 'token_count': 304}
// 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/foundation.dart'; import 'package:meta/meta.dart'; import 'package:vm_service/vm_service.dart'; import '../globals.dart'; import '../ui/search.dart'; import '../utils.dart'; import '../vm_flags.dart' as vm_flags; import 'cpu_profile_model.dart'; import 'cpu_profile_service.dart'; import 'cpu_profile_transformer.dart'; class CpuProfilerController with SearchControllerMixin<CpuStackFrame> { /// Tag to represent when no user tag filters are applied. /// /// The word 'none' is not a magic word - just a user-friendly name to convey /// the message that no filters are applied. static const userTagNone = 'none'; /// Data for the initial value and reset value of [_dataNotifier]. /// /// When this data is the value of [_dataNotifier], the CPU profiler is in a /// base state where recording instructions should be shown. static CpuProfileData baseStateCpuProfileData = CpuProfileData.empty(); /// Store of cached CPU profiles. final cpuProfileStore = CpuProfileStore(); /// Notifies that new cpu profile data is available. ValueListenable<CpuProfileData> get dataNotifier => _dataNotifier; final _dataNotifier = ValueNotifier<CpuProfileData>(baseStateCpuProfileData); /// Notifies that CPU profile data is currently being processed. ValueListenable get processingNotifier => _processingNotifier; final _processingNotifier = ValueNotifier<bool>(false); /// Notifies that a cpu stack frame was selected. ValueListenable get selectedCpuStackFrameNotifier => _selectedCpuStackFrameNotifier; final _selectedCpuStackFrameNotifier = ValueNotifier<CpuStackFrame>(null); /// Notifies that a user tag filter is set on the CPU profile flame chart. ValueListenable<String> get userTagFilter => _userTagFilter; final _userTagFilter = ValueNotifier<String>(userTagNone); final _dataByTag = <String, CpuProfileData>{}; Iterable<String> get userTags => _dataByTag[userTagNone]?.userTags ?? []; int selectedProfilerTabIndex = 0; void changeSelectedProfilerTab(int index) { selectedProfilerTabIndex = index; } final transformer = CpuProfileTransformer(); /// Notifies that the vm profiler flag has changed. ValueNotifier<Flag> get profilerFlagNotifier => serviceManager.vmFlagManager.flag(vm_flags.profiler); ValueNotifier<Flag> get profileGranularityFlagNotifier => serviceManager.vmFlagManager.flag(vm_flags.profilePeriod); /// Whether the profiler is enabled. /// /// Clients interested in the current value of [profilerFlagNotifier] should /// use this getter. Otherwise, clients subscribing to change notifications, /// should listen to [profilerFlagNotifier]. bool get profilerEnabled => offlineMode ? true : profilerFlagNotifier.value.valueAsString == 'true'; Future<dynamic> enableCpuProfiler() { return serviceManager.service.enableCpuProfiler(); } Future<void> pullAndProcessProfile({ @required int startMicros, @required int extentMicros, String processId, }) async { if (!profilerEnabled) return; assert(_dataNotifier.value != null); assert(!_processingNotifier.value); _processingNotifier.value = true; var cpuProfileData = baseStateCpuProfileData; _dataNotifier.value = null; // TODO(kenz): add a cancel button to the processing UI in case pulling a // large payload from the vm service takes a long time. cpuProfileData = await serviceManager.service.getCpuProfile( startMicros: startMicros, extentMicros: extentMicros, ); await processAndSetData(cpuProfileData, processId: processId); cpuProfileStore.addProfile( TimeRange() ..start = Duration(microseconds: startMicros) ..end = Duration(microseconds: startMicros + extentMicros), _dataNotifier.value, ); } Future<void> processAndSetData( CpuProfileData cpuProfileData, { String processId, }) async { _processingNotifier.value = true; _dataNotifier.value = null; try { await transformer.processData(cpuProfileData, processId: processId); _dataNotifier.value = cpuProfileData; _dataByTag[userTagNone] = cpuProfileData; refreshSearchMatches(); _processingNotifier.value = false; } on AssertionError catch (_) { _dataNotifier.value = cpuProfileData; _processingNotifier.value = false; // Rethrow after setting notifiers so that cpu profile data is included // in the timeline export. rethrow; } on ProcessCancelledException catch (_) { // Do nothing because the attempt to process data has been cancelled in // favor of a new one. } } @override List<CpuStackFrame> matchesForSearch(String search) { if (search?.isEmpty ?? true) return []; final regexSearch = RegExp(search, caseSensitive: false); final matches = <CpuStackFrame>[]; final currentStackFrames = _dataNotifier.value.stackFrames.values; for (final frame in currentStackFrames) { if (frame.name.caseInsensitiveContains(regexSearch) || frame.url.caseInsensitiveContains(regexSearch)) { matches.add(frame); frame.isSearchMatch = true; } else { frame.isSearchMatch = false; } } return matches; } void loadProcessedData(CpuProfileData data) { assert(data.processed); _dataNotifier.value = data; _dataByTag[userTagNone] = data; } Future<void> loadDataWithTag(String tag) async { _userTagFilter.value = tag; _dataNotifier.value = null; _processingNotifier.value = true; try { _dataNotifier.value = await processDataForTag(tag); } catch (e) { // In the event of an error, reset the data to the original CPU profile. _dataNotifier.value = _dataByTag[userTagNone]; throw Exception('Error loading data with tag "$tag": ${e.toString()}'); } finally { _processingNotifier.value = false; } } Future<CpuProfileData> processDataForTag(String tag) async { final fullData = _dataByTag[userTagNone]; final data = _dataByTag.putIfAbsent( tag, () => fullData.dataForUserTag(tag), ); if (!data.processed) { await transformer.processData(data); } return data; } void selectCpuStackFrame(CpuStackFrame stackFrame) { if (stackFrame == dataNotifier.value.selectedStackFrame) return; dataNotifier.value.selectedStackFrame = stackFrame; _selectedCpuStackFrameNotifier.value = stackFrame; } Future<void> clear() async { reset(); cpuProfileStore.clear(); await serviceManager.service.clearSamples(); } void reset() { _selectedCpuStackFrameNotifier.value = null; _dataNotifier.value = baseStateCpuProfileData; _dataByTag.clear(); _processingNotifier.value = false; transformer.reset(); resetSearch(); } void dispose() { _dataNotifier.dispose(); _selectedCpuStackFrameNotifier.dispose(); _processingNotifier.dispose(); transformer.dispose(); } } mixin CpuProfilerControllerProviderMixin { final cpuProfilerController = CpuProfilerController(); }
devtools/packages/devtools_app/lib/src/profiler/cpu_profile_controller.dart/0
{'file_path': 'devtools/packages/devtools_app/lib/src/profiler/cpu_profile_controller.dart', 'repo_id': 'devtools', 'token_count': 2402}
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:math' as math; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'utils.dart'; /// A widget that takes a list of children, lays them out along [axis], and /// allows the user to resize them. /// /// The user can customize the amount of space allocated to each child by /// dragging a divider between them. /// /// [initialFractions] defines how much space to give each child when building /// this widget. class Split extends StatefulWidget { /// Builds a split oriented along [axis]. Split({ Key key, @required this.axis, @required this.children, @required this.initialFractions, this.minSizes, this.splitters, }) : assert(axis != null), assert(children != null && children.length >= 2), assert(initialFractions != null && initialFractions.length >= 2), assert(children.length == initialFractions.length), super(key: key) { _verifyFractionsSumTo1(initialFractions); if (minSizes != null) { assert(minSizes.length == children.length); } if (splitters != null) { assert(splitters.length == children.length - 1); } } /// The main axis the children will lay out on. /// /// If [Axis.horizontal], the children will be placed in a [Row] /// and they will be horizontally resizable. /// /// If [Axis.vertical], the children will be placed in a [Column] /// and they will be vertically resizable. /// /// Cannot be null. final Axis axis; /// The children that will be laid out along [axis]. final List<Widget> children; /// The fraction of the layout to allocate to each child in [children]. /// /// The index of [initialFractions] corresponds to the child at index of /// [children]. final List<double> initialFractions; /// The minimum size each child is allowed to be. final List<double> minSizes; /// Splitter widgets to divide [children]. /// /// If this is null, a default splitter will be used to divide [children]. final List<PreferredSizeWidget> splitters; /// The key passed to the divider between children[index] and /// children[index + 1]. /// /// Visible to grab it in tests. @visibleForTesting Key dividerKey(int index) => Key('$this dividerKey $index'); static Axis axisFor(BuildContext context, double horizontalAspectRatio) { final screenSize = MediaQuery.of(context).size; final aspectRatio = screenSize.width / screenSize.height; if (aspectRatio >= horizontalAspectRatio) return Axis.horizontal; return Axis.vertical; } @override State<StatefulWidget> createState() => _SplitState(); } class _SplitState extends State<Split> { List<double> fractions; bool get isHorizontal => widget.axis == Axis.horizontal; @override void initState() { super.initState(); fractions = List.from(widget.initialFractions); } @override Widget build(BuildContext context) { return LayoutBuilder(builder: _buildLayout); } Widget _buildLayout(BuildContext context, BoxConstraints constraints) { final width = constraints.maxWidth; final height = constraints.maxHeight; final axisSize = isHorizontal ? width : height; final availableSize = axisSize - _totalSplitterSize(); // Size calculation helpers. double _minSizeForIndex(int index) { if (widget.minSizes == null) return 0.0; double totalMinSize = 0; for (var minSize in widget.minSizes) { totalMinSize += minSize; } // Reduce the min sizes gracefully if the total required min size for all // children is greater than the available size for children. if (totalMinSize > availableSize) { return widget.minSizes[index] * availableSize / totalMinSize; } else { return widget.minSizes[index]; } } double _minFractionForIndex(int index) => _minSizeForIndex(index) / availableSize; void _clampFraction(int index) { fractions[index] = fractions[index].clamp(_minFractionForIndex(index), 1.0); } double _sizeForIndex(int index) => availableSize * fractions[index]; double fractionDeltaRequired = 0.0; double fractionDeltaAvailable = 0.0; double deltaFromMinimumSize(int index) => fractions[index] - _minFractionForIndex(index); for (int i = 0; i < fractions.length; ++i) { final delta = deltaFromMinimumSize(i); if (delta < 0) { fractionDeltaRequired -= delta; } else { fractionDeltaAvailable += delta; } } if (fractionDeltaRequired > 0) { // Likely due to a change in the available size, the current fractions for // the children do not obey the min size constraints. // The min size constraints for children are scaled so it is always // possible to meet them. A scaleFactor greater than 1 would indicate that // it is impossible to meet the constraints. double scaleFactor = fractionDeltaRequired / fractionDeltaAvailable; assert(scaleFactor <= 1 + defaultEpsilon); scaleFactor = math.min(scaleFactor, 1.0); for (int i = 0; i < fractions.length; ++i) { final delta = deltaFromMinimumSize(i); if (delta < 0) { // This is equivalent to adding delta but avoids rounding error. fractions[i] = _minFractionForIndex(i); } else { // Reduce all fractions that are above their minimum size by an amount // proportional to their ability to reduce their size without // violating their minimum size constraints. fractions[i] -= delta * scaleFactor; } } } // Determine what fraction to give each child, including enough space to // display the divider. final sizes = List.generate(fractions.length, (i) => _sizeForIndex(i)); void updateSpacing(DragUpdateDetails dragDetails, int splitterIndex) { final dragDelta = isHorizontal ? dragDetails.delta.dx : dragDetails.delta.dy; final fractionalDelta = dragDelta / axisSize; // Returns the actual delta applied to elements before the splitter. double updateSpacingBeforeSplitterIndex(double delta) { final startingDelta = delta; var index = splitterIndex; while (index >= 0) { fractions[index] += delta; final minFractionForIndex = _minFractionForIndex(index); if (fractions[index] >= minFractionForIndex) { _clampFraction(index); return startingDelta; } delta = fractions[index] - minFractionForIndex; _clampFraction(index); index--; } // At this point, we know that both [startingDelta] and [delta] are // negative, and that [delta] represents the overflow that did not get // applied. return startingDelta - delta; } // Returns the actual delta applied to elements after the splitter. double updateSpacingAfterSplitterIndex(double delta) { final startingDelta = delta; var index = splitterIndex + 1; while (index < fractions.length) { fractions[index] += delta; final minFractionForIndex = _minFractionForIndex(index); if (fractions[index] >= minFractionForIndex) { _clampFraction(index); return startingDelta; } delta = fractions[index] - minFractionForIndex; _clampFraction(index); index++; } // At this point, we know that both [startingDelta] and [delta] are // negative, and that [delta] represents the overflow that did not get // applied. return startingDelta - delta; } setState(() { // Update the fraction of space consumed by the children. Always update // the shrinking children first so that we do not over-increase the size // of the growing children and cause layout overflow errors. if (fractionalDelta <= 0.0) { final appliedDelta = updateSpacingBeforeSplitterIndex(fractionalDelta); updateSpacingAfterSplitterIndex(-appliedDelta); } else { final appliedDelta = updateSpacingAfterSplitterIndex(-fractionalDelta); updateSpacingBeforeSplitterIndex(-appliedDelta); } }); _verifyFractionsSumTo1(fractions); } final children = <Widget>[]; for (int i = 0; i < widget.children.length; i++) { children.addAll([ SizedBox( width: isHorizontal ? sizes[i] : width, height: isHorizontal ? height : sizes[i], child: widget.children[i], ), if (i < widget.children.length - 1) MouseRegion( cursor: isHorizontal ? SystemMouseCursors.resizeColumn : SystemMouseCursors.resizeRow, child: GestureDetector( key: widget.dividerKey(i), behavior: HitTestBehavior.translucent, onHorizontalDragUpdate: (details) => isHorizontal ? updateSpacing(details, i) : null, onVerticalDragUpdate: (details) => isHorizontal ? null : updateSpacing(details, i), // DartStartBehavior.down is needed to keep the mouse pointer stuck to // the drag bar. There still appears to be a few frame lag before the // drag action triggers which is't ideal but isn't a launch blocker. dragStartBehavior: DragStartBehavior.down, child: widget.splitters != null ? widget.splitters[i] : DefaultSplitter(isHorizontal: isHorizontal), ), ), ]); } return Flex( direction: widget.axis, children: children, crossAxisAlignment: CrossAxisAlignment.stretch, ); } double _totalSplitterSize() { final numSplitters = widget.children.length - 1; if (widget.splitters == null) { return numSplitters * DefaultSplitter.splitterWidth; } else { var totalSize = 0.0; for (var splitter in widget.splitters) { totalSize += isHorizontal ? splitter.preferredSize.width : splitter.preferredSize.height; } return totalSize; } } } class DefaultSplitter extends StatelessWidget { const DefaultSplitter({@required this.isHorizontal}); static const double iconSize = 24.0; static const double splitterWidth = 12.0; final bool isHorizontal; @override Widget build(BuildContext context) { return Transform.rotate( angle: isHorizontal ? degToRad(90.0) : degToRad(0.0), child: Align( widthFactor: 0.5, heightFactor: 0.5, child: Icon( Icons.drag_handle, size: iconSize, color: Theme.of(context).focusColor, ), ), ); } } void _verifyFractionsSumTo1(List<double> fractions) { var sumFractions = 0.0; for (var fraction in fractions) { sumFractions += fraction; } assert( (1.0 - sumFractions).abs() < defaultEpsilon, 'Fractions should sum to 1.0, but instead sum to $sumFractions:\n$fractions', ); }
devtools/packages/devtools_app/lib/src/split.dart/0
{'file_path': 'devtools/packages/devtools_app/lib/src/split.dart', 'repo_id': 'devtools', 'token_count': 4269}
/* * Copyright 2017 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. */ /// Platform independent definition of icons. /// /// See [HtmlIconRenderer] for a browser specific implementation of icon /// rendering. If you add an Icon class you also need to add a renderer class /// to handle the actual platform specific icon rendering. /// The benefit of this approach is that icons can be const objects and tests /// of code that uses icons can run on the Dart VM. library icons; import 'package:flutter/material.dart'; import 'package:meta/meta.dart'; import '../theme.dart'; import '../utils.dart'; class CustomIcon extends StatelessWidget { const CustomIcon({ @required this.kind, @required this.text, this.isAbstract = false, }); final IconKind kind; final String text; final bool isAbstract; Image get baseIcon => kind.icon; @override Widget build(BuildContext context) { return Container( width: baseIcon.width, height: baseIcon.height, child: Stack( alignment: AlignmentDirectional.center, children: <Widget>[ baseIcon, Text( text, textAlign: TextAlign.center, style: const TextStyle(fontSize: 9, color: Color(0xFF231F20)), ), ], ), ); } } class CustomIconMaker { final Map<String, CustomIcon> iconCache = {}; CustomIcon getCustomIcon(String fromText, {IconKind kind, bool isAbstract = false}) { kind ??= IconKind.classIcon; if (fromText?.isEmpty != false) { return null; } final String text = fromText[0].toUpperCase(); final String mapKey = '${text}_${kind.name}_$isAbstract'; return iconCache.putIfAbsent(mapKey, () { return CustomIcon(kind: kind, text: text, isAbstract: isAbstract); }); } CustomIcon fromWidgetName(String name) { if (name == null) { return null; } while (name.isNotEmpty && !isAlphabetic(name.codeUnitAt(0))) { name = name.substring(1); } if (name.isEmpty) { return null; } return getCustomIcon( name, kind: isPrivate(name) ? IconKind.method : IconKind.classIcon, ); } CustomIcon fromInfo(String name) { if (name == null) { return null; } if (name.isEmpty) { return null; } return getCustomIcon(name, kind: IconKind.info); } bool isAlphabetic(int char) { return (char < '0'.codeUnitAt(0) || char > '9'.codeUnitAt(0)) && char != '_'.codeUnitAt(0) && char != r'$'.codeUnitAt(0); } } class IconKind { const IconKind(this.name, this.icon, [Image abstractIcon]) : abstractIcon = abstractIcon ?? icon; static IconKind classIcon = IconKind( 'class', createImageIcon('icons/custom/class.png'), createImageIcon('icons/custom/class_abstract.png'), ); static IconKind field = IconKind( 'fields', createImageIcon('icons/custom/fields.png'), ); static IconKind interface = IconKind( 'interface', createImageIcon('icons/custom/interface.png'), ); static IconKind method = IconKind( 'method', createImageIcon('icons/custom/method.png'), createImageIcon('icons/custom/method_abstract.png'), ); static IconKind property = IconKind( 'property', createImageIcon('icons/custom/property.png'), ); static IconKind info = IconKind( 'info', createImageIcon('icons/custom/info.png'), ); final String name; final Image icon; final Image abstractIcon; } class ColorIcon extends StatelessWidget { const ColorIcon(this.color); final Color color; @override Widget build(BuildContext context) { final colorScheme = Theme.of(context).colorScheme; return CustomPaint( painter: _ColorIconPainter(color, colorScheme), size: const Size(defaultIconSize, defaultIconSize), ); } } class ColorIconMaker { final Map<Color, ColorIcon> iconCache = {}; ColorIcon getCustomIcon(Color color) { return iconCache.putIfAbsent(color, () => ColorIcon(color)); } } class _ColorIconPainter extends CustomPainter { const _ColorIconPainter(this.color, this.colorScheme); final Color color; final ColorScheme colorScheme; static const double iconMargin = 1; @override void paint(Canvas canvas, Size size) { // draw a black and gray grid to use as the background to disambiguate // opaque colors from translucent colors. final greyPaint = Paint()..color = colorScheme.grey; final iconRect = Rect.fromLTRB( iconMargin, iconMargin, size.width - iconMargin, size.height - iconMargin, ); canvas ..drawRect( Rect.fromLTRB( iconMargin, iconMargin, size.width - iconMargin, size.height - iconMargin, ), Paint()..color = colorScheme.defaultBackground, ) ..drawRect( Rect.fromLTRB( iconMargin, iconMargin, size.width * 0.5, size.height * 0.5, ), greyPaint, ) ..drawRect( Rect.fromLTRB( size.width * 0.5, size.height * 0.5, size.width - iconMargin, size.height - iconMargin, ), greyPaint, ) ..drawRect( iconRect, Paint()..color = color, ) ..drawRect( iconRect, Paint() ..style = PaintingStyle.stroke ..color = colorScheme.defaultForeground, ); } @override bool shouldRepaint(CustomPainter oldDelegate) { if (oldDelegate is _ColorIconPainter) { return oldDelegate.colorScheme.isLight != colorScheme.isLight; } return true; } } class FlutterMaterialIcons { FlutterMaterialIcons._(); static Icon getIconForCodePoint(int charCode, ColorScheme colorScheme) { return Icon(IconData(charCode), color: colorScheme.defaultForeground); } } Image createImageIcon(String url, {double size = defaultIconSize}) { return Image( image: AssetImage(url), height: size, width: size, ); } class Octicons { static const IconData bug = IconData(61714, fontFamily: 'Octicons'); static const IconData info = IconData(61778, fontFamily: 'Octicons'); static const IconData deviceMobile = IconData(61739, fontFamily: 'Octicons'); static const IconData fileZip = IconData(61757, fontFamily: 'Octicons'); static const IconData clippy = IconData(61724, fontFamily: 'Octicons'); static const IconData package = IconData(61812, fontFamily: 'Octicons'); static const IconData dashboard = IconData(61733, fontFamily: 'Octicons'); static const IconData pulse = IconData(61823, fontFamily: 'Octicons'); }
devtools/packages/devtools_app/lib/src/ui/icons.dart/0
{'file_path': 'devtools/packages/devtools_app/lib/src/ui/icons.dart', 'repo_id': 'devtools', 'token_count': 2580}
// 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_service/vm_service.dart'; import '../common_widgets.dart'; import '../table.dart'; import '../table_data.dart'; import '../utils.dart'; import 'vm_developer_common_widgets.dart'; import 'vm_developer_tools_screen.dart'; import 'vm_service_private_extensions.dart'; import 'vm_statistics_view_controller.dart'; class VMStatisticsView extends VMDeveloperView { const VMStatisticsView() : super( id, title: 'VM', icon: Icons.devices, ); static const id = 'vm-statistics'; @override Widget build(BuildContext context) => VMStatisticsViewBody(); } /// Displays general information about the state of the Dart VM. class VMStatisticsViewBody extends StatelessWidget { final controller = VMStatisticsViewController(); @override Widget build(BuildContext context) { return ValueListenableBuilder( valueListenable: controller.refreshing, builder: (context, refreshing, _) { return Column( children: [ Row( children: [ RefreshButton( onPressed: controller.refresh, ), ], ), Expanded( child: VMStatisticsWidget( controller: controller, ), ), ], ); }, ); } } class VMStatisticsWidget extends StatelessWidget { const VMStatisticsWidget({@required this.controller}); final VMStatisticsViewController controller; @override Widget build(BuildContext context) { return Row( children: [ Flexible( flex: 3, child: Column( children: [ Flexible( child: GeneralVMStatisticsWidget( controller: controller, ), ), Flexible( child: ProcessStatisticsWidget( controller: controller, ), ) ], ), ), Flexible( flex: 4, child: Column( children: [ Flexible( child: IsolatesPreviewWidget( controller: controller, ), ), Flexible( child: IsolatesPreviewWidget( controller: controller, systemIsolates: true, ), ), ], ), ), ], ); } } /// Displays general information about the VM instance, including: /// - VM debug name /// - Dart version /// - Embedder name /// - Start time /// - Profiler mode /// - Current memory consumption class GeneralVMStatisticsWidget extends StatelessWidget { const GeneralVMStatisticsWidget({@required this.controller}); final VMStatisticsViewController controller; @override Widget build(BuildContext context) { final vm = controller.vm; return VMInfoCard( title: 'VM', rowKeyValues: [ MapEntry('Name', vm?.name), MapEntry('Version', vm?.version), MapEntry('Embedder', vm?.embedder), MapEntry( 'Started', vm == null ? null : formatDateTime( DateTime.fromMillisecondsSinceEpoch(vm.startTime), ), ), MapEntry('Profiler Mode', vm?.profilerMode), MapEntry( 'Current Memory', prettyPrintBytes( vm?.currentMemory, includeUnit: true, ), ), ], ); } } /// Displays information about the current VM process, including: /// - Process ID /// - Host CPU /// - Target CPU /// - OS /// - Current and maximum resident set size (RSS) utilization /// - Zone allocator memory utilization class ProcessStatisticsWidget extends StatelessWidget { const ProcessStatisticsWidget({@required this.controller}); final VMStatisticsViewController controller; @override Widget build(BuildContext context) { final vm = controller.vm; return VMInfoCard( title: 'Process', rowKeyValues: [ MapEntry('PID', vm?.pid), MapEntry('Host CPU', vm == null ? null : '${vm.hostCPU} (${vm.architectureBits}-bits)'), MapEntry('Target CPU', vm?.targetCPU), MapEntry('Operating System', vm?.operatingSystem), MapEntry( 'Max Memory (RSS)', prettyPrintBytes( vm?.maxRSS, includeUnit: true, ), ), MapEntry( 'Current Memory (RSS)', prettyPrintBytes( vm?.currentRSS, includeUnit: true, ), ), MapEntry( 'Zone Memory', prettyPrintBytes( vm?.nativeZoneMemoryUsage, includeUnit: true, ), ), ], ); } } class _IsolateNameColumn extends ColumnData<Isolate> { _IsolateNameColumn() : super.wide('Name'); @override String getValue(Isolate i) => i.name; } class _IsolateIDColumn extends ColumnData<Isolate> { _IsolateIDColumn() : super.wide('ID'); @override String getValue(Isolate i) => i.number; } abstract class _IsolateMemoryColumn extends ColumnData<Isolate> { _IsolateMemoryColumn(String title) : super.wide(title); int getCapacity(Isolate i); int getUsage(Isolate i); @override String getValue(Isolate i) { return '${prettyPrintBytes(getUsage(i), includeUnit: true)} ' 'of ${prettyPrintBytes(getCapacity(i), includeUnit: true)}'; } } class _IsolateNewSpaceColumn extends _IsolateMemoryColumn { _IsolateNewSpaceColumn() : super('New Space'); @override int getCapacity(Isolate i) => i.newSpaceCapacity; @override int getUsage(Isolate i) => i.newSpaceUsage; } class _IsolateOldSpaceColumn extends _IsolateMemoryColumn { _IsolateOldSpaceColumn() : super('Old Space'); @override int getCapacity(Isolate i) => i.oldSpaceCapacity; @override int getUsage(Isolate i) => i.oldSpaceUsage; } class _IsolateHeapColumn extends _IsolateMemoryColumn { _IsolateHeapColumn() : super('Heap'); @override int getCapacity(Isolate i) => i.dartHeapCapacity; @override int getUsage(Isolate i) => i.dartHeapSize; } /// Displays general statistics about running isolates including: /// - Isolate debug name /// - VM Isolate ID /// - New / old space usage /// - Dart heap usage class IsolatesPreviewWidget extends StatelessWidget { IsolatesPreviewWidget({ @required this.controller, this.systemIsolates = false, }); final name = _IsolateNameColumn(); final number = _IsolateIDColumn(); final newSpace = _IsolateNewSpaceColumn(); final oldSpace = _IsolateOldSpaceColumn(); final heap = _IsolateHeapColumn(); List<ColumnData<Isolate>> get columns => [ name, number, newSpace, oldSpace, heap, ]; final VMStatisticsViewController controller; final bool systemIsolates; @override Widget build(BuildContext context) { final title = systemIsolates ? 'System Isolates' : 'Isolates'; final isolates = systemIsolates ? controller.systemIsolates : controller.isolates; return VMInfoCard( title: '$title (${isolates?.length ?? 0})', table: Flexible( child: FlatTable<Isolate>( columns: columns, data: isolates, keyFactory: (Isolate i) => ValueKey<String>(i.id), sortColumn: name, sortDirection: SortDirection.descending, onItemSelected: (_) => null, ), ), ); } }
devtools/packages/devtools_app/lib/src/vm_developer/vm_statistics_view.dart/0
{'file_path': 'devtools/packages/devtools_app/lib/src/vm_developer/vm_statistics_view.dart', 'repo_id': 'devtools', 'token_count': 3355}
// 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/devtools.dart' as devtools; import 'package:devtools_app/src/app.dart'; import 'package:devtools_app/src/extension_points/extensions_base.dart'; import 'package:devtools_app/src/extension_points/extensions_external.dart'; import 'package:devtools_app/src/globals.dart'; import 'package:devtools_app/src/service_manager.dart'; import 'package:flutter_test/flutter_test.dart'; import 'support/mocks.dart'; import 'support/utils.dart'; import 'support/wrappers.dart'; void main() { DevToolsAboutDialog aboutDialog; group('About Dialog', () { setUp(() { aboutDialog = DevToolsAboutDialog(); setGlobal(DevToolsExtensionPoints, ExternalDevToolsExtensionPoints()); setGlobal(ServiceConnectionManager, FakeServiceManager()); }); testWidgets('builds dialog', (WidgetTester tester) async { await tester.pumpWidget(wrap(aboutDialog)); expect(find.text('About DevTools'), findsOneWidget); }); testWidgets('DevTools section', (WidgetTester tester) async { await tester.pumpWidget(wrap(aboutDialog)); expect(find.text('About DevTools'), findsOneWidget); expect(findSubstring(aboutDialog, devtools.version), findsOneWidget); }); testWidgets('Feedback section', (WidgetTester tester) async { await tester.pumpWidget(wrap(aboutDialog)); expect(find.text('Feedback'), findsOneWidget); expect(findSubstring(aboutDialog, 'github.com/flutter/devtools'), findsOneWidget); }); }); }
devtools/packages/devtools_app/test/about_dialog_test.dart/0
{'file_path': 'devtools/packages/devtools_app/test/about_dialog_test.dart', 'repo_id': 'devtools', 'token_count': 576}
// 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/charts/flame_chart.dart'; import 'package:devtools_app/src/common_widgets.dart'; import 'package:devtools_app/src/globals.dart'; import 'package:devtools_app/src/profiler/cpu_profile_bottom_up.dart'; import 'package:devtools_app/src/profiler/cpu_profile_call_tree.dart'; import 'package:devtools_app/src/profiler/cpu_profile_controller.dart'; import 'package:devtools_app/src/profiler/cpu_profile_flame_chart.dart'; import 'package:devtools_app/src/profiler/cpu_profile_model.dart'; import 'package:devtools_app/src/profiler/cpu_profile_transformer.dart'; import 'package:devtools_app/src/profiler/cpu_profiler.dart'; import 'package:devtools_app/src/profiler/profiler_screen.dart'; import 'package:devtools_app/src/profiler/profiler_screen_controller.dart'; import 'package:devtools_app/src/service_manager.dart'; import 'package:devtools_testing/support/cpu_profile_test_data.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'support/mocks.dart'; import 'support/wrappers.dart'; void main() { CpuProfiler cpuProfiler; CpuProfileData cpuProfileData; CpuProfilerController controller; setUp(() async { final transformer = CpuProfileTransformer(); controller = CpuProfilerController(); cpuProfileData = CpuProfileData.parse(goldenCpuProfileDataJson); await transformer.processData(cpuProfileData); setGlobal(ServiceConnectionManager, FakeServiceManager()); }); group('CpuProfiler', () { const windowSize = Size(2000.0, 1000.0); final searchFieldKey = GlobalKey(debugLabel: 'test search field key'); testWidgetsWithWindowSize('builds for null cpuProfileData', windowSize, (WidgetTester tester) async { cpuProfiler = CpuProfiler( data: null, controller: controller, searchFieldKey: searchFieldKey, ); await tester.pumpWidget(wrap(cpuProfiler)); expect(find.byType(TabBar), findsOneWidget); expect(find.byKey(CpuProfiler.dataProcessingKey), findsOneWidget); expect(find.byType(CpuProfileFlameChart), findsNothing); expect(find.byType(CpuCallTreeTable), findsNothing); expect(find.byType(CpuBottomUpTable), findsNothing); expect(find.byType(UserTagDropdown), findsNothing); expect(find.byType(ExpandAllButton), findsNothing); expect(find.byType(CollapseAllButton), findsNothing); expect(find.byType(FlameChartHelpButton), findsNothing); expect(find.byKey(searchFieldKey), findsNothing); expect(find.byKey(CpuProfiler.flameChartTab), findsNothing); expect(find.byKey(CpuProfiler.callTreeTab), findsNothing); expect(find.byKey(CpuProfiler.bottomUpTab), findsNothing); expect(find.byKey(CpuProfiler.summaryTab), findsNothing); }); testWidgetsWithWindowSize('builds for empty cpuProfileData', windowSize, (WidgetTester tester) async { cpuProfileData = CpuProfileData.parse(emptyCpuProfileDataJson); cpuProfiler = CpuProfiler( data: cpuProfileData, controller: controller, searchFieldKey: searchFieldKey, ); await tester.pumpWidget(wrap(cpuProfiler)); expect(find.byType(TabBar), findsOneWidget); expect(find.byKey(CpuProfiler.dataProcessingKey), findsNothing); expect(find.byType(CpuProfileFlameChart), findsNothing); expect(find.byType(CpuCallTreeTable), findsNothing); expect(find.byType(CpuBottomUpTable), findsNothing); expect(find.byType(UserTagDropdown), findsNothing); expect(find.byType(ExpandAllButton), findsNothing); expect(find.byType(CollapseAllButton), findsNothing); expect(find.byType(FlameChartHelpButton), findsNothing); expect(find.byKey(searchFieldKey), findsNothing); expect(find.byKey(CpuProfiler.flameChartTab), findsNothing); expect(find.byKey(CpuProfiler.callTreeTab), findsNothing); expect(find.byKey(CpuProfiler.bottomUpTab), findsNothing); expect(find.byKey(CpuProfiler.summaryTab), findsNothing); }); testWidgetsWithWindowSize( 'builds for empty cpuProfileData with summary view', windowSize, (WidgetTester tester) async { cpuProfileData = CpuProfileData.parse(emptyCpuProfileDataJson); const summaryViewKey = Key('test summary view'); cpuProfiler = CpuProfiler( data: cpuProfileData, controller: controller, searchFieldKey: searchFieldKey, summaryView: const SizedBox(key: summaryViewKey), ); await tester.pumpWidget(wrap(cpuProfiler)); expect(find.byType(TabBar), findsOneWidget); expect(find.byKey(CpuProfiler.dataProcessingKey), findsNothing); expect(find.byType(CpuProfileFlameChart), findsNothing); expect(find.byType(CpuCallTreeTable), findsNothing); expect(find.byType(CpuBottomUpTable), findsNothing); expect(find.byType(UserTagDropdown), findsNothing); expect(find.byType(ExpandAllButton), findsNothing); expect(find.byType(CollapseAllButton), findsNothing); expect(find.byType(FlameChartHelpButton), findsNothing); expect(find.byKey(searchFieldKey), findsNothing); expect(find.byKey(CpuProfiler.flameChartTab), findsNothing); expect(find.byKey(CpuProfiler.callTreeTab), findsNothing); expect(find.byKey(CpuProfiler.bottomUpTab), findsNothing); expect(find.byKey(CpuProfiler.summaryTab), findsOneWidget); expect(find.byKey(summaryViewKey), findsOneWidget); }); testWidgetsWithWindowSize('builds for valid cpuProfileData', windowSize, (WidgetTester tester) async { cpuProfiler = CpuProfiler( data: cpuProfileData, controller: controller, searchFieldKey: searchFieldKey, ); await tester.pumpWidget(wrap(cpuProfiler)); expect(find.byType(TabBar), findsOneWidget); expect(find.byKey(CpuProfiler.dataProcessingKey), findsNothing); expect(find.byType(CpuBottomUpTable), findsOneWidget); expect(find.byType(UserTagDropdown), findsOneWidget); expect(find.byType(ExpandAllButton), findsOneWidget); expect(find.byType(CollapseAllButton), findsOneWidget); expect(find.byType(FlameChartHelpButton), findsNothing); expect(find.byKey(searchFieldKey), findsNothing); expect(find.byKey(CpuProfiler.flameChartTab), findsOneWidget); expect(find.byKey(CpuProfiler.callTreeTab), findsOneWidget); expect(find.byKey(CpuProfiler.bottomUpTab), findsOneWidget); expect(find.byKey(CpuProfiler.summaryTab), findsNothing); }); testWidgetsWithWindowSize( 'builds for valid cpuProfileData with summaryView', windowSize, (WidgetTester tester) async { const summaryViewKey = Key('test summary view'); cpuProfiler = CpuProfiler( data: cpuProfileData, controller: controller, searchFieldKey: searchFieldKey, summaryView: const SizedBox(key: summaryViewKey), ); await tester.pumpWidget(wrap(cpuProfiler)); expect(find.byType(TabBar), findsOneWidget); expect(find.byKey(CpuProfiler.dataProcessingKey), findsNothing); expect(find.byKey(summaryViewKey), findsOneWidget); expect(find.byType(UserTagDropdown), findsNothing); expect(find.byType(ExpandAllButton), findsNothing); expect(find.byType(CollapseAllButton), findsNothing); expect(find.byType(FlameChartHelpButton), findsNothing); expect(find.byKey(searchFieldKey), findsNothing); expect(find.byKey(CpuProfiler.flameChartTab), findsOneWidget); expect(find.byKey(CpuProfiler.callTreeTab), findsOneWidget); expect(find.byKey(CpuProfiler.bottomUpTab), findsOneWidget); expect(find.byKey(CpuProfiler.summaryTab), findsOneWidget); }); testWidgetsWithWindowSize('switches tabs', windowSize, (WidgetTester tester) async { cpuProfiler = CpuProfiler( data: cpuProfileData, controller: controller, searchFieldKey: searchFieldKey, ); await tester.pumpWidget(wrap(cpuProfiler)); expect(find.byType(TabBar), findsOneWidget); expect(find.byKey(CpuProfiler.dataProcessingKey), findsNothing); expect(find.byType(CpuProfileFlameChart), findsNothing); expect(find.byType(CpuCallTreeTable), findsNothing); expect(find.byType(CpuBottomUpTable), findsOneWidget); expect(find.byType(ExpandAllButton), findsOneWidget); expect(find.byType(CollapseAllButton), findsOneWidget); expect(find.byType(FlameChartHelpButton), findsNothing); expect(find.byKey(searchFieldKey), findsNothing); await tester.tap(find.text('Call Tree')); await tester.pumpAndSettle(); expect(find.byType(CpuProfileFlameChart), findsNothing); expect(find.byType(CpuCallTreeTable), findsOneWidget); expect(find.byType(CpuBottomUpTable), findsNothing); expect(find.byType(UserTagDropdown), findsOneWidget); expect(find.byType(ExpandAllButton), findsOneWidget); expect(find.byType(CollapseAllButton), findsOneWidget); expect(find.byType(FlameChartHelpButton), findsNothing); expect(find.byKey(searchFieldKey), findsNothing); await tester.tap(find.text('CPU Flame Chart')); await tester.pumpAndSettle(); expect(find.byType(CpuProfileFlameChart), findsOneWidget); expect(find.byType(CpuCallTreeTable), findsNothing); expect(find.byType(CpuBottomUpTable), findsNothing); expect(find.byType(UserTagDropdown), findsOneWidget); expect(find.byType(ExpandAllButton), findsNothing); expect(find.byType(CollapseAllButton), findsNothing); expect(find.byType(FlameChartHelpButton), findsOneWidget); expect(find.byKey(searchFieldKey), findsOneWidget); }); testWidgetsWithWindowSize( 'does not include search field without search field key', windowSize, (WidgetTester tester) async { cpuProfiler = CpuProfiler( data: cpuProfileData, controller: controller, // No search field key. // searchFieldKey: searchFieldKey, ); await tester.pumpWidget(wrap(cpuProfiler)); await tester.pumpAndSettle(); await tester.tap(find.text('CPU Flame Chart')); await tester.pumpAndSettle(); expect(find.byType(CpuProfileFlameChart), findsOneWidget); expect(find.byType(CpuCallTreeTable), findsNothing); expect(find.byType(CpuBottomUpTable), findsNothing); expect(find.byType(UserTagDropdown), findsOneWidget); expect(find.byType(ExpandAllButton), findsNothing); expect(find.byType(CollapseAllButton), findsNothing); expect(find.byType(FlameChartHelpButton), findsOneWidget); expect(find.byKey(searchFieldKey), findsNothing); }); testWidgetsWithWindowSize('can expand and collapse data', windowSize, (WidgetTester tester) async { cpuProfiler = CpuProfiler( data: cpuProfileData, controller: controller, searchFieldKey: searchFieldKey, ); await tester.pumpWidget(wrap(cpuProfiler)); await tester.tap(find.text('Call Tree')); await tester.pumpAndSettle(); expect(cpuProfileData.cpuProfileRoot.isExpanded, isFalse); await tester.tap(find.byType(ExpandAllButton)); expect(cpuProfiler.callTreeRoots.first.isExpanded, isTrue); await tester.tap(find.byType(CollapseAllButton)); expect(cpuProfiler.callTreeRoots.first.isExpanded, isFalse); await tester.tap(find.text('Bottom Up')); await tester.pumpAndSettle(); for (final root in cpuProfiler.bottomUpRoots) { expect(root.isExpanded, isFalse); } await tester.tap(find.byType(ExpandAllButton)); for (final root in cpuProfiler.bottomUpRoots) { expect(root.isExpanded, isTrue); } await tester.tap(find.byType(CollapseAllButton)); for (final root in cpuProfiler.bottomUpRoots) { expect(root.isExpanded, isFalse); } }); group('UserTag filters', () { ProfilerScreenController controller; setUp(() async { controller = ProfilerScreenController(); cpuProfileData = CpuProfileData.parse(cpuProfileDataWithUserTagsJson); await controller.cpuProfilerController.transformer .processData(cpuProfileData); // Call this to force the value of `_dataByTag[userTagNone]` to be set. controller.cpuProfilerController.loadProcessedData(cpuProfileData); }); testWidgetsWithWindowSize('can filter data by user tag', windowSize, (WidgetTester tester) async { // We need to pump the entire `ProfilerScreenBody` widget because the // CpuProfiler widget has `cpuProfileData` passed in from there, and // CpuProfiler needs to be rebuilt on data updates. await tester.pumpWidget(wrapWithControllers( const ProfilerScreenBody(), profiler: controller, )); expect(controller.cpuProfilerController.userTags.length, equals(3)); expect(find.byType(UserTagDropdown), findsOneWidget); // There is a Text widget and a RichText widget. expect(find.text('Filter by tag: userTagA'), findsWidgets); expect(find.text('Filter by tag: userTagB'), findsWidgets); expect(find.text('Filter by tag: userTagC'), findsWidgets); await tester.tap(find.text('CPU Flame Chart')); await tester.pumpAndSettle(); expect(find.byType(CpuProfileFlameChart), findsOneWidget); expect( controller .cpuProfileData.profileMetaData.time.duration.inMicroseconds, equals(250), ); expect(find.text('Frame1'), findsOneWidget); expect(find.text('Frame2'), findsOneWidget); expect(find.text('Frame3'), findsOneWidget); expect(find.text('Frame4'), findsOneWidget); expect(find.text('Frame5'), findsOneWidget); expect(find.text('Frame6'), findsOneWidget); await tester.tap(find.byType(UserTagDropdown)); await tester.pumpAndSettle(); await tester.tap(find.text('Filter by tag: userTagA').last); await tester.pumpAndSettle(); expect( controller .cpuProfileData.profileMetaData.time.duration.inMicroseconds, equals(100), ); expect(find.text('Frame1'), findsOneWidget); expect(find.text('Frame2'), findsOneWidget); expect(find.text('Frame3'), findsOneWidget); expect(find.text('Frame4'), findsNothing); expect(find.text('Frame5'), findsOneWidget); expect(find.text('Frame6'), findsNothing); await tester.tap(find.byType(UserTagDropdown)); await tester.pumpAndSettle(); await tester.tap(find.text('Filter by tag: userTagB').last); await tester.pumpAndSettle(); expect( controller .cpuProfileData.profileMetaData.time.duration.inMicroseconds, equals(50), ); expect(find.text('Frame1'), findsOneWidget); expect(find.text('Frame2'), findsOneWidget); expect(find.text('Frame3'), findsNothing); expect(find.text('Frame4'), findsOneWidget); expect(find.text('Frame5'), findsNothing); expect(find.text('Frame6'), findsNothing); await tester.tap(find.byType(UserTagDropdown)); await tester.pumpAndSettle(); await tester.tap(find.text('Filter by tag: userTagC').last); await tester.pumpAndSettle(); expect( controller .cpuProfileData.profileMetaData.time.duration.inMicroseconds, equals(100), ); expect(find.text('Frame1'), findsOneWidget); expect(find.text('Frame2'), findsNothing); expect(find.text('Frame3'), findsNothing); expect(find.text('Frame4'), findsNothing); expect(find.text('Frame5'), findsOneWidget); expect(find.text('Frame6'), findsOneWidget); }); }); }); }
devtools/packages/devtools_app/test/cpu_profiler_test.dart/0
{'file_path': 'devtools/packages/devtools_app/test/cpu_profiler_test.dart', 'repo_id': 'devtools', 'token_count': 6203}
// 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'; void main() { print('starting empty app'); // Don't exit until it's indicated we should by the controller. Timer(const Duration(days: 1), () {}); }
devtools/packages/devtools_app/test/fixtures/empty_app.dart/0
{'file_path': 'devtools/packages/devtools_app/test/fixtures/empty_app.dart', 'repo_id': 'devtools', 'token_count': 98}
// 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:devtools_app/src/config_specific/import_export/import_export.dart'; import 'package:devtools_app/src/utils.dart'; import 'package:flutter_test/flutter_test.dart'; import 'support/wrappers.dart'; void main() async { group('ImportControllerTest', () { ImportController importController; TestNotifications notifications; setUp(() { notifications = TestNotifications(); importController = ImportController(notifications, (_) {}); }); test('importData pushes proper notifications', () async { expect(notifications.messages, isEmpty); importController.importData(nonDevToolsFileJson); expect(notifications.messages.length, equals(1)); expect(notifications.messages, contains(nonDevToolsFileMessage)); await Future.delayed(const Duration( milliseconds: ImportController.repeatImportTimeBufferMs)); importController.importData(nonDevToolsFileJsonWithListData); expect(notifications.messages.length, equals(2)); expect(notifications.messages, contains(nonDevToolsFileMessage)); await Future.delayed(const Duration( milliseconds: ImportController.repeatImportTimeBufferMs)); importController.importData(devToolsFileJson); expect(notifications.messages.length, equals(3)); expect( notifications.messages, contains(attemptingToImportMessage('example')), ); }); }); } final nonDevToolsFileJson = DevToolsJsonFile( name: 'nonDevToolsFileJson', lastModifiedTime: DateTime.fromMicrosecondsSinceEpoch(1000), data: <String, dynamic>{}, ); final nonDevToolsFileJsonWithListData = DevToolsJsonFile( name: 'nonDevToolsFileJsonWithListData', lastModifiedTime: DateTime.fromMicrosecondsSinceEpoch(1000), data: <Map<String, dynamic>>[], ); final devToolsFileJson = DevToolsJsonFile( name: 'devToolsFileJson', lastModifiedTime: DateTime.fromMicrosecondsSinceEpoch(2000), data: <String, dynamic>{ 'devToolsSnapshot': true, 'activeScreenId': 'example', 'example': {'title': 'example custom tools'} }, );
devtools/packages/devtools_app/test/import_export_test.dart/0
{'file_path': 'devtools/packages/devtools_app/test/import_export_test.dart', 'repo_id': 'devtools', 'token_count': 748}
// 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/globals.dart'; import 'package:devtools_app/src/landing_screen.dart'; import 'package:devtools_app/src/service_manager.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter_test/flutter_test.dart'; import 'support/mocks.dart'; import 'support/wrappers.dart'; void main() { setUp(() { setGlobal(ServiceConnectionManager, FakeServiceManager()); }); testWidgetsWithWindowSize( 'Landing screen displays without error', const Size(2000.0, 2000.0), (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(wrap(LandingScreenBody())); expect(find.text('Connect to a Running App'), findsOneWidget); expect(find.text('App Size Tooling'), findsOneWidget); }); }
devtools/packages/devtools_app/test/landing_screen_test.dart/0
{'file_path': 'devtools/packages/devtools_app/test/landing_screen_test.dart', 'repo_id': 'devtools', 'token_count': 314}
// 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. @TestOn('vm') import 'dart:convert'; import 'package:devtools_app/src/globals.dart'; import 'package:devtools_app/src/inspector/inspector_service.dart'; import 'package:devtools_app/src/logging/logging_controller.dart'; import 'package:devtools_app/src/service_manager.dart'; import 'package:devtools_app/src/ui/filter.dart'; import 'package:flutter_test/flutter_test.dart'; import 'inspector_screen_test.dart'; import 'support/mocks.dart'; import 'support/utils.dart'; void main() { group('LoggingController', () { LoggingController controller; void addStdoutData(String message) { controller.log(LogData( 'stdout', jsonEncode({'kind': 'stdout', 'message': message}), 0, summary: message, )); } void addGcData(String message) { controller.log(LogData( 'gc', jsonEncode({'kind': 'gc', 'message': message}), 0, summary: message, )); } setUp(() async { setGlobal( ServiceConnectionManager, FakeServiceManager(), ); final InspectorService inspectorService = MockInspectorService(); controller = LoggingController(inspectorService: inspectorService); }); test('initial state', () { expect(controller.data, isEmpty); expect(controller.filteredData.value, isEmpty); expect(controller.activeFilter.value, isNull); }); test('receives data', () { expect(controller.data, isEmpty); addStdoutData('Abc.'); expect(controller.data, isNotEmpty); expect(controller.filteredData.value, isNotEmpty); expect(controller.data.first.summary, contains('Abc')); }); test('clear', () { addStdoutData('Abc.'); expect(controller.data, isNotEmpty); expect(controller.filteredData.value, isNotEmpty); controller.clear(); expect(controller.data, isEmpty); expect(controller.filteredData.value, isEmpty); }); test('matchesForSearch', () { addStdoutData('abc'); addStdoutData('def'); addStdoutData('abc ghi'); addGcData('gc1'); addGcData('gc2'); expect(controller.filteredData.value, hasLength(5)); expect(controller.matchesForSearch('abc').length, equals(2)); expect(controller.matchesForSearch('ghi').length, equals(1)); expect(controller.matchesForSearch('abcd').length, equals(0)); expect(controller.matchesForSearch('').length, equals(0)); // Search by event kind. expect(controller.matchesForSearch('stdout').length, equals(3)); expect(controller.matchesForSearch('gc').length, equals(2)); // Search with incorrect case. expect(controller.matchesForSearch('STDOUT').length, equals(3)); }); test('matchesForSearch sets isSearchMatch property', () { addStdoutData('abc'); addStdoutData('def'); addStdoutData('abc ghi'); addGcData('gc1'); addGcData('gc2'); expect(controller.filteredData.value, hasLength(5)); var matches = controller.matchesForSearch('abc'); expect(matches.length, equals(2)); verifyIsSearchMatch(controller.filteredData.value, matches); matches = controller.matchesForSearch('gc'); expect(matches.length, equals(2)); verifyIsSearchMatch(controller.filteredData.value, matches); }); test('filterData', () { addStdoutData('abc'); addStdoutData('def'); addStdoutData('abc ghi'); addGcData('gc1'); addGcData('gc2'); expect(controller.data, hasLength(5)); expect(controller.filteredData.value, hasLength(5)); controller.filterData(QueryFilter.parse('abc', controller.filterArgs)); expect(controller.data, hasLength(5)); expect(controller.filteredData.value, hasLength(2)); controller.filterData(QueryFilter.parse('def', controller.filterArgs)); expect(controller.data, hasLength(5)); expect(controller.filteredData.value, hasLength(1)); controller.filterData( QueryFilter.parse('k:stdout abc def', controller.filterArgs)); expect(controller.data, hasLength(5)); expect(controller.filteredData.value, hasLength(3)); controller .filterData(QueryFilter.parse('kind:gc', controller.filterArgs)); expect(controller.data, hasLength(5)); expect(controller.filteredData.value, hasLength(2)); controller .filterData(QueryFilter.parse('k:stdout abc', controller.filterArgs)); expect(controller.data, hasLength(5)); expect(controller.filteredData.value, hasLength(2)); controller.filterData(QueryFilter.parse('-k:gc', controller.filterArgs)); expect(controller.data, hasLength(5)); expect(controller.filteredData.value, hasLength(3)); controller .filterData(QueryFilter.parse('-k:gc,stdout', controller.filterArgs)); expect(controller.data, hasLength(5)); expect(controller.filteredData.value, hasLength(0)); controller.filterData(QueryFilter.parse( 'k:gc,stdout,stdin,flutter.frame', controller.filterArgs)); expect(controller.data, hasLength(5)); expect(controller.filteredData.value, hasLength(5)); controller.filterData(null); expect(controller.data, hasLength(5)); expect(controller.filteredData.value, hasLength(5)); }); }); group('LogData', () { test( 'pretty prints when details are json, and returns its details otherwise.', () { final nonJson = LogData('some kind', 'Not json', 0); final json = LogData( 'some kind', '{"firstValue": "value", "otherValue": "value2"}', 1); final nullDetails = LogData('some kind', null, 1); const prettyJson = '{\n' ' "firstValue": "value",\n' ' "otherValue": "value2"\n' '}'; expect(json.prettyPrinted, prettyJson); expect(nonJson.prettyPrinted, 'Not json'); expect(nullDetails.prettyPrinted, null); }); }); }
devtools/packages/devtools_app/test/logging_controller_test.dart/0
{'file_path': 'devtools/packages/devtools_app/test/logging_controller_test.dart', 'repo_id': 'devtools', 'token_count': 2371}
// 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:devtools_app/src/preferences.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { group('PreferencesController', () { PreferencesController controller; setUp(() { controller = PreferencesController(); }); test('has value', () { expect(controller.darkModeTheme.value, isNotNull); expect(controller.denseModeEnabled.value, isNotNull); }); test('toggleDarkModeTheme', () { bool valueChanged = false; final originalValue = controller.darkModeTheme.value; controller.darkModeTheme.addListener(() { valueChanged = true; }); controller.toggleDarkModeTheme(!controller.darkModeTheme.value); expect(valueChanged, isTrue); expect(controller.darkModeTheme.value, isNot(originalValue)); }); test('toggleVmDeveloperMode', () { bool valueChanged = false; final originalValue = controller.vmDeveloperModeEnabled.value; controller.vmDeveloperModeEnabled.addListener(() { valueChanged = true; }); controller .toggleVmDeveloperMode(!controller.vmDeveloperModeEnabled.value); expect(valueChanged, isTrue); expect(controller.vmDeveloperModeEnabled.value, isNot(originalValue)); }); test('toggleDenseMode', () { bool valueChanged = false; final originalValue = controller.denseModeEnabled.value; controller.denseModeEnabled.addListener(() { valueChanged = true; }); controller.toggleDenseMode(!controller.denseModeEnabled.value); expect(valueChanged, isTrue); expect(controller.denseModeEnabled.value, isNot(originalValue)); }); }); }
devtools/packages/devtools_app/test/preferences_controller_test.dart/0
{'file_path': 'devtools/packages/devtools_app/test/preferences_controller_test.dart', 'repo_id': 'devtools', 'token_count': 639}
const smallInstructionSizes = ''' [ { "l": "dart:_internal", "c": "_CastListBase", "n": "[Optimized] getRange", "s": 112 }, { "l": "dart:_internal", "c": "CastIterable", "n": "[Optimized] new CastIterable.", "s": 216 }, { "l": "dart:_internal", "c": "CastIterable", "n": "[Stub] Allocate CastIterable", "s": 12 }, { "l": "dart:core", "c": "List", "n": "[Optimized] castFrom", "s": 120 } ] ''';
devtools/packages/devtools_app/test/support/app_size_test_data/small_sizes.dart/0
{'file_path': 'devtools/packages/devtools_app/test/support/app_size_test_data/small_sizes.dart', 'repo_id': 'devtools', 'token_count': 286}
// 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:io'; import 'package:devtools_app/src/charts/treemap.dart'; import 'package:devtools_app/src/globals.dart'; import 'package:devtools_app/src/service_manager.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'support/app_size_test_data/apk_analysis.dart'; import 'support/app_size_test_data/new_v8.dart'; import 'support/app_size_test_data/sizes.dart'; import 'support/app_size_test_data/small_sizes.dart'; import 'support/mocks.dart'; import 'support/utils.dart'; import 'support/wrappers.dart'; void main() { TreemapNode root; void changeRoot(TreemapNode newRoot) { root = newRoot; } // Pump treemap widget with tree built with test data. Future<void> pumpTreemapWidget(WidgetTester tester, Key treemapKey) async { await tester.pumpWidget(wrap(LayoutBuilder( key: treemapKey, builder: (context, constraints) { return Treemap.fromRoot( rootNode: root, levelsVisible: 2, isOutermostLevel: true, width: constraints.maxWidth, height: constraints.maxHeight, onRootChangedCallback: changeRoot, ); }, ))); await tester.pumpAndSettle(); } const windowSize = Size(2225.0, 1000.0); setUp(() { setGlobal(ServiceConnectionManager, FakeServiceManager()); }); group('TreemapNode', () { final child1 = TreemapNode(name: 'package:child1'); final child2 = TreemapNode(name: 'package:child2'); final grandchild1 = TreemapNode(name: 'non-package-grandchild'); final grandchild2 = TreemapNode(name: 'package:grandchild2'); final greatGrandchild1 = TreemapNode(name: 'package:greatGrandchild1'); final greatGrandchild2 = TreemapNode(name: 'package:greatGrandchild2'); final testRoot = TreemapNode(name: 'libapp.so (Dart AOT)') ..addAllChildren([ child1 ..addChild( grandchild1 ..addChild( greatGrandchild1, ), ), child2 ..addChild( grandchild2 ..addChild( greatGrandchild2, ), ), ]); final nodeWithDuplicatePackageNameGrandchild = TreemapNode(name: 'grandchild'); final nodeWithDuplicatePackageNameChild1 = TreemapNode(name: 'package:a'); final nodeWithDuplicatePackageNameChild2 = TreemapNode(name: '<Type>'); final nodeWithDuplicatePackageName = TreemapNode(name: 'package:a'); TreemapNode(name: 'libapp.so (Dart AOT)') ..addChild(nodeWithDuplicatePackageName ..addAllChildren([ nodeWithDuplicatePackageNameChild1 ..addChild(nodeWithDuplicatePackageNameGrandchild), nodeWithDuplicatePackageNameChild2, ])); final dartLibraryChild = TreemapNode(name: 'dart lib child'); final dartLibraryNode = TreemapNode(name: 'dart:core'); TreemapNode(name: 'libapp.so (Dart AOT)') ..addChild(dartLibraryNode..addChild(dartLibraryChild)); test('packagePath returns correct values', () { expect(testRoot.packagePath(), equals([])); expect(grandchild1.packagePath(), equals(['package:child1'])); expect(grandchild2.packagePath(), equals(['package:child2', 'package:grandchild2'])); expect(greatGrandchild1.packagePath(), equals(['package:child1', 'package:greatGrandchild1'])); expect( greatGrandchild2.packagePath(), equals([ 'package:child2', 'package:grandchild2', 'package:greatGrandchild2', ])); }); test('packagePath returns correct values for duplicate package name', () { expect(nodeWithDuplicatePackageNameGrandchild.packagePath(), equals(['package:a'])); }); test('packagePath returns correct value for dart library node', () { expect(dartLibraryChild.packagePath(), equals(['dart:core'])); }); }); group('Treemap from small instruction sizes', () { setUp(() async { root = await loadSnapshotJsonAsTree(smallInstructionSizes); }); testWidgetsWithWindowSize( 'zooms in down to a node without children', windowSize, (WidgetTester tester) async { const treemapKey = Key('Treemap'); await pumpTreemapWidget(tester, treemapKey); String text = 'dart:_internal [0.3 KB]'; expect(find.text(text), findsOneWidget); await tester.tap(find.text(text)); await tester.pumpAndSettle(); await pumpTreemapWidget(tester, treemapKey); text = 'CastIterable [0.2 KB]'; expect(find.text(text), findsOneWidget); await tester.tap(find.text(text)); await tester.pumpAndSettle(); await pumpTreemapWidget(tester, treemapKey); text = 'new CastIterable.\n[0.2 KB]'; expect(find.text(text), findsOneWidget); await tester.tap(find.text(text)); await tester.pumpAndSettle(); await pumpTreemapWidget(tester, treemapKey); // TODO(jacobr): what text should be found in this case? // expect(find.text('new CastIterable. [0.2 KB]'), findsOneWidget); }, ); }); group('Treemap from instruction sizes', () { setUp(() async { root = await loadSnapshotJsonAsTree(instructionSizes); }); testWidgetsWithWindowSize( 'builds treemap with expected data', windowSize, (WidgetTester tester) async { const treemapKey = Key('Treemap'); await pumpTreemapWidget(tester, treemapKey); expect(find.byKey(treemapKey), findsOneWidget); await expectLater( find.byKey(treemapKey), matchesGoldenFile('goldens/treemap_sizes.png'), ); }, skip: kIsWeb || !Platform.isMacOS, ); }); group('Treemap from v8 snapshot', () { setUp(() async { root = await loadSnapshotJsonAsTree(newV8); }); testWidgetsWithWindowSize( 'builds treemap with expected data', windowSize, (WidgetTester tester) async { const treemapKey = Key('Treemap'); await pumpTreemapWidget(tester, treemapKey); expect(find.byKey(treemapKey), findsOneWidget); await expectLater( find.byKey(treemapKey), matchesGoldenFile('goldens/treemap_v8.png'), ); // Await delay for golden comparison. await tester.pumpAndSettle(const Duration(seconds: 2)); }, skip: kIsWeb || !Platform.isMacOS, ); }); group('Treemap from APK analysis', () { setUp(() async { root = await loadSnapshotJsonAsTree(apkAnalysis); }); testWidgetsWithWindowSize( 'builds treemap with expected data', windowSize, (WidgetTester tester) async { const treemapKey = Key('Treemap'); await pumpTreemapWidget(tester, treemapKey); expect(find.byKey(treemapKey), findsOneWidget); await expectLater( find.byKey(treemapKey), matchesGoldenFile('goldens/treemap_apk.png'), ); // Await delay for golden comparison. await tester.pumpAndSettle(const Duration(seconds: 2)); }, skip: kIsWeb || !Platform.isMacOS, ); }); }
devtools/packages/devtools_app/test/treemap_test.dart/0
{'file_path': 'devtools/packages/devtools_app/test/treemap_test.dart', 'repo_id': 'devtools', 'token_count': 3124}
name: devtools_shared description: Package of shared structures between devtools_app and devtools_server. # Note: this version should only be updated by running tools/update_version.dart # that updates all versions of packages from packages/devtools. version: 2.3.3-dev.1 homepage: https://github.com/flutter/devtools environment: sdk: '>=2.12.0 <3.0.0' dependencies: path: ^1.8.0 shelf: ^1.1.0 usage: ^4.0.0 vm_service: ^7.1.0
devtools/packages/devtools_shared/pubspec.yaml/0
{'file_path': 'devtools/packages/devtools_shared/pubspec.yaml', 'repo_id': 'devtools', 'token_count': 159}
// 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'; // Unused class in the sample application that is a widget. class MyOtherWidget extends StatelessWidget { @override Widget build(BuildContext context) { return const SizedBox(); } } // Unused class in the sample application that is not a widget. class NotAWidget {}
devtools/packages/devtools_testing/fixtures/flutter_app/lib/src/other_classes.dart/0
{'file_path': 'devtools/packages/devtools_testing/fixtures/flutter_app/lib/src/other_classes.dart', 'repo_id': 'devtools', 'token_count': 133}
// 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. // ignore_for_file: implementation_imports import 'dart:async'; import 'dart:math'; import 'package:devtools_app/src/inspector/inspector_tree.dart'; import 'package:devtools_app/src/ui/icons.dart'; import 'package:flutter/material.dart'; const double fakeRowWidth = 200.0; class FakeInspectorTree extends InspectorTreeController with InspectorTreeFixedRowHeightController { FakeInspectorTree(); final List<Rect> scrollToRequests = []; @override InspectorTreeNode createNode() { return InspectorTreeNode(); } @override Rect getBoundingBox(InspectorTreeRow row) { return Rect.fromLTWH( getDepthIndent(row.depth), getRowY(row.index), fakeRowWidth, rowHeight, ); } @override void scrollToRect(Rect targetRect) { scrollToRequests.add(targetRect); } Completer<void> setStateCalled; /// Hack to allow tests to wait until the next time this UI is updated. Future<void> get nextUiFrame { setStateCalled ??= Completer(); return setStateCalled.future; } @override void setState(VoidCallback fn) { // Execute async calls synchronously for faster test execution. fn(); setStateCalled?.complete(null); setStateCalled = null; } // Debugging string to make it easy to write integration tests. String toStringDeep( {bool hidePropertyLines = false, bool includeTextStyles = false}) { if (root == null) return '<empty>\n'; // Visualize the ticks computed for this node so that bugs in the tick // computation code will result in rendering artifacts in the text output. final StringBuffer sb = StringBuffer(); for (int i = 0; i < numRows; i++) { final row = getCachedRow(i); if (hidePropertyLines && row?.node?.diagnostic?.isProperty == true) { continue; } int last = 0; for (int tick in row.ticks) { // Visualize the line to parent if there is one. if (tick - last > 0) { sb.write(' ' * (tick - last)); } if (tick == (row.depth - 1) && row.lineToParent) { sb.write('├─'); } else { sb.write('│ '); } last = max(tick, 1); } final int delta = row.depth - last; if (delta > 0) { if (row.lineToParent) { if (delta > 1 || last == 0) { sb.write(' ' * (delta - 1)); sb.write('└─'); } else { sb.write('──'); } } else { sb.write(' ' * delta); } } final InspectorTreeNode node = row?.node; final diagnostic = node?.diagnostic; if (diagnostic == null) { sb.write('<empty>\n'); continue; } if (node.showExpandCollapse) { if (node.isExpanded) { sb.write('▼'); } else { sb.write('▶'); } } final icon = node.diagnostic.icon; if (icon is CustomIcon) { sb.write('[${icon.text}]'); } else if (icon is ColorIcon) { sb.write('[${icon.color.value}]'); } else if (icon is Image) { sb.write('[${(icon.image as AssetImage).assetName}]'); } sb.write(node.diagnostic.description); // // TODO(jacobr): optionally visualize colors as well. // if (entry.text != null) { // if (entry.textStyle != null && includeTextStyles) { // final String shortStyle = styles.debugStyleNames[entry.textStyle]; // if (shortStyle == null) { // // Display the style a little like an html style. // sb.write('<style ${entry.textStyle}>${entry.text}</style>'); // } else { // if (shortStyle == '') { // // Omit the default text style completely for readability of // // the debug output. // sb.write(entry.text); // } else { // sb.write('<$shortStyle>${entry.text}</$shortStyle>'); // } // } // } else { // sb.write(entry.text); // } // } if (row.isSelected) { sb.write(' <-- selected'); } sb.write('\n'); } return sb.toString(); } }
devtools/packages/devtools_testing/lib/support/fake_inspector_tree.dart/0
{'file_path': 'devtools/packages/devtools_testing/lib/support/fake_inspector_tree.dart', 'repo_id': 'devtools', 'token_count': 1894}
import 'package:dio/dio.dart'; var dio=new Dio();
dio/example/flutter_example/lib/http.dart/0
{'file_path': 'dio/example/flutter_example/lib/http.dart', 'repo_id': 'dio', 'token_count': 22}
import 'dart:io'; import '../interceptor.dart'; import '../options.dart'; import '../response.dart'; import '../dio_error.dart'; import 'package:cookie_jar/cookie_jar.dart'; class CookieManager extends Interceptor { /// Cookie manager for http requests。Learn more details about /// CookieJar please refer to [cookie_jar](https://github.com/flutterchina/cookie_jar) final CookieJar cookieJar; static const invalidCookieValue = "_invalid_"; /// Dart SDK will cause an exception When response cookie's value is empty, /// eg. 'Set-Cookie: session=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT' /// /// This is a bug of Dart SDK: https://github.com/dart-lang/sdk/issues/35804 /// So, we should normalize the cookie value before this bug is fixed. bool needNormalize = false; CookieManager(this.cookieJar) { // Set `needNormalize` value by Duck test try { Cookie.fromSetCookieValue("k=;"); } catch (e) { needNormalize = true; } } @override onRequest(RequestOptions options) { var cookies = cookieJar.loadForRequest(options.uri); cookies.removeWhere((cookie) => cookie.value == invalidCookieValue && cookie.expires.isBefore(DateTime.now())); cookies.addAll(options.cookies); String cookie = getCookies(cookies); if (cookie.isNotEmpty) options.headers[HttpHeaders.cookieHeader] = cookie; } @override onResponse(Response response) => _saveCookies(response); @override onError(DioError err) => _saveCookies(err.response); _saveCookies(Response response) { if (response != null && response.headers != null) { List<String> cookies = response.headers[HttpHeaders.setCookieHeader]; if (cookies != null) { if (needNormalize) { var _cookies = normalizeCookies(cookies); cookies ..clear() ..addAll(_cookies); } cookieJar.saveFromResponse( response.request.uri, cookies.map((str) => Cookie.fromSetCookieValue(str)).toList(), ); } } } static String getCookies(List<Cookie> cookies) { return cookies.map((cookie) => "${cookie.name}=${cookie.value}").join('; '); } static List<String> normalizeCookies(List<String> cookies) { if (cookies != null) { const String expires = " Expires=Thu, 01 Jan 1970 00:00:00 GMT"; return cookies.map((cookie) { var _cookie = cookie.split(";"); var kv = _cookie.first?.split("="); if (kv != null && kv[1].isEmpty) { kv[1] = invalidCookieValue; _cookie[0] = kv.join('='); if (_cookie.length > 1) { int i = 1; while (i < _cookie.length) { if (_cookie[i].trim().toLowerCase().startsWith("expires")) { _cookie[i] = expires; break; } ++i; } if (i == _cookie.length) { _cookie.add(expires); } } } return _cookie.join(";"); }).toList(); } return []; } }
dio/package_src/lib/src/interceptors/cookie_mgr.dart/0
{'file_path': 'dio/package_src/lib/src/interceptors/cookie_mgr.dart', 'repo_id': 'dio', 'token_count': 1283}
export 'network/firebase.dart';
duck_duck_shop/lib/data/network.dart/0
{'file_path': 'duck_duck_shop/lib/data/network.dart', 'repo_id': 'duck_duck_shop', 'token_count': 11}
# TYPE - name: "bug" color: "d73a4a" description: "Something isn't working" - name: "enhancement" color: "2ec9ff" description: "New feature or request" - name: "documentation" color: "0075ca" description: "Improvements or additions to documentation" - name: "question" color: "ff419d" description: "Question" # ACTION - name: "help wanted" color: "0e8a16" description: "Extra attention is needed" - name: "feedback wanted" color: "0e8a16" description: "Looking for feedback from the community" - name: "waiting for response" color: "fbca04" description: "Waiting for follow up" - name: "investigating" color: "fbca04" description: "Investigating the issue" - name: "good first issue" color: "008672" description: "Investigating the issue" - name: "dependency" color: "ff7619" description: "This issue has an external dependency" # NEGATIVE - name: "duplicate" color: "eeeeee" description: "This issue or pull request already exists" - name: "wontfix" color: "eeeeee" description: "This will not be worked on"
effective_dart/.github/labels.yaml/0
{'file_path': 'effective_dart/.github/labels.yaml', 'repo_id': 'effective_dart', 'token_count': 358}
# 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. # See https://github.com/actions/labeler/blob/main/README.md for docs. 'affects: desktop': - changed-files: - any-glob-to-any-file: - shell/platform/darwin/common/**/* - shell/platform/darwin/macos/**/* - shell/platform/linux/**/* - shell/platform/windows/**/* embedder: - changed-files: - any-glob-to-any-file: - shell/platform/embedder 'e: impeller': - changed-files: - any-glob-to-any-file: - impeller/**/* platform-android: - changed-files: - any-glob-to-any-file: - shell/platform/android/**/* platform-ios: - changed-files: - any-glob-to-any-file: - shell/platform/darwin/common/**/* - shell/platform/darwin/ios/**/* platform-fuchsia: - changed-files: - any-glob-to-any-file: - shell/platform/fuchsia/**/* platform-linux: - changed-files: - any-glob-to-any-file: - shell/platform/linux/**/* platform-macos: - changed-files: - any-glob-to-any-file: - shell/platform/darwin/common/**/* - shell/platform/darwin/macos/**/* platform-web: - changed-files: - any-glob-to-any-file: - lib/web_ui/**/* - '**/web_sdk/**/*' platform-windows: - changed-files: - any-glob-to-any-file: - shell/platform/windows/**/*
engine/.github/labeler.yml/0
{'file_path': 'engine/.github/labeler.yml', 'repo_id': 'engine', 'token_count': 609}
// 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; /// A reference to a byte range within a GPU-resident [Buffer]. class BufferView { /// The buffer of this view. final Buffer buffer; /// The start of the view, in bytes starting from the beginning of the /// [buffer]. final int offsetInBytes; /// The length of the view. final int lengthInBytes; /// Create a new view into a buffer on the GPU. const BufferView(this.buffer, {required this.offsetInBytes, required this.lengthInBytes}); } /// A buffer that can be referenced by commands on the GPU. mixin Buffer { void _bindAsVertexBuffer(RenderPass renderPass, int offsetInBytes, int lengthInBytes, int vertexCount); void _bindAsIndexBuffer(RenderPass renderPass, int offsetInBytes, int lengthInBytes, IndexType indexType, int indexCount); bool _bindAsUniform(RenderPass renderPass, UniformSlot slot, int offsetInBytes, int lengthInBytes); } /// [DeviceBuffer] is a region of memory allocated on the device heap /// (GPU-resident memory). base class DeviceBuffer extends NativeFieldWrapperClass1 with Buffer { bool _valid = false; get isValid { return _valid; } /// Creates a new DeviceBuffer. DeviceBuffer._initialize( GpuContext gpuContext, StorageMode storageMode, int sizeInBytes) : storageMode = storageMode, sizeInBytes = sizeInBytes { _valid = _initialize(gpuContext, storageMode.index, sizeInBytes); } /// Creates a new host visible DeviceBuffer with data copied from the host. DeviceBuffer._initializeWithHostData(GpuContext gpuContext, ByteData data) : storageMode = StorageMode.hostVisible, sizeInBytes = data.lengthInBytes { _valid = _initializeWithHostData(gpuContext, data); } final StorageMode storageMode; final int sizeInBytes; @override void _bindAsVertexBuffer(RenderPass renderPass, int offsetInBytes, int lengthInBytes, int vertexCount) { renderPass._bindVertexBufferDevice( this, offsetInBytes, lengthInBytes, vertexCount); } @override void _bindAsIndexBuffer(RenderPass renderPass, int offsetInBytes, int lengthInBytes, IndexType indexType, int indexCount) { renderPass._bindIndexBufferDevice( this, offsetInBytes, lengthInBytes, indexType.index, indexCount); } @override bool _bindAsUniform(RenderPass renderPass, UniformSlot slot, int offsetInBytes, int lengthInBytes) { return renderPass._bindUniformDevice( slot.shader, slot.uniformName, this, offsetInBytes, lengthInBytes); } /// Wrap with native counterpart. @Native<Bool Function(Handle, Pointer<Void>, Int, Int)>( symbol: 'InternalFlutterGpu_DeviceBuffer_Initialize') external bool _initialize( GpuContext gpuContext, int storageMode, int sizeInBytes); /// Wrap with native counterpart. @Native<Bool Function(Handle, Pointer<Void>, Handle)>( symbol: 'InternalFlutterGpu_DeviceBuffer_InitializeWithHostData') external bool _initializeWithHostData(GpuContext gpuContext, ByteData data); /// Overwrite a range of bytes in the already created [DeviceBuffer]. /// /// This method can only be used if the [DeviceBuffer] was created with /// [StorageMode.hostVisible]. An exception will be thrown otherwise. /// /// The entire length of [sourceBytes] will be copied into the [DeviceBuffer], /// starting at byte index [destinationOffsetInBytes] in the [DeviceBuffer]. /// If performing this copy would result in an out of bounds write to the /// buffer, then the write will not be attempted and will fail. /// /// Returns [true] if the write was successful, or [false] if the write /// failed due to an internal error. bool overwrite(ByteData sourceBytes, {int destinationOffsetInBytes = 0}) { if (storageMode != StorageMode.hostVisible) { throw Exception( 'DeviceBuffer.overwrite can only be used with DeviceBuffers that are host visible'); } if (destinationOffsetInBytes < 0) { throw Exception('destinationOffsetInBytes must be positive'); } return _overwrite(sourceBytes, destinationOffsetInBytes); } @Native<Bool Function(Pointer<Void>, Handle, Int)>( symbol: 'InternalFlutterGpu_DeviceBuffer_Overwrite') external bool _overwrite(ByteData bytes, int destinationOffsetInBytes); } /// [HostBuffer] is a [Buffer] which is allocated on the host (native CPU /// resident memory) and lazily uploaded to the GPU. A [HostBuffer] can be /// safely mutated or extended at any time on the host, and will be /// automatically re-uploaded to the GPU the next time a GPU operation needs to /// access it. /// /// This is useful for efficiently chunking sparse data uploads, especially /// ephemeral uniform data that needs to change from frame to frame. /// /// Different platforms have different data alignment requirements for accessing /// device buffer data. The [HostBuffer] takes these requirements into account /// and automatically inserts padding between emplaced data if necessary. base class HostBuffer extends NativeFieldWrapperClass1 with Buffer { /// Creates a new HostBuffer. HostBuffer._initialize(GpuContext gpuContext) { _initialize(gpuContext); } @override void _bindAsVertexBuffer(RenderPass renderPass, int offsetInBytes, int lengthInBytes, int vertexCount) { renderPass._bindVertexBufferHost( this, offsetInBytes, lengthInBytes, vertexCount); } @override void _bindAsIndexBuffer(RenderPass renderPass, int offsetInBytes, int lengthInBytes, IndexType indexType, int indexCount) { renderPass._bindIndexBufferHost( this, offsetInBytes, lengthInBytes, indexType.index, indexCount); } @override bool _bindAsUniform(RenderPass renderPass, UniformSlot slot, int offsetInBytes, int lengthInBytes) { return renderPass._bindUniformHost( slot.shader, slot.uniformName, this, offsetInBytes, lengthInBytes); } /// Wrap with native counterpart. @Native<Void Function(Handle, Pointer<Void>)>( symbol: 'InternalFlutterGpu_HostBuffer_Initialize') external void _initialize(GpuContext gpuContext); /// Append byte data to the end of the [HostBuffer] and produce a [BufferView] /// that references the new data in the buffer. /// /// This method automatically inserts padding in-between emplace calls in the /// buffer if necessary to abide by platform-specific uniform alignment /// requirements. /// /// The updated buffer will be uploaded to the GPU if the returned /// [BufferView] is used by a rendering command. BufferView emplace(ByteData bytes) { int resultOffset = _emplaceBytes(bytes); return BufferView(this, offsetInBytes: resultOffset, lengthInBytes: bytes.lengthInBytes); } @Native<Uint64 Function(Pointer<Void>, Handle)>( symbol: 'InternalFlutterGpu_HostBuffer_EmplaceBytes') external int _emplaceBytes(ByteData bytes); }
engine/lib/gpu/lib/src/buffer.dart/0
{'file_path': 'engine/lib/gpu/lib/src/buffer.dart', 'repo_id': 'engine', 'token_count': 2117}
// 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 dart.ui; class GpuContextException implements Exception { GpuContextException(this.message); String message; @override String toString() { return 'GpuContextException: $message'; } } enum BlendOperation { add, subtract, reverseSubtract } enum BlendFactor { zero, one, sourceColor, oneMinusSourceColor, sourceAlpha, oneMinusSourceAlpha, destinationColor, oneMinusDestinationColor, destinationAlpha, oneMinusDestinationAlpha, sourceAlphaSaturated, blendColor, oneMinusBlendColor, blendAlpha, oneMinusBlendAlpha, } class BlendOptions { const BlendOptions({ this.colorOperation = BlendOperation.add, this.sourceColorFactor = BlendFactor.one, this.destinationColorFactor = BlendFactor.oneMinusSourceAlpha, this.alphaOperation = BlendOperation.add, this.sourceAlphaFactor = BlendFactor.one, this.destinationAlphaFactor = BlendFactor.oneMinusSourceAlpha, }); final BlendOperation colorOperation; final BlendFactor sourceColorFactor; final BlendFactor destinationColorFactor; final BlendOperation alphaOperation; final BlendFactor sourceAlphaFactor; final BlendFactor destinationAlphaFactor; } enum StencilOperation { keep, zero, setToReferenceValue, incrementClamp, decrementClamp, invert, incrementWrap, decrementWrap, } enum CompareFunction { never, always, less, equal, lessEqual, greater, notEqual, greaterEqual, } class StencilOptions { const StencilOptions({ this.operation = StencilOperation.incrementClamp, this.compare = CompareFunction.always, }); final StencilOperation operation; final CompareFunction compare; } enum ShaderType { unknown, voidType, booleanType, signedByteType, unsignedByteType, signedShortType, unsignedShortType, signedIntType, unsignedIntType, signedInt64Type, unsignedInt64Type, atomicCounterType, halfFloatType, floatType, doubleType, structType, imageType, sampledImageType, samplerType, } class VertexAttribute { const VertexAttribute({ this.name = '', this.location = 0, this.set = 0, this.binding = 0, this.type = ShaderType.floatType, this.elements = 2, }); final String name; final int location; final int set; final int binding; final ShaderType type; final int elements; } class UniformSlot { const UniformSlot({ this.name = '', this.set = 0, this.extRes0 = 0, this.binding = 0, }); final String name; final int set; final int extRes0; final int binding; } class GpuShader {} class RasterPipeline {} /// A handle to a graphics context. Used to create and manage GPU resources. /// /// To obtain the default graphics context, use [getGpuContext]. base class GpuContext extends NativeFieldWrapperClass1 { /// Creates a new graphics context that corresponds to the default Impeller /// context. GpuContext._createDefault() { final String error = _initializeDefault(); if (error.isNotEmpty) { throw GpuContextException(error); } } //registerShaderLibrary() async Future<RasterPipeline> createRasterPipeline({ required GpuShader vertex, required GpuShader fragment, BlendOptions blendOptions = const BlendOptions(), StencilOptions stencilOptions = const StencilOptions(), List<VertexAttribute> vertexLayout = const <VertexAttribute>[], List<UniformSlot> uniformLayout = const <UniformSlot>[], }) async { return RasterPipeline(); } /// Associates the default Impeller context with this GpuContext. @Native<Handle Function(Handle)>(symbol: 'GpuContext::InitializeDefault') external String _initializeDefault(); } GpuContext? _defaultGpuContext; /// Returns the default graphics context. GpuContext getGpuContext() { _defaultGpuContext ??= GpuContext._createDefault(); return _defaultGpuContext!; }
engine/lib/ui/experiments/gpu.dart/0
{'file_path': 'engine/lib/ui/experiments/gpu.dart', 'repo_id': 'engine', 'token_count': 1299}
// 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 dart.ui; /// A wrapper for a raw callback handle. /// /// This is the return type for [PluginUtilities.getCallbackHandle]. class CallbackHandle { /// Create an instance using a raw callback handle. /// /// Only values produced by a call to [CallbackHandle.toRawHandle] should be /// used, otherwise this object will be an invalid handle. CallbackHandle.fromRawHandle(this._handle); final int _handle; /// Get the raw callback handle to pass over a [MethodChannel] or [SendPort] /// (to pass to another [Isolate]). int toRawHandle() => _handle; @override bool operator ==(Object other) { if (runtimeType != other.runtimeType) { return false; } return other is CallbackHandle && other._handle == _handle; } @override int get hashCode => _handle.hashCode; } /// Functionality for Flutter plugin authors. /// /// See also: /// /// * [IsolateNameServer], which provides utilities for dealing with /// [Isolate]s. abstract final class PluginUtilities { static final Map<Function, CallbackHandle?> _forwardCache = <Function, CallbackHandle?>{}; static final Map<CallbackHandle, Function?> _backwardCache = <CallbackHandle, Function?>{}; /// Get a handle to a named top-level or static callback function which can /// be easily passed between isolates. /// /// The `callback` argument must not be null. /// /// Returns a [CallbackHandle] that can be provided to /// [PluginUtilities.getCallbackFromHandle] to retrieve a tear-off of the /// original callback. If `callback` is not a top-level or static function, /// null is returned. static CallbackHandle? getCallbackHandle(Function callback) { return _forwardCache.putIfAbsent(callback, () { final int? handle = _getCallbackHandle(callback); return handle != null ? CallbackHandle.fromRawHandle(handle) : null; }); } /// Get a tear-off of a named top-level or static callback represented by a /// handle. /// /// The `handle` argument must not be null. /// /// If `handle` is not a valid handle returned by /// [PluginUtilities.getCallbackHandle], null is returned. Otherwise, a /// tear-off of the callback associated with `handle` is returned. static Function? getCallbackFromHandle(CallbackHandle handle) { return _backwardCache.putIfAbsent( handle, () => _getCallbackFromHandle(handle.toRawHandle())); } }
engine/lib/ui/plugins.dart/0
{'file_path': 'engine/lib/ui/plugins.dart', 'repo_id': 'engine', 'token_count': 759}
// 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 dart.ui; @pragma('vm:entry-point') void _setupHooks() { assert(() { // In debug mode, register the schedule frame extension. developer.registerExtension('ext.ui.window.scheduleFrame', _scheduleFrame); // In debug mode, allow shaders to be reinitialized. developer.registerExtension( 'ext.ui.window.reinitializeShader', _reinitializeShader, ); return true; }()); // In debug and profile mode, allow tools to display the current rendering backend. if (!_kReleaseMode) { developer.registerExtension( 'ext.ui.window.impellerEnabled', _getImpellerEnabled, ); } }
engine/lib/ui/setup_hooks.dart/0
{'file_path': 'engine/lib/ui/setup_hooks.dart', 'repo_id': 'engine', 'token_count': 270}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. part of ui; double clampDouble(double x, double min, double max) { assert(min <= max && !max.isNaN && !min.isNaN); if (x < min) { return min; } if (x > max) { return max; } if (x.isNaN) { return max; } return x; }
engine/lib/web_ui/lib/math.dart/0
{'file_path': 'engine/lib/web_ui/lib/math.dart', 'repo_id': 'engine', 'token_count': 152}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:typed_data'; import 'package:ui/src/engine/vector_math.dart'; import 'package:ui/ui.dart' as ui; import '../color_filter.dart'; import '../util.dart'; import 'canvaskit_api.dart'; import 'image_filter.dart'; import 'native_memory.dart'; /// Owns a [SkColorFilter] and manages its lifecycle. /// /// See also: /// /// * [CkPaint.colorFilter], which uses a [ManagedSkColorFilter] to manage /// the lifecycle of its [SkColorFilter]. class ManagedSkColorFilter { ManagedSkColorFilter(CkColorFilter ckColorFilter) : colorFilter = ckColorFilter { _ref = UniqueRef<SkColorFilter>(this, colorFilter._initRawColorFilter(), 'ColorFilter'); } final CkColorFilter colorFilter; late final UniqueRef<SkColorFilter> _ref; SkColorFilter get skiaObject => _ref.nativeObject; @override int get hashCode => colorFilter.hashCode; @override bool operator ==(Object other) { if (runtimeType != other.runtimeType) { return false; } return other is ManagedSkColorFilter && other.colorFilter == colorFilter; } @override String toString() => colorFilter.toString(); } /// CanvasKit implementation of [ui.ColorFilter]. abstract class CkColorFilter implements CkManagedSkImageFilterConvertible { const CkColorFilter(); /// Converts this color filter into an image filter. /// /// Passes the ownership of the returned [SkImageFilter] to the caller. It is /// the caller's responsibility to manage the lifecycle of the returned value. SkImageFilter initRawImageFilter() { final SkColorFilter skColorFilter = _initRawColorFilter(); final SkImageFilter result = canvasKit.ImageFilter.MakeColorFilter(skColorFilter, null); // The underlying SkColorFilter is now owned by the SkImageFilter, so we // need to drop the reference to allow it to be collected. skColorFilter.delete(); return result; } /// Creates a Skia object based on the properties of this color filter. /// /// Passes the ownership of the returned [SkColorFilter] to the caller. It is /// the caller's responsibility to manage the lifecycle of the returned value. SkColorFilter _initRawColorFilter(); @override void imageFilter(SkImageFilterBorrow borrow) { // Since ColorFilter has a const constructor it cannot store dynamically // created Skia objects. Therefore a new SkImageFilter is created every time // it's used. However, once used it's no longer needed, so it's deleted // immediately to free memory. final SkImageFilter skImageFilter = initRawImageFilter(); borrow(skImageFilter); skImageFilter.delete(); } @override Matrix4 get transform => Matrix4.identity(); } /// A reusable identity transform matrix. /// /// WARNING: DO NOT MUTATE THIS MATRIX! It is a shared global singleton. Float32List _identityTransform = _computeIdentityTransform(); Float32List _computeIdentityTransform() { final Float32List result = Float32List(20); const List<int> translationIndices = <int>[0, 6, 12, 18]; for (final int i in translationIndices) { result[i] = 1; } _identityTransform = result; return result; } SkColorFilter createSkColorFilterFromColorAndBlendMode(ui.Color color, ui.BlendMode blendMode) { /// Return the identity matrix when the color opacity is 0. Replicates /// effect of applying no filter if (color.opacity == 0) { return canvasKit.ColorFilter.MakeMatrix(_identityTransform); } final SkColorFilter? filter = canvasKit.ColorFilter.MakeBlend( toSharedSkColor1(color), toSkBlendMode(blendMode), ); if (filter == null) { throw ArgumentError('Invalid parameters for blend mode ColorFilter'); } return filter; } class CkBlendModeColorFilter extends CkColorFilter { const CkBlendModeColorFilter(this.color, this.blendMode); final ui.Color color; final ui.BlendMode blendMode; @override SkColorFilter _initRawColorFilter() { return createSkColorFilterFromColorAndBlendMode(color, blendMode); } @override int get hashCode => Object.hash(color, blendMode); @override bool operator ==(Object other) { if (runtimeType != other.runtimeType) { return false; } return other is CkBlendModeColorFilter && other.color == color && other.blendMode == blendMode; } @override String toString() => 'ColorFilter.mode($color, $blendMode)'; } class CkMatrixColorFilter extends CkColorFilter { const CkMatrixColorFilter(this.matrix); final List<double> matrix; /// Flutter documentation says the translation column of the color matrix /// is specified in unnormalized 0..255 space. CanvasKit expects the /// translation values to be normalized to 0..1 space. /// /// See [https://api.flutter.dev/flutter/dart-ui/ColorFilter/ColorFilter.matrix.html]. Float32List get _normalizedMatrix { assert(matrix.length == 20, 'Color Matrix must have 20 entries.'); final Float32List result = Float32List(20); const List<int> translationIndices = <int>[4, 9, 14, 19]; for (int i = 0; i < 20; i++) { if (translationIndices.contains(i)) { result[i] = matrix[i] / 255.0; } else { result[i] = matrix[i]; } } return result; } @override SkColorFilter _initRawColorFilter() { return canvasKit.ColorFilter.MakeMatrix(_normalizedMatrix); } @override int get hashCode => Object.hashAll(matrix); @override bool operator ==(Object other) { return runtimeType == other.runtimeType && other is CkMatrixColorFilter && listEquals<double>(matrix, other.matrix); } @override String toString() => 'ColorFilter.matrix($matrix)'; } class CkLinearToSrgbGammaColorFilter extends CkColorFilter { const CkLinearToSrgbGammaColorFilter(); @override SkColorFilter _initRawColorFilter() => canvasKit.ColorFilter.MakeLinearToSRGBGamma(); @override bool operator ==(Object other) => runtimeType == other.runtimeType; @override int get hashCode => runtimeType.hashCode; @override String toString() => 'ColorFilter.linearToSrgbGamma()'; } class CkSrgbToLinearGammaColorFilter extends CkColorFilter { const CkSrgbToLinearGammaColorFilter(); @override SkColorFilter _initRawColorFilter() => canvasKit.ColorFilter.MakeSRGBToLinearGamma(); @override bool operator ==(Object other) => runtimeType == other.runtimeType; @override int get hashCode => runtimeType.hashCode; @override String toString() => 'ColorFilter.srgbToLinearGamma()'; } class CkComposeColorFilter extends CkColorFilter { const CkComposeColorFilter(this.outer, this.inner); final ManagedSkColorFilter? outer; final ManagedSkColorFilter inner; @override SkColorFilter _initRawColorFilter() => canvasKit.ColorFilter.MakeCompose(outer?.skiaObject, inner.skiaObject); @override bool operator ==(Object other) { if (other is! CkComposeColorFilter) { return false; } final CkComposeColorFilter filter = other; return filter.outer == outer && filter.inner == inner; } @override int get hashCode => Object.hash(outer, inner); @override String toString() => 'ColorFilter.compose($outer, $inner)'; } /// Convert the current [ColorFilter] to a CkColorFilter. /// /// This workaround allows ColorFilter to be const constructbile and /// efficiently comparable, so that widgets can check for ColorFilter equality to /// avoid repainting. CkColorFilter? createCkColorFilter(EngineColorFilter colorFilter) { switch (colorFilter.type) { case ColorFilterType.mode: if (colorFilter.color == null || colorFilter.blendMode == null) { return null; } return CkBlendModeColorFilter(colorFilter.color!, colorFilter.blendMode!); case ColorFilterType.matrix: if (colorFilter.matrix == null) { return null; } assert(colorFilter.matrix!.length == 20, 'Color Matrix must have 20 entries.'); return CkMatrixColorFilter(colorFilter.matrix!); case ColorFilterType.linearToSrgbGamma: return const CkLinearToSrgbGammaColorFilter(); case ColorFilterType.srgbToLinearGamma: return const CkSrgbToLinearGammaColorFilter(); default: throw StateError('Unknown mode $colorFilter.type for ColorFilter.'); } }
engine/lib/web_ui/lib/src/engine/canvaskit/color_filter.dart/0
{'file_path': 'engine/lib/web_ui/lib/src/engine/canvaskit/color_filter.dart', 'repo_id': 'engine', 'token_count': 2774}
// 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/src/engine.dart'; /// A [Rasterizer] that uses a single GL context in an OffscreenCanvas to do /// all the rendering. It transfers bitmaps created in the OffscreenCanvas to /// one or many on-screen <canvas> elements to actually display the scene. class OffscreenCanvasRasterizer extends Rasterizer { /// This is an SkSurface backed by an OffScreenCanvas. This single Surface is /// used to render to many RenderCanvases to produce the rendered scene. final Surface offscreenSurface = Surface(); @override OffscreenCanvasViewRasterizer createViewRasterizer(EngineFlutterView view) { return _viewRasterizers.putIfAbsent( view, () => OffscreenCanvasViewRasterizer(view, this)); } final Map<EngineFlutterView, OffscreenCanvasViewRasterizer> _viewRasterizers = <EngineFlutterView, OffscreenCanvasViewRasterizer>{}; @override void setResourceCacheMaxBytes(int bytes) { offscreenSurface.setSkiaResourceCacheMaxBytes(bytes); } @override void dispose() { offscreenSurface.dispose(); for (final OffscreenCanvasViewRasterizer viewRasterizer in _viewRasterizers.values) { viewRasterizer.dispose(); } } } class OffscreenCanvasViewRasterizer extends ViewRasterizer { OffscreenCanvasViewRasterizer(super.view, this.rasterizer); final OffscreenCanvasRasterizer rasterizer; @override final DisplayCanvasFactory<RenderCanvas> displayFactory = DisplayCanvasFactory<RenderCanvas>(createCanvas: () => RenderCanvas()); /// Render the given [pictures] so it is displayed by the given [canvas]. @override Future<void> rasterizeToCanvas( DisplayCanvas canvas, List<CkPicture> pictures) async { await rasterizer.offscreenSurface.rasterizeToCanvas( currentFrameSize, canvas as RenderCanvas, pictures, ); } @override void prepareToDraw() { rasterizer.offscreenSurface.createOrUpdateSurface(currentFrameSize); } }
engine/lib/web_ui/lib/src/engine/canvaskit/offscreen_canvas_rasterizer.dart/0
{'file_path': 'engine/lib/web_ui/lib/src/engine/canvaskit/offscreen_canvas_rasterizer.dart', 'repo_id': 'engine', 'token_count': 681}
// 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/ui.dart' as ui; import 'canvaskit_api.dart'; import 'native_memory.dart'; class CkVertices implements ui.Vertices { factory CkVertices( ui.VertexMode mode, List<ui.Offset> positions, { List<ui.Offset>? textureCoordinates, List<ui.Color>? colors, List<int>? indices, }) { if (textureCoordinates != null && textureCoordinates.length != positions.length) { throw ArgumentError( '"positions" and "textureCoordinates" lengths must match.'); } if (colors != null && colors.length != positions.length) { throw ArgumentError('"positions" and "colors" lengths must match.'); } if (indices != null && indices.any((int i) => i < 0 || i >= positions.length)) { throw ArgumentError( '"indices" values must be valid indices in the positions list.'); } return CkVertices._( toSkVertexMode(mode), toFlatSkPoints(positions), textureCoordinates != null ? toFlatSkPoints(textureCoordinates) : null, colors != null ? toFlatColors(colors) : null, indices != null ? toUint16List(indices) : null, ); } factory CkVertices.raw( ui.VertexMode mode, Float32List positions, { Float32List? textureCoordinates, Int32List? colors, Uint16List? indices, }) { if (textureCoordinates != null && textureCoordinates.length != positions.length) { throw ArgumentError( '"positions" and "textureCoordinates" lengths must match.'); } if (colors != null && colors.length * 2 != positions.length) { throw ArgumentError('"positions" and "colors" lengths must match.'); } if (indices != null && indices.any((int i) => i < 0 || i >= positions.length)) { throw ArgumentError( '"indices" values must be valid indices in the positions list.'); } Uint32List? unsignedColors; if (colors != null) { unsignedColors = colors.buffer.asUint32List(colors.offsetInBytes, colors.length); } return CkVertices._( toSkVertexMode(mode), positions, textureCoordinates, unsignedColors, indices, ); } CkVertices._( this._mode, this._positions, this._textureCoordinates, this._colors, this._indices, ) { final SkVertices skVertices = canvasKit.MakeVertices( _mode, _positions, _textureCoordinates, _colors, _indices, ); _ref = UniqueRef<SkVertices>(this, skVertices, 'Vertices'); } final SkVertexMode _mode; final Float32List _positions; final Float32List? _textureCoordinates; final Uint32List? _colors; final Uint16List? _indices; late final UniqueRef<SkVertices> _ref; SkVertices get skiaObject => _ref.nativeObject; @override void dispose() { _ref.dispose(); } @override bool get debugDisposed => _ref.isDisposed; }
engine/lib/web_ui/lib/src/engine/canvaskit/vertices.dart/0
{'file_path': 'engine/lib/web_ui/lib/src/engine/canvaskit/vertices.dart', 'repo_id': 'engine', 'token_count': 1206}
// 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 '../svg.dart'; import '../util.dart'; import 'path_to_svg_clip.dart'; import 'surface.dart'; import 'surface_stats.dart'; /// Mixin used by surfaces that clip their contents using an overflowing DOM /// element. mixin _DomClip on PersistedContainerSurface { /// The dedicated child container element that's separate from the /// [rootElement] is used to compensate for the coordinate system shift /// introduced by the [rootElement] translation. @override DomElement? get childContainer => _childContainer; DomElement? _childContainer; @override void adoptElements(_DomClip oldSurface) { super.adoptElements(oldSurface); _childContainer = oldSurface._childContainer; oldSurface._childContainer = null; } @override DomElement createElement() { final DomElement element = defaultCreateElement('flt-clip'); _childContainer = createDomElement('flt-clip-interior'); if (debugExplainSurfaceStats) { // This creates an additional interior element. Count it too. surfaceStatsFor(this).allocatedDomNodeCount++; } _childContainer!.style.position = 'absolute'; element.append(_childContainer!); return element; } @override void discard() { super.discard(); // Do not detach the child container from the root. It is permanently // attached. The elements are reused together and are detached from the DOM // together. _childContainer = null; } void applyOverflow(DomElement element, ui.Clip? clipBehaviour) { if (!debugShowClipLayers) { // Hide overflow in production mode. When debugging we want to see the // clipped picture in full. if (clipBehaviour != ui.Clip.none) { element.style ..overflow = 'hidden' ..zIndex = '0'; } } else { // Display the outline of the clipping region. When debugShowClipLayers is // `true` we don't hide clip overflow (see above). This outline helps // visualizing clip areas. element.style.boxShadow = 'inset 0 0 10px green'; } } } /// A surface that creates a rectangular clip. class PersistedClipRect extends PersistedContainerSurface with _DomClip implements ui.ClipRectEngineLayer { PersistedClipRect(PersistedClipRect? super.oldLayer, this.rect, this.clipBehavior); final ui.Clip? clipBehavior; final ui.Rect rect; @override void recomputeTransformAndClip() { transform = parent!.transform; if (clipBehavior != ui.Clip.none) { localClipBounds = rect; } else { localClipBounds = null; } projectedClip = null; } @override DomElement createElement() { return super.createElement()..setAttribute('clip-type', 'rect'); } @override void apply() { rootElement!.style ..left = '${rect.left}px' ..top = '${rect.top}px' ..width = '${rect.right - rect.left}px' ..height = '${rect.bottom - rect.top}px'; applyOverflow(rootElement!, clipBehavior); // Translate the child container in the opposite direction to compensate for // the shift in the coordinate system introduced by the translation of the // rootElement. Clipping in Flutter has no effect on the coordinate system. childContainer!.style ..left = '${-rect.left}px' ..top = '${-rect.top}px'; } @override void update(PersistedClipRect oldSurface) { super.update(oldSurface); if (rect != oldSurface.rect || clipBehavior != oldSurface.clipBehavior) { localClipBounds = null; apply(); } } @override bool get isClipping => true; } /// A surface that creates a rounded rectangular clip. class PersistedClipRRect extends PersistedContainerSurface with _DomClip implements ui.ClipRRectEngineLayer { PersistedClipRRect(ui.EngineLayer? oldLayer, this.rrect, this.clipBehavior) : super(oldLayer as PersistedSurface?); final ui.RRect rrect; // TODO(yjbanov): can this be controlled in the browser? final ui.Clip? clipBehavior; @override void recomputeTransformAndClip() { transform = parent!.transform; if (clipBehavior != ui.Clip.none) { localClipBounds = rrect.outerRect; } else { localClipBounds = null; } projectedClip = null; } @override DomElement createElement() { return super.createElement()..setAttribute('clip-type', 'rrect'); } @override void apply() { final DomCSSStyleDeclaration style = rootElement!.style; style ..left = '${rrect.left}px' ..top = '${rrect.top}px' ..width = '${rrect.width}px' ..height = '${rrect.height}px' ..borderTopLeftRadius = '${rrect.tlRadiusX}px' ..borderTopRightRadius = '${rrect.trRadiusX}px' ..borderBottomRightRadius = '${rrect.brRadiusX}px' ..borderBottomLeftRadius = '${rrect.blRadiusX}px'; applyOverflow(rootElement!, clipBehavior); // Translate the child container in the opposite direction to compensate for // the shift in the coordinate system introduced by the translation of the // rootElement. Clipping in Flutter has no effect on the coordinate system. childContainer!.style ..left = '${-rrect.left}px' ..top = '${-rrect.top}px'; } @override void update(PersistedClipRRect oldSurface) { super.update(oldSurface); if (rrect != oldSurface.rrect || clipBehavior != oldSurface.clipBehavior) { localClipBounds = null; apply(); } } @override bool get isClipping => true; } /// A surface that clips it's children. class PersistedClipPath extends PersistedContainerSurface implements ui.ClipPathEngineLayer { PersistedClipPath( PersistedClipPath? super.oldLayer, this.clipPath, this.clipBehavior); final ui.Path clipPath; final ui.Clip clipBehavior; DomElement? _clipElement; @override DomElement createElement() { return defaultCreateElement('flt-clippath'); } @override void recomputeTransformAndClip() { super.recomputeTransformAndClip(); if (clipBehavior != ui.Clip.none) { localClipBounds ??= clipPath.getBounds(); } else { localClipBounds = null; } } @override void apply() { _clipElement?.remove(); _clipElement = createSvgClipDef(childContainer!, clipPath); childContainer!.append(_clipElement!); } @override void update(PersistedClipPath oldSurface) { super.update(oldSurface); if (oldSurface.clipPath != clipPath) { localClipBounds = null; oldSurface._clipElement?.remove(); apply(); } else { _clipElement = oldSurface._clipElement; } oldSurface._clipElement = null; } @override void discard() { _clipElement?.remove(); _clipElement = null; super.discard(); } @override bool get isClipping => true; } /// Creates an svg clipPath and applies it to [element]. SVGSVGElement createSvgClipDef(DomElement element, ui.Path clipPath) { final ui.Rect pathBounds = clipPath.getBounds(); final SVGSVGElement svgClipPath = pathToSvgClipPath(clipPath, scaleX: 1.0 / pathBounds.right, scaleY: 1.0 / pathBounds.bottom); setClipPath(element, createSvgClipUrl()); // We need to set width and height for the clipElement to cover the // bounds of the path since browsers such as Safari and Edge // seem to incorrectly intersect the element bounding rect with // the clip path. Chrome and Firefox don't perform intersect instead they // use the path itself as source of truth. element.style ..width = '${pathBounds.right}px' ..height = '${pathBounds.bottom}px'; return svgClipPath; }
engine/lib/web_ui/lib/src/engine/html/clip.dart/0
{'file_path': 'engine/lib/web_ui/lib/src/engine/html/clip.dart', 'repo_id': 'engine', 'token_count': 2751}
// 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 'conic.dart'; import 'cubic.dart'; import 'path_iterator.dart'; import 'path_ref.dart'; import 'path_utils.dart'; /// Computes winding number and onCurveCount for a path and point. class PathWinding { PathWinding(this.pathRef, this.x, this.y) { _walkPath(); } final PathRef pathRef; final double x; final double y; int _w = 0; int _onCurveCount = 0; int get w => _w; int get onCurveCount => _onCurveCount; /// Buffer used for max(iterator result, chopped 3 cubics). final Float32List _buffer = Float32List(8 + 10); /// Iterates through path and computes winding. void _walkPath() { final PathIterator iter = PathIterator(pathRef, true); int verb; while ((verb = iter.next(_buffer)) != SPath.kDoneVerb) { switch (verb) { case SPath.kMoveVerb: case SPath.kCloseVerb: break; case SPath.kLineVerb: _computeLineWinding(); case SPath.kQuadVerb: _computeQuadWinding(); case SPath.kConicVerb: _computeConicWinding(pathRef.conicWeights![iter.conicWeightIndex]); case SPath.kCubicVerb: _computeCubicWinding(); } } } void _computeLineWinding() { final double x0 = _buffer[0]; final double startY = _buffer[1]; double y0 = startY; final double x1 = _buffer[2]; final double endY = _buffer[3]; double y1 = endY; final double dy = y1 - y0; int dir = 1; // Swap so that y0 <= y1 holds. if (y0 > y1) { final double temp = y0; y0 = y1; y1 = temp; dir = -1; } // If point is outside top/bottom bounds, winding is 0. if (y < y0 || y > y1) { return; } if (_checkOnCurve(x, y, x0, startY, x1, endY)) { _onCurveCount++; return; } if (y == y1) { return; } // c = ax*by − ay*bx where a is the line and b is line formed from start // to the given point(x,y). final double crossProduct = (x1 - x0) * (y - startY) - dy * (x - x0); if (crossProduct == 0) { // zero cross means the point is on the line, and since the case where // y of the query point is at the end point is handled above, we can be // sure that we're on the line (excluding the end point) here. if (x != x1 || y != endY) { _onCurveCount++; } dir = 0; } else if (SPath.scalarSignedAsInt(crossProduct) == dir) { // Direction of cross product and line the same. dir = 0; } _w += dir; } // Check if point starts the line, handle special case for horizontal lines // where and point except the end point is considered on curve. static bool _checkOnCurve(double x, double y, double startX, double startY, double endX, double endY) { if (startY == endY) { // Horizontal line. return SPath.between(startX, x, endX) && x != endX; } else { return x == startX && y == startY; } } void _computeQuadWinding() { // Check if we need to chop quadratic at extrema to compute 2 separate // windings. int n = 0; if (!_isQuadMonotonic(_buffer)) { n = _chopQuadAtExtrema(_buffer); } int winding = _computeMonoQuadWinding( _buffer[0], _buffer[1], _buffer[2], _buffer[3], _buffer[4], _buffer[5]); if (n > 0) { winding += _computeMonoQuadWinding(_buffer[4], _buffer[5], _buffer[6], _buffer[7], _buffer[8], _buffer[9]); } _w += winding; } int _computeMonoQuadWinding( double x0, double y0, double x1, double y1, double x2, double y2) { int dir = 1; final double startY = y0; final double endY = y2; if (y0 > y2) { final double temp = y0; y0 = y2; y2 = temp; dir = -1; } if (y < y0 || y > y2) { return 0; } if (_checkOnCurve(x, y, x0, startY, x2, endY)) { _onCurveCount++; return 0; } if (y == y2) { return 0; } final QuadRoots quadRoots = QuadRoots(); final int n = quadRoots.findRoots( startY - 2 * y1 + endY, 2 * (y1 - startY), startY - y); assert(n <= 1); double xt; if (0 == n) { // zero roots are returned only when y0 == y xt = dir == 1 ? x0 : x2; } else { final double t = quadRoots.root0!; final double C = x0; final double A = x2 - 2 * x1 + C; final double B = 2 * (x1 - C); xt = polyEval(A, B, C, t); } if (SPath.nearlyEqual(xt, x)) { if (x != x2 || y != endY) { // don't test end points; they're start points _onCurveCount += 1; return 0; } } return xt < x ? dir : 0; } /// Chops a non-monotonic quadratic curve, returns subdivisions and writes /// result into [buffer]. static int _chopQuadAtExtrema(Float32List buffer) { final double x0 = buffer[0]; final double y0 = buffer[1]; final double x1 = buffer[2]; final double y1 = buffer[3]; final double x2 = buffer[4]; final double y2 = buffer[5]; final double? tValueAtExtrema = validUnitDivide(y0 - y1, y0 - y1 - y1 + y2); if (tValueAtExtrema != null) { // Chop quad at t value by interpolating along p0-p1 and p1-p2. final double p01x = x0 + (tValueAtExtrema * (x1 - x0)); final double p01y = y0 + (tValueAtExtrema * (y1 - y0)); final double p12x = x1 + (tValueAtExtrema * (x2 - x1)); final double p12y = y1 + (tValueAtExtrema * (y2 - y1)); final double cx = p01x + (tValueAtExtrema * (p12x - p01x)); final double cy = p01y + (tValueAtExtrema * (p12y - p01y)); buffer[2] = p01x; buffer[3] = p01y; buffer[4] = cx; buffer[5] = cy; buffer[6] = p12x; buffer[7] = p12y; buffer[8] = x2; buffer[9] = y2; return 1; } // if we get here, we need to force output to be monotonic, even though // we couldn't compute a unit divide value (probably underflow). buffer[3] = (y0 - y1).abs() < (y1 - y2).abs() ? y0 : y2; return 0; } static bool _isQuadMonotonic(Float32List quad) { final double y0 = quad[1]; final double y1 = quad[3]; final double y2 = quad[5]; if (y0 == y1) { return true; } if (y0 < y1) { return y1 <= y2; } else { return y1 >= y2; } } void _computeConicWinding(double weight) { final Conic conic = Conic(_buffer[0], _buffer[1], _buffer[2], _buffer[3], _buffer[4], _buffer[5], weight); // If the data points are very large, the conic may not be monotonic but may also // fail to chop. Then, the chopper does not split the original conic in two. final bool isMono = _isQuadMonotonic(_buffer); final List<Conic> conics = <Conic>[]; conic.chopAtYExtrema(conics); _computeMonoConicWinding(conics[0]); if (!isMono && conics.length == 2) { _computeMonoConicWinding(conics[1]); } } void _computeMonoConicWinding(Conic conic) { double y0 = conic.p0y; double y2 = conic.p2y; int dir = 1; if (y0 > y2) { final double swap = y0; y0 = y2; y2 = swap; dir = -1; } if (y < y0 || y > y2) { return; } if (_checkOnCurve(x, y, conic.p0x, conic.p0y, conic.p2x, conic.p2y)) { _onCurveCount += 1; return; } if (y == y2) { return; } double A = conic.p2y; double B = conic.p1y * conic.fW - y * conic.fW + y; double C = conic.p0y; // A = a + c - 2*(b*w - yCept*w + yCept) A += C - 2 * B; // B = b*w - w * yCept + yCept - a B -= C; C -= y; final QuadRoots quadRoots = QuadRoots(); final int n = quadRoots.findRoots(A, 2 * B, C); assert(n <= 1); double xt; if (0 == n) { // zero roots are returned only when y0 == y // Need [0] if dir == 1 // and [2] if dir == -1 xt = dir == 1 ? conic.p0x : conic.p2x; } else { final double root = quadRoots.root0!; xt = Conic.evalNumerator(conic.p0x, conic.p1x, conic.p2x, conic.fW, root) / Conic.evalDenominator(conic.fW, root); } if (SPath.nearlyEqual(xt, x)) { if (x != conic.p2x || y != conic.p2y) { // don't test end points; they're start points _onCurveCount += 1; return; } } _w += xt < x ? dir : 0; } void _computeCubicWinding() { final int n = chopCubicAtYExtrema(_buffer, _buffer); for (int i = 0; i <= n; ++i) { _windingMonoCubic(i * 3 * 2); } } void _windingMonoCubic(int bufferIndex) { final int bufferStartPos = bufferIndex; final double px0 = _buffer[bufferIndex++]; final double py0 = _buffer[bufferIndex++]; final double px1 = _buffer[bufferIndex++]; bufferIndex++; final double px2 = _buffer[bufferIndex++]; bufferIndex++; final double px3 = _buffer[bufferIndex++]; final double py3 = _buffer[bufferIndex++]; double y0 = py0; double y3 = py3; int dir = 1; if (y0 > y3) { final double swap = y0; y0 = y3; y3 = swap; dir = -1; } if (y < y0 || y > y3) { return; } if (_checkOnCurve(x, y, px0, py0, px3, py3)) { _onCurveCount += 1; return; } if (y == y3) { return; } // Quickly reject or accept final double min = math.min(px0, math.min(px1, math.min(px2, px3))); final double max = math.max(px0, math.max(px1, math.max(px2, px3))); if (x < min) { return; } if (x > max) { _w += dir; return; } // Compute the actual x(t) value. final double? t = chopMonoAtY(_buffer, bufferStartPos, y); if (t == null) { return; } final double xt = evalCubicPts(px0, px1, px2, px3, t); if (SPath.nearlyEqual(xt, x)) { if (x != px3 || y != py3) { // don't test end points; they're start points _onCurveCount += 1; return; } } _w += xt < x ? dir : 0; } }
engine/lib/web_ui/lib/src/engine/html/path/path_windings.dart/0
{'file_path': 'engine/lib/web_ui/lib/src/engine/html/path/path_windings.dart', 'repo_id': 'engine', 'token_count': 4665}
// 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:meta/meta.dart'; import '../platform_dispatcher.dart'; import 'accessibility.dart'; import 'label_and_value.dart'; import 'semantics.dart'; /// Manages semantics configurations that represent live regions. /// /// Assistive technologies treat "aria-live" attribute differently. To keep /// the behavior consistent, [AccessibilityAnnouncements.announce] is used. /// /// When there is an update to [LiveRegion], assistive technologies read the /// label of the element. See [LabelAndValue]. If there is no label provided /// no content will be read. class LiveRegion extends RoleManager { LiveRegion(SemanticsObject semanticsObject, PrimaryRoleManager owner) : super(Role.liveRegion, semanticsObject, owner); String? _lastAnnouncement; static AccessibilityAnnouncements? _accessibilityAnnouncementsOverride; @visibleForTesting static void debugOverrideAccessibilityAnnouncements(AccessibilityAnnouncements? value) { _accessibilityAnnouncementsOverride = value; } AccessibilityAnnouncements get _accessibilityAnnouncements => _accessibilityAnnouncementsOverride ?? EnginePlatformDispatcher.instance.implicitView!.accessibilityAnnouncements; @override void update() { if (!semanticsObject.isLiveRegion) { return; } // Avoid announcing the same message over and over. if (_lastAnnouncement != semanticsObject.label) { _lastAnnouncement = semanticsObject.label; if (semanticsObject.hasLabel) { _accessibilityAnnouncements.announce( _lastAnnouncement!, Assertiveness.polite, ); } } } }
engine/lib/web_ui/lib/src/engine/semantics/live_region.dart/0
{'file_path': 'engine/lib/web_ui/lib/src/engine/semantics/live_region.dart', 'repo_id': 'engine', 'token_count': 540}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:js_interop'; import 'package:ui/src/engine.dart'; import 'package:ui/src/engine/skwasm/skwasm_impl.dart'; import 'package:ui/ui.dart' as ui; class SkwasmImageDecoder extends BrowserImageDecoder { SkwasmImageDecoder({ required super.contentType, required super.dataSource, required super.debugSource, }); @override ui.Image generateImageFromVideoFrame(VideoFrame frame) { final int width = frame.codedWidth.toInt(); final int height = frame.codedHeight.toInt(); final SkwasmSurface surface = (renderer as SkwasmRenderer).surface; return SkwasmImage(imageCreateFromTextureSource( frame as JSObject, width, height, surface.handle, )); } }
engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/codecs.dart/0
{'file_path': 'engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/codecs.dart', 'repo_id': 'engine', 'token_count': 307}
// 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. @DefaultAsset('skwasm') library skwasm_impl; import 'dart:ffi'; import 'package:ui/src/engine/skwasm/skwasm_impl.dart'; final class RawPaint extends Opaque {} typedef PaintHandle = Pointer<RawPaint>; @Native<PaintHandle Function()>(symbol: 'paint_create', isLeaf: true) external PaintHandle paintCreate(); @Native<Void Function(PaintHandle)>(symbol: 'paint_dispose', isLeaf: true) external void paintDispose(PaintHandle paint); @Native<Void Function(PaintHandle, Int)>(symbol: 'paint_setBlendMode', isLeaf: true) external void paintSetBlendMode(PaintHandle paint, int blendMode); @Native<Void Function(PaintHandle, Int)>(symbol: 'paint_setStyle', isLeaf: true) external void paintSetStyle(PaintHandle paint, int paintStyle); @Native<Int Function(PaintHandle)>(symbol: 'paint_getStyle', isLeaf: true) external int paintGetStyle(PaintHandle paint); @Native<Void Function(PaintHandle, Float)>(symbol: 'paint_setStrokeWidth', isLeaf: true) external void paintSetStrokeWidth(PaintHandle paint, double strokeWidth); @Native<Float Function(PaintHandle)>(symbol: 'paint_getStrokeWidth', isLeaf: true) external double paintGetStrokeWidth(PaintHandle paint); @Native<Void Function(PaintHandle, Int)>(symbol: 'paint_setStrokeCap', isLeaf: true) external void paintSetStrokeCap(PaintHandle paint, int cap); @Native<Int Function(PaintHandle)>(symbol: 'paint_getStrokeCap', isLeaf: true) external int paintGetStrokeCap(PaintHandle paint); @Native<Void Function(PaintHandle, Int)>(symbol: 'paint_setStrokeJoin', isLeaf: true) external void paintSetStrokeJoin(PaintHandle paint, int join); @Native<Int Function(PaintHandle)>(symbol: 'paint_getStrokeJoin', isLeaf: true) external int paintGetStrokeJoin(PaintHandle paint); @Native<Void Function(PaintHandle, Bool)>(symbol: 'paint_setAntiAlias', isLeaf: true) external void paintSetAntiAlias(PaintHandle paint, bool antiAlias); @Native<Bool Function(PaintHandle)>(symbol: 'paint_getAntiAlias', isLeaf: true) external bool paintGetAntiAlias(PaintHandle paint); @Native<Void Function(PaintHandle, Uint32)>(symbol: 'paint_setColorInt', isLeaf: true) external void paintSetColorInt(PaintHandle paint, int color); @Native<Uint32 Function(PaintHandle)>(symbol: 'paint_getColorInt', isLeaf: true) external int paintGetColorInt(PaintHandle paint); @Native<Void Function(PaintHandle, Float)>(symbol: 'paint_setMiterLimit', isLeaf: true) external void paintSetMiterLimit(PaintHandle paint, double miterLimit); @Native<Float Function(PaintHandle)>(symbol: 'paint_getMiterLimit', isLeaf: true) external double paintGetMiterLimit(PaintHandle paint); @Native<Void Function(PaintHandle, ShaderHandle)>(symbol: 'paint_setShader', isLeaf: true) external void paintSetShader(PaintHandle handle, ShaderHandle shader); @Native<Void Function(PaintHandle, ImageFilterHandle)>(symbol: 'paint_setImageFilter', isLeaf: true) external void paintSetImageFilter(PaintHandle handle, ImageFilterHandle filter); @Native<Void Function(PaintHandle, ColorFilterHandle)>(symbol: 'paint_setColorFilter', isLeaf: true) external void paintSetColorFilter(PaintHandle handle, ColorFilterHandle filter); @Native<Void Function(PaintHandle, MaskFilterHandle)>(symbol: 'paint_setMaskFilter', isLeaf: true) external void paintSetMaskFilter(PaintHandle handle, MaskFilterHandle filter);
engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/raw/raw_paint.dart/0
{'file_path': 'engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/raw/raw_paint.dart', 'repo_id': 'engine', 'token_count': 1139}
// 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 '../html/bitmap_canvas.dart'; import '../html/painting.dart'; import 'canvas_paragraph.dart'; import 'layout_fragmenter.dart'; import 'paragraph.dart'; /// Responsible for painting a [CanvasParagraph] on a [BitmapCanvas]. class TextPaintService { TextPaintService(this.paragraph); final CanvasParagraph paragraph; void paint(BitmapCanvas canvas, ui.Offset offset) { // Loop through all the lines, for each line, loop through all fragments and // paint them. The fragment objects have enough information to be painted // individually. final List<ParagraphLine> lines = paragraph.lines; for (final ParagraphLine line in lines) { for (final LayoutFragment fragment in line.fragments) { _paintBackground(canvas, offset, fragment); _paintText(canvas, offset, line, fragment); } } } void _paintBackground( BitmapCanvas canvas, ui.Offset offset, LayoutFragment fragment, ) { if (fragment.isPlaceholder) { return; } // Paint the background of the box, if the span has a background. final SurfacePaint? background = fragment.style.background as SurfacePaint?; if (background != null) { final ui.Rect rect = fragment.toPaintingTextBox().toRect(); if (!rect.isEmpty) { canvas.drawRect(rect.shift(offset), background.paintData); } } } void _paintText( BitmapCanvas canvas, ui.Offset offset, ParagraphLine line, LayoutFragment fragment, ) { // There's no text to paint in placeholder spans. if (fragment.isPlaceholder) { return; } // Don't paint the text for space-only boxes. This is just an // optimization, it doesn't have any effect on the output. if (fragment.isSpaceOnly) { return; } _prepareCanvasForFragment(canvas, fragment); final double fragmentX = fragment.textDirection! == ui.TextDirection.ltr ? fragment.left : fragment.right; final double x = offset.dx + line.left + fragmentX; final double y = offset.dy + line.baseline; final EngineTextStyle style = fragment.style; final String text = fragment.getText(paragraph); canvas.drawText(text, x, y, style: style.foreground?.style, shadows: style.shadows); canvas.tearDownPaint(); } void _prepareCanvasForFragment(BitmapCanvas canvas, LayoutFragment fragment) { final EngineTextStyle style = fragment.style; final SurfacePaint? paint; final ui.Paint? foreground = style.foreground; if (foreground != null) { paint = foreground as SurfacePaint; } else { paint = ui.Paint() as SurfacePaint; if (style.color != null) { paint.color = style.color!; } } canvas.setCssFont(style.cssFontString, fragment.textDirection!); canvas.setUpPaint(paint.paintData, null); } }
engine/lib/web_ui/lib/src/engine/text/paint_service.dart/0
{'file_path': 'engine/lib/web_ui/lib/src/engine/text/paint_service.dart', 'repo_id': 'engine', 'token_count': 1088}
// 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/dom.dart'; import 'package:ui/src/engine/window.dart'; import 'package:ui/ui.dart' as ui show Size; import 'dimensions_provider.dart'; /// This class provides observable, real-time dimensions of a host element. /// /// All the measurements returned from this class are potentially *expensive*, /// and should be cached as needed. Every call to every method on this class /// WILL perform actual DOM measurements. class CustomElementDimensionsProvider extends DimensionsProvider { /// Creates a [CustomElementDimensionsProvider] from a [_hostElement]. CustomElementDimensionsProvider(this._hostElement) { // Hook up a resize observer on the hostElement (if supported!). _hostElementResizeObserver = createDomResizeObserver(( List<DomResizeObserverEntry> entries, DomResizeObserver _, ) { entries .map((DomResizeObserverEntry entry) => ui.Size(entry.contentRect.width, entry.contentRect.height)) .forEach(_broadcastSize); }); assert(() { if (_hostElementResizeObserver == null) { domWindow.console.warn('ResizeObserver API not supported. ' 'Flutter will not resize with its hostElement.'); } return true; }()); _hostElementResizeObserver?.observe(_hostElement); } // The host element that will be used to retrieve (and observe) app size measurements. final DomElement _hostElement; // Handle resize events late DomResizeObserver? _hostElementResizeObserver; final StreamController<ui.Size> _onResizeStreamController = StreamController<ui.Size>.broadcast(); // Broadcasts the last seen `Size`. void _broadcastSize(ui.Size size) { _onResizeStreamController.add(size); } @override void close() { super.close(); _hostElementResizeObserver?.disconnect(); // ignore:unawaited_futures _onResizeStreamController.close(); } @override Stream<ui.Size> get onResize => _onResizeStreamController.stream; @override ui.Size computePhysicalSize() { final double devicePixelRatio = getDevicePixelRatio(); return ui.Size( _hostElement.clientWidth * devicePixelRatio, _hostElement.clientHeight * devicePixelRatio, ); } @override ViewPadding computeKeyboardInsets( double physicalHeight, bool isEditingOnMobile, ) { return const ViewPadding( top: 0, right: 0, bottom: 0, left: 0, ); } }
engine/lib/web_ui/lib/src/engine/view_embedder/dimensions_provider/custom_element_dimensions_provider.dart/0
{'file_path': 'engine/lib/web_ui/lib/src/engine/view_embedder/dimensions_provider/custom_element_dimensions_provider.dart', 'repo_id': 'engine', 'token_count': 900}
// 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/src/engine.dart'; /// Signature of the callback that receives a benchmark [value] labeled by /// [name]. typedef BenchmarkValueCallback = void Function(String name, double value); /// A callback for receiving benchmark values. /// /// Each benchmark value is labeled by a `name` and has a double `value`. set benchmarkValueCallback(BenchmarkValueCallback? callback) { engineBenchmarkValueCallback = callback; }
engine/lib/web_ui/lib/ui_web/src/ui_web/benchmarks.dart/0
{'file_path': 'engine/lib/web_ui/lib/ui_web/src/ui_web/benchmarks.dart', 'repo_id': 'engine', 'token_count': 152}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; import '../common/matchers.dart'; import 'common.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } void testMain() { group('CkPaint', () { setUpCanvasKitTest(); test('lifecycle', () { final CkPaint paint = CkPaint(); expect(paint.skiaObject, isNotNull); expect(paint.debugRef.isDisposed, isFalse); paint.dispose(); expect(paint.debugRef.isDisposed, isTrue); expect( reason: 'Cannot dispose more than once', () => paint.dispose(), throwsA(isAssertionError), ); }); }); }
engine/lib/web_ui/test/canvaskit/painting_test.dart/0
{'file_path': 'engine/lib/web_ui/test/canvaskit/painting_test.dart', 'repo_id': 'engine', 'token_count': 331}
// 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:test/test.dart'; import 'package:ui/ui.dart' as ui; /// Tests frame timings in a renderer-agnostic way. /// /// See CanvasKit-specific and HTML-specific test files `frame_timings_test.dart`. Future<void> runFrameTimingsTest() async { List<ui.FrameTiming>? timings; ui.PlatformDispatcher.instance.onReportTimings = (List<ui.FrameTiming> data) { timings = data; }; Completer<void> frameDone = Completer<void>(); ui.PlatformDispatcher.instance.onDrawFrame = () { final ui.SceneBuilder sceneBuilder = ui.SceneBuilder(); sceneBuilder ..pushOffset(0, 0) ..pop(); ui.PlatformDispatcher.instance.render(sceneBuilder.build()).then((_) { frameDone.complete(); }); }; // Frame 1. ui.PlatformDispatcher.instance.scheduleFrame(); await frameDone.future; expect(timings, isNull, reason: "100 ms hasn't passed yet"); await Future<void>.delayed(const Duration(milliseconds: 150)); // Frame 2. frameDone = Completer<void>(); ui.PlatformDispatcher.instance.scheduleFrame(); await frameDone.future; expect(timings, hasLength(2), reason: '100 ms passed. 2 frames pumped.'); for (final ui.FrameTiming timing in timings!) { expect(timing.vsyncOverhead, greaterThanOrEqualTo(Duration.zero)); expect(timing.buildDuration, greaterThanOrEqualTo(Duration.zero)); expect(timing.rasterDuration, greaterThanOrEqualTo(Duration.zero)); expect(timing.totalSpan, greaterThanOrEqualTo(Duration.zero)); expect(timing.layerCacheCount, equals(0)); expect(timing.layerCacheBytes, equals(0)); expect(timing.pictureCacheCount, equals(0)); expect(timing.pictureCacheBytes, equals(0)); } }
engine/lib/web_ui/test/common/frame_timings_common.dart/0
{'file_path': 'engine/lib/web_ui/test/common/frame_timings_common.dart', 'repo_id': 'engine', 'token_count': 646}
// 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:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; import 'package:ui/ui.dart' as ui; void main() { internalBootstrapBrowserTest(() => testMain); } void testMain() { group('EngineFlutterDisplay', () { test('overrides and restores devicePixelRatio', () { final EngineFlutterDisplay display = EngineFlutterDisplay( id: 0, size: const ui.Size(100.0, 100.0), refreshRate: 60.0, ); final double originalDevicePixelRatio = display.devicePixelRatio; display.debugOverrideDevicePixelRatio(99.3); expect(display.devicePixelRatio, 99.3); display.debugOverrideDevicePixelRatio(null); expect(display.devicePixelRatio, originalDevicePixelRatio); }); }); }
engine/lib/web_ui/test/engine/display_test.dart/0
{'file_path': 'engine/lib/web_ui/test/engine/display_test.dart', 'repo_id': 'engine', 'token_count': 339}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/ui.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } void testMain() { test('Locale', () { expect(const Locale('en').toString(), 'en'); expect(const Locale('en'), const Locale('en')); expect(const Locale('en').hashCode, const Locale('en').hashCode); expect(const Locale('en'), isNot(const Locale('en', ''))); // TODO(het): This fails on web because "".hashCode == null.hashCode == 0 //expect(const Locale('en').hashCode, isNot(const Locale('en', '').hashCode)); expect(const Locale('en', 'US').toString(), 'en_US'); expect(const Locale('iw').toString(), 'he'); expect(const Locale('iw', 'DD').toString(), 'he_DE'); expect(const Locale('iw', 'DD'), const Locale('he', 'DE')); }); test('Locale.fromSubtags', () { expect(const Locale.fromSubtags().languageCode, 'und'); expect(const Locale.fromSubtags().scriptCode, null); expect(const Locale.fromSubtags().countryCode, null); expect(const Locale.fromSubtags(languageCode: 'en').toString(), 'en'); expect(const Locale.fromSubtags(languageCode: 'en').languageCode, 'en'); expect(const Locale.fromSubtags(scriptCode: 'Latn').toString(), 'und_Latn'); expect(const Locale.fromSubtags(scriptCode: 'Latn').scriptCode, 'Latn'); expect(const Locale.fromSubtags(countryCode: 'US').toString(), 'und_US'); expect(const Locale.fromSubtags(countryCode: 'US').countryCode, 'US'); expect( const Locale.fromSubtags(languageCode: 'es', countryCode: '419') .toString(), 'es_419'); expect( const Locale.fromSubtags(languageCode: 'es', countryCode: '419') .languageCode, 'es'); expect( const Locale.fromSubtags(languageCode: 'es', countryCode: '419') .countryCode, '419'); expect( const Locale.fromSubtags( languageCode: 'zh', scriptCode: 'Hans', countryCode: 'CN') .toString(), 'zh_Hans_CN'); }); test('Locale equality', () { expect( const Locale.fromSubtags(languageCode: 'en'), isNot( const Locale.fromSubtags(languageCode: 'en', scriptCode: 'Latn'))); expect( const Locale.fromSubtags(languageCode: 'en').hashCode, isNot(const Locale.fromSubtags(languageCode: 'en', scriptCode: 'Latn') .hashCode)); }); }
engine/lib/web_ui/test/engine/locale_test.dart/0
{'file_path': 'engine/lib/web_ui/test/engine/locale_test.dart', 'repo_id': 'engine', 'token_count': 1032}
// 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:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } void testMain() { final Float32List points = Float32List(PathIterator.kMaxBufferSize); group('PathIterator', () { test('Should return done verb for empty path', () { final SurfacePath path = SurfacePath(); final PathIterator iter = PathIterator(path.pathRef, false); expect(iter.peek(), SPath.kDoneVerb); expect(iter.next(points), SPath.kDoneVerb); }); test('Should return done when moveTo is last instruction', () { final SurfacePath path = SurfacePath(); path.moveTo(10, 10); final PathIterator iter = PathIterator(path.pathRef, false); expect(iter.peek(), SPath.kMoveVerb); expect(iter.next(points), SPath.kDoneVerb); }); test('Should return lineTo', () { final SurfacePath path = SurfacePath(); path.moveTo(10, 10); path.lineTo(20, 20); final PathIterator iter = PathIterator(path.pathRef, false); expect(iter.peek(), SPath.kMoveVerb); expect(iter.next(points), SPath.kMoveVerb); expect(points[0], 10); expect(iter.next(points), SPath.kLineVerb); expect(points[2], 20); expect(iter.next(points), SPath.kDoneVerb); }); test('Should return extra lineTo if iteration is closed', () { final SurfacePath path = SurfacePath(); path.moveTo(10, 10); path.lineTo(20, 20); final PathIterator iter = PathIterator(path.pathRef, true); expect(iter.peek(), SPath.kMoveVerb); expect(iter.next(points), SPath.kMoveVerb); expect(points[0], 10); expect(iter.next(points), SPath.kLineVerb); expect(points[2], 20); expect(iter.next(points), SPath.kLineVerb); expect(points[2], 10); expect(iter.next(points), SPath.kCloseVerb); expect(iter.next(points), SPath.kDoneVerb); }); test('Should not return extra lineTo if last point is starting point', () { final SurfacePath path = SurfacePath(); path.moveTo(10, 10); path.lineTo(20, 20); path.lineTo(10, 10); final PathIterator iter = PathIterator(path.pathRef, true); expect(iter.peek(), SPath.kMoveVerb); expect(iter.next(points), SPath.kMoveVerb); expect(points[0], 10); expect(iter.next(points), SPath.kLineVerb); expect(points[2], 20); expect(iter.next(points), SPath.kLineVerb); expect(points[2], 10); expect(iter.next(points), SPath.kCloseVerb); expect(iter.next(points), SPath.kDoneVerb); }); test('peek should return lineTo if iteration is closed', () { final SurfacePath path = SurfacePath(); path.moveTo(10, 10); path.lineTo(20, 20); final PathIterator iter = PathIterator(path.pathRef, true); expect(iter.next(points), SPath.kMoveVerb); expect(iter.next(points), SPath.kLineVerb); expect(iter.peek(), SPath.kLineVerb); }); }); }
engine/lib/web_ui/test/engine/surface/path/path_iterator_test.dart/0
{'file_path': 'engine/lib/web_ui/test/engine/surface/path/path_iterator_test.dart', 'repo_id': 'engine', 'token_count': 1264}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @TestOn('browser') library; import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine/dom.dart'; import 'package:ui/src/engine/view_embedder/embedding_strategy/full_page_embedding_strategy.dart'; void main() { internalBootstrapBrowserTest(() => doTests); } void doTests() { late FullPageEmbeddingStrategy strategy; late DomElement target; group('initialize', () { setUp(() { strategy = FullPageEmbeddingStrategy(); target = domDocument.body!; final DomHTMLMetaElement meta = createDomHTMLMetaElement(); meta ..id = 'my_viewport_meta_for_testing' ..name = 'viewport' ..content = 'width=device-width, initial-scale=1.0, ' 'maximum-scale=1.0, user-scalable=no'; domDocument.head!.append(meta); }); test('Prepares target environment', () { DomElement? userMeta = domDocument.querySelector('#my_viewport_meta_for_testing'); expect(userMeta, isNotNull); strategy.initialize( hostElementAttributes: <String, String>{ 'key-for-testing': 'value-for-testing', }, ); expect(target.getAttribute('key-for-testing'), 'value-for-testing', reason: 'Should add attributes as key=value into target element.'); expect(target.getAttribute('flt-embedding'), 'full-page', reason: 'Should identify itself as a specific key=value into the target element.'); // Locate the viewport metas again... userMeta = domDocument.querySelector('#my_viewport_meta_for_testing'); final DomElement? flutterMeta = domDocument.querySelector('meta[name="viewport"]'); expect(userMeta, isNull, reason: 'Should delete previously existing viewport meta tags.'); expect(flutterMeta, isNotNull); expect(flutterMeta!.hasAttribute('flt-viewport'), isTrue, reason: 'Should install flutter viewport meta tag.'); }); }); group('attachViewRoot', () { setUp(() { strategy = FullPageEmbeddingStrategy(); strategy.initialize(); }); test('Should attach glasspane into embedder target (body)', () async { final DomElement glassPane = createDomElement('some-tag-for-tests'); final DomCSSStyleDeclaration style = glassPane.style; expect(glassPane.isConnected, isFalse); expect(style.position, '', reason: 'Should not have any specific position.'); expect(style.top, '', reason: 'Should not have any top/right/bottom/left positioning/inset.'); strategy.attachViewRoot(glassPane); // Assert injection into <body> expect(glassPane.isConnected, isTrue, reason: 'Should inject glassPane into the document.'); expect(glassPane.parent, domDocument.body, reason: 'Should inject glassPane into the <body>'); final DomCSSStyleDeclaration styleAfter = glassPane.style; // Assert required styling to cover the viewport expect(styleAfter.position, 'absolute', reason: 'Should be absolutely positioned.'); expect(styleAfter.top, '0px', reason: 'Should cover the whole viewport.'); expect(styleAfter.right, '0px', reason: 'Should cover the whole viewport.'); expect(styleAfter.bottom, '0px', reason: 'Should cover the whole viewport.'); expect(styleAfter.left, '0px', reason: 'Should cover the whole viewport.'); }); }); group('attachResourcesHost', () { late DomElement glassPane; setUp(() { glassPane = createDomElement('some-tag-for-tests'); strategy = FullPageEmbeddingStrategy(); strategy.initialize(); strategy.attachViewRoot(glassPane); }); test( 'Should attach resources host into target (body), `nextTo` other element', () async { final DomElement resources = createDomElement('resources-host-element'); expect(resources.isConnected, isFalse); strategy.attachResourcesHost(resources, nextTo: glassPane); expect(resources.isConnected, isTrue, reason: 'Should inject resources host somewhere in the document.'); expect(resources.parent, domDocument.body, reason: 'Should inject resources host into the <body>'); expect(resources.nextSibling, glassPane, reason: 'Should be injected `nextTo` the passed element.'); }); }); }
engine/lib/web_ui/test/engine/view_embedder/embedding_strategy/full_page_embedding_strategy_test.dart/0
{'file_path': 'engine/lib/web_ui/test/engine/view_embedder/embedding_strategy/full_page_embedding_strategy_test.dart', 'repo_id': 'engine', 'token_count': 1729}
// 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:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; import 'package:ui/ui.dart' hide TextStyle; import '../../common/test_initialization.dart'; import '../screenshot.dart'; import '../testimage.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } SurfacePaint makePaint() => Paint() as SurfacePaint; Future<void> testMain() async { setUpUnitTests( withImplicitView: true, setUpTestViewDimensions: false, ); const Color red = Color(0xFFFF0000); const Color green = Color(0xFF00FF00); const Color blue = Color(0xFF2196F3); const Color white = Color(0xFFFFFFFF); const Color grey = Color(0xFF808080); const Color black = Color(0xFF000000); final List<List<BlendMode>> modes = <List<BlendMode>>[ <BlendMode>[BlendMode.clear, BlendMode.src, BlendMode.dst, BlendMode.srcOver, BlendMode.dstOver, BlendMode.srcIn, BlendMode.dstIn, BlendMode.srcOut], <BlendMode>[BlendMode.dstOut, BlendMode.srcATop, BlendMode.dstATop, BlendMode.xor, BlendMode.plus, BlendMode.modulate, BlendMode.screen, BlendMode.overlay], <BlendMode>[BlendMode.darken, BlendMode.lighten, BlendMode.colorDodge, BlendMode.hardLight, BlendMode.softLight, BlendMode.difference, BlendMode.exclusion, BlendMode.multiply], <BlendMode>[BlendMode.hue, BlendMode.saturation, BlendMode.color, BlendMode.luminosity], ]; for (int blendGroup = 0; blendGroup < 4; ++blendGroup) { test('Draw image with Group$blendGroup blend modes', () async { final RecordingCanvas rc = RecordingCanvas( const Rect.fromLTRB(0, 0, 400, 400)); rc.save(); final List<BlendMode> blendModes = modes[blendGroup]; for (int row = 0; row < blendModes.length; row++) { // draw white background for first 4, black for next 4 blends. final double top = row * 50.0; rc.drawRect(Rect.fromLTWH(0, top, 200, 50), makePaint() ..color = white); rc.drawRect(Rect.fromLTWH(200, top, 200, 50), makePaint() ..color = grey); final BlendMode blendMode = blendModes[row]; rc.drawImage(createFlutterLogoTestImage(), Offset(0, top), makePaint() ..colorFilter = EngineColorFilter.mode(red, blendMode)); rc.drawImage(createFlutterLogoTestImage(), Offset(50, top), makePaint() ..colorFilter = EngineColorFilter.mode(green, blendMode)); rc.drawImage(createFlutterLogoTestImage(), Offset(100, top), makePaint() ..colorFilter = EngineColorFilter.mode(blue, blendMode)); rc.drawImage(createFlutterLogoTestImage(), Offset(150, top), makePaint() ..colorFilter = EngineColorFilter.mode(black, blendMode)); rc.drawImage(createFlutterLogoTestImage(), Offset(200, top), makePaint() ..colorFilter = EngineColorFilter.mode(red, blendMode)); rc.drawImage(createFlutterLogoTestImage(), Offset(250, top), makePaint() ..colorFilter = EngineColorFilter.mode(green, blendMode)); rc.drawImage(createFlutterLogoTestImage(), Offset(300, top), makePaint() ..colorFilter = EngineColorFilter.mode(blue, blendMode)); rc.drawImage(createFlutterLogoTestImage(), Offset(350, top), makePaint() ..colorFilter = EngineColorFilter.mode(black, blendMode)); } rc.restore(); await canvasScreenshot(rc, 'canvas_image_blend_group$blendGroup'); }, skip: isSafari); } // Regression test for https://github.com/flutter/flutter/issues/56971 test('Draws image and paragraph at same vertical position', () async { final RecordingCanvas rc = RecordingCanvas( const Rect.fromLTRB(0, 0, 400, 400)); rc.save(); rc.drawRect(const Rect.fromLTWH(0, 50, 200, 50), makePaint() ..color = white); rc.drawImage(createFlutterLogoTestImage(), const Offset(0, 50), makePaint() ..colorFilter = const EngineColorFilter.mode(red, BlendMode.srcIn)); final Paragraph paragraph = createTestParagraph(); const double textLeft = 80.0; const double textTop = 50.0; const double widthConstraint = 300.0; paragraph.layout(const ParagraphConstraints(width: widthConstraint)); rc.drawParagraph(paragraph, const Offset(textLeft, textTop)); rc.restore(); await canvasScreenshot(rc, 'canvas_image_blend_and_text'); }); test('Does not re-use styles with same image src', () async { final RecordingCanvas rc = RecordingCanvas( const Rect.fromLTRB(0, 0, 400, 400)); final HtmlImage flutterImage = createFlutterLogoTestImage(); rc.save(); rc.drawRect(const Rect.fromLTWH(0, 50, 200, 50), makePaint() ..color = white); rc.drawImage(flutterImage, const Offset(0, 50), makePaint() ..colorFilter = const EngineColorFilter.mode(red, BlendMode.modulate)); // Expect that the colorFilter is only applied to the first image, since the // colorFilter is applied to a clone of the flutterImage and not the original rc.drawImage(flutterImage, const Offset(0, 100), makePaint()); rc.restore(); await canvasScreenshot(rc, 'canvas_image_same_src'); }); } Paragraph createTestParagraph() { final ParagraphBuilder builder = ParagraphBuilder(ParagraphStyle( fontFamily: 'Ahem', fontStyle: FontStyle.normal, fontWeight: FontWeight.normal, fontSize: 14.0, )); builder.addText('FOO'); return builder.build(); }
engine/lib/web_ui/test/html/compositing/canvas_image_blend_mode_golden_test.dart/0
{'file_path': 'engine/lib/web_ui/test/html/compositing/canvas_image_blend_mode_golden_test.dart', 'repo_id': 'engine', 'token_count': 2232}
// 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:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; import 'package:ui/ui.dart'; import 'package:web_engine_tester/golden_tester.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } Future<void> testMain() async { const Rect region = Rect.fromLTWH(8, 8, 600, 800); // Compensate for old golden tester padding Future<void> testPath(Path path, String goldenFileName) async { const Rect canvasBounds = Rect.fromLTWH(0, 0, 600, 800); final BitmapCanvas bitmapCanvas = BitmapCanvas(canvasBounds, RenderStrategy()); final RecordingCanvas canvas = RecordingCanvas(canvasBounds); SurfacePaint paint = SurfacePaint() ..color = const Color(0x7F7F7F7F) ..style = PaintingStyle.fill; canvas.drawPath(path, paint); paint = SurfacePaint() ..strokeWidth = 2.0 ..color = const Color(0xFF7F007F) ..style = PaintingStyle.stroke; canvas.drawPath(path, paint); canvas.endRecording(); domDocument.body!.append(bitmapCanvas.rootElement); canvas.apply(bitmapCanvas, canvasBounds); await matchGoldenFile('$goldenFileName.png', region: region); bitmapCanvas.rootElement.remove(); } test('render conic with control point horizontal center', () async { const double yStart = 20; const Offset p0 = Offset(25, yStart + 25); const Offset pc = Offset(60, yStart + 150); const Offset p2 = Offset(100, yStart + 50); final Path path = Path(); path.moveTo(p0.dx, p0.dy); path.conicTo(pc.dx, pc.dy, p2.dx, p2.dy, 0.5); path.close(); path.moveTo(p0.dx, p0.dy + 200); path.conicTo(pc.dx, pc.dy + 200, p2.dx, p2.dy + 200, 10); path.close(); await testPath(path, 'render_conic_1_w10'); }); test('render conic with control point left of start point', () async { const double yStart = 20; const Offset p0 = Offset(60, yStart + 25); const Offset pc = Offset(25, yStart + 150); const Offset p2 = Offset(100, yStart + 50); final Path path = Path(); path.moveTo(p0.dx, p0.dy); path.conicTo(pc.dx, pc.dy, p2.dx, p2.dy, 0.5); path.close(); path.moveTo(p0.dx, p0.dy + 200); path.conicTo(pc.dx, pc.dy + 200, p2.dx, p2.dy + 200, 10); path.close(); await testPath(path, 'render_conic_2_w10'); }); test('render conic with control point above start point', () async { const double yStart = 20; const Offset p0 = Offset(25, yStart + 125); const Offset pc = Offset(60, yStart + 50); const Offset p2 = Offset(100, yStart + 150); final Path path = Path(); path.moveTo(p0.dx, p0.dy); path.conicTo(pc.dx, pc.dy, p2.dx, p2.dy, 0.5); path.close(); path.moveTo(p0.dx, p0.dy + 200); path.conicTo(pc.dx, pc.dy + 200, p2.dx, p2.dy + 200, 10); path.close(); await testPath(path, 'render_conic_2'); }); }
engine/lib/web_ui/test/html/drawing/conic_golden_test.dart/0
{'file_path': 'engine/lib/web_ui/test/html/drawing/conic_golden_test.dart', 'repo_id': 'engine', 'token_count': 1222}
// 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:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; import 'package:ui/ui.dart'; // TODO(yjbanov): https://github.com/flutter/flutter/issues/76885 const bool issue76885Exists = true; void main() { internalBootstrapBrowserTest(() => testMain); } void testMain() { test('PathRef.getRRect with radius', () { final SurfacePath path = SurfacePath(); final RRect rrect = RRect.fromLTRBR(0, 0, 10, 10, const Radius.circular(2)); path.addRRect(rrect); expect(path.toRoundedRect(), rrect); }); test('PathRef.getRRect with radius larger than rect', () { final SurfacePath path = SurfacePath(); final RRect rrect = RRect.fromLTRBR(0, 0, 10, 10, const Radius.circular(20)); path.addRRect(rrect); expect( path.toRoundedRect(), // Path.addRRect will correct the radius to fit the dimensions, so when // extracting the rrect out of the path we don't get the original. RRect.fromLTRBR(0, 0, 10, 10, const Radius.circular(5)), ); }); test('PathRef.getRRect with zero radius', () { final SurfacePath path = SurfacePath(); final RRect rrect = RRect.fromLTRBR(0, 0, 10, 10, Radius.zero); path.addRRect(rrect); expect(path.toRoundedRect(), isNull); expect(path.toRect(), rrect.outerRect); }); test('PathRef.getRRect elliptical', () { final SurfacePath path = SurfacePath(); final RRect rrect = RRect.fromLTRBR(0, 0, 10, 10, const Radius.elliptical(2, 4)); path.addRRect(rrect); expect(path.toRoundedRect(), rrect); }); test('PathRef.getRRect elliptical zero x', () { final SurfacePath path = SurfacePath(); final RRect rrect = RRect.fromLTRBR(0, 0, 10, 10, const Radius.elliptical(0, 3)); path.addRRect(rrect); expect(path.toRoundedRect(), isNull); expect(path.toRect(), rrect.outerRect); }); test('PathRef.getRRect elliptical zero y', () { final SurfacePath path = SurfacePath(); final RRect rrect = RRect.fromLTRBR(0, 0, 10, 10, const Radius.elliptical(3, 0)); path.addRRect(rrect); expect(path.toRoundedRect(), isNull); expect(path.toRect(), rrect.outerRect); }); test('PathRef.getRect returns a Rect from a valid Path and null otherwise', () { final SurfacePath path = SurfacePath(); // Draw a line path.moveTo(0,0); path.lineTo(10,0); expect(path.pathRef.getRect(), isNull); // Draw two other lines to get a valid rectangle path.lineTo(10,10); path.lineTo(0,10); expect(path.pathRef.getRect(), const Rect.fromLTWH(0, 0, 10, 10)); }); // Regression test for https://github.com/flutter/flutter/issues/111750 test('PathRef.getRect returns Rect with positive width and height', () { final SurfacePath path = SurfacePath(); // Draw a rectangle starting from bottom right corner path.moveTo(10,10); path.lineTo(0,10); path.lineTo(0,0); path.lineTo(10,0); // pathRef.getRect() should return a rectangle with positive height and width expect(path.pathRef.getRect(), const Rect.fromLTWH(0, 0, 10, 10)); }); // This test demonstrates the issue with attempting to reconstruct an RRect // with imprecision introduced by comparing double values. We should fix this // by removing the need to reconstruct rrects: // https://github.com/flutter/flutter/issues/76885 test('PathRef.getRRect with nearly zero corner', () { final SurfacePath path = SurfacePath(); final RRect original = RRect.fromLTRBR(0, 0, 10, 10, const Radius.elliptical(0.00000001, 5)); path.addRRect(original); expect(path.toRoundedRect(), original); }, skip: issue76885Exists); }
engine/lib/web_ui/test/html/path_ref_test.dart/0
{'file_path': 'engine/lib/web_ui/test/html/path_ref_test.dart', 'repo_id': 'engine', 'token_count': 1367}
// 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:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; import '../../common/fake_asset_manager.dart'; import '../../common/test_initialization.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } void testMain() { group('$HtmlFontCollection', () { setUpUnitTests(); const String testFontUrl = '/assets/fonts/ahem.ttf'; late FakeAssetScope testScope; setUp(() { testScope = fakeAssetManager.pushAssetScope(); testScope.setAssetPassthrough(testFontUrl); // Clear the fonts before the test begins to wipe out the fonts from the // test initialization. domDocument.fonts!.clear(); }); tearDown(() { fakeAssetManager.popAssetScope(testScope); }); group('regular special characters', () { test('Register Asset with no special characters', () async { const String testFontFamily = 'Ahem'; final List<String> fontFamilyList = <String>[]; final HtmlFontCollection collection = HtmlFontCollection(); await collection.loadAssetFonts(FontManifest(<FontFamily>[ FontFamily(testFontFamily, <FontAsset>[ FontAsset(testFontUrl, <String, String>{}) ]) ])); domDocument.fonts! .forEach((DomFontFace f, DomFontFace f2, DomFontFaceSet s) { fontFamilyList.add(f.family!); }); expect(fontFamilyList.length, equals(1)); expect(fontFamilyList.first, 'Ahem'); }); test('Register Asset with white space in the family name', () async { const String testFontFamily = 'Ahem ahem ahem'; final List<String> fontFamilyList = <String>[]; final HtmlFontCollection collection = HtmlFontCollection(); await collection.loadAssetFonts(FontManifest(<FontFamily>[ FontFamily(testFontFamily, <FontAsset>[ FontAsset(testFontUrl, <String, String>{}) ]) ])); domDocument.fonts! .forEach((DomFontFace f, DomFontFace f2, DomFontFaceSet s) { fontFamilyList.add(f.family!); }); expect(fontFamilyList.length, equals(1)); expect(fontFamilyList.first, 'Ahem ahem ahem'); }, // TODO(mdebbar): https://github.com/flutter/flutter/issues/51142 skip: browserEngine == BrowserEngine.webkit); test('Register Asset with capital case letters', () async { const String testFontFamily = 'AhEm'; final List<String> fontFamilyList = <String>[]; final HtmlFontCollection collection = HtmlFontCollection(); await collection.loadAssetFonts(FontManifest(<FontFamily>[ FontFamily(testFontFamily, <FontAsset>[ FontAsset(testFontUrl, <String, String>{}) ]) ])); domDocument.fonts! .forEach((DomFontFace f, DomFontFace f2, DomFontFaceSet s) { fontFamilyList.add(f.family!); }); expect(fontFamilyList.length, equals(1)); expect(fontFamilyList.first, 'AhEm'); }); test('Register Asset with descriptor', () async { const String testFontFamily = 'Ahem'; final List<String> fontFamilyList = <String>[]; final HtmlFontCollection collection = HtmlFontCollection(); await collection.loadAssetFonts(FontManifest(<FontFamily>[ FontFamily(testFontFamily, <FontAsset>[ FontAsset(testFontUrl, <String, String>{ 'weight': 'bold' }) ]) ])); domDocument.fonts! .forEach((DomFontFace f, DomFontFace f2, DomFontFaceSet s) { expect(f.weight, 'bold'); expect(f2.weight, 'bold'); fontFamilyList.add(f.family!); }); expect(fontFamilyList.length, equals(1)); expect(fontFamilyList.first, 'Ahem'); }); }); group('fonts with special characters', () { test('Register Asset twice with special character slash', () async { const String testFontFamily = '/Ahem'; final List<String> fontFamilyList = <String>[]; final HtmlFontCollection collection = HtmlFontCollection(); await collection.loadAssetFonts(FontManifest(<FontFamily>[ FontFamily(testFontFamily, <FontAsset>[ FontAsset(testFontUrl, <String, String>{}) ]) ])); domDocument.fonts! .forEach((DomFontFace f, DomFontFace f2, DomFontFaceSet s) { fontFamilyList.add(f.family!); }); if (browserEngine != BrowserEngine.firefox) { expect(fontFamilyList.length, equals(2)); expect(fontFamilyList, contains("'/Ahem'")); expect(fontFamilyList, contains('/Ahem')); } else { expect(fontFamilyList.length, equals(1)); expect(fontFamilyList.first, '"/Ahem"'); } }, // TODO(mdebbar): https://github.com/flutter/flutter/issues/51142 skip: browserEngine == BrowserEngine.webkit); test('Register Asset twice with exclamation mark', () async { const String testFontFamily = 'Ahem!!ahem'; final List<String> fontFamilyList = <String>[]; final HtmlFontCollection collection = HtmlFontCollection(); await collection.loadAssetFonts(FontManifest(<FontFamily>[ FontFamily(testFontFamily, <FontAsset>[ FontAsset(testFontUrl, <String, String>{}) ]) ])); domDocument.fonts! .forEach((DomFontFace f, DomFontFace f2, DomFontFaceSet s) { fontFamilyList.add(f.family!); }); if (browserEngine != BrowserEngine.firefox) { expect(fontFamilyList.length, equals(2)); expect(fontFamilyList, contains("'Ahem!!ahem'")); expect(fontFamilyList, contains('Ahem!!ahem')); } else { expect(fontFamilyList.length, equals(1)); expect(fontFamilyList.first, '"Ahem!!ahem"'); } }, // TODO(mdebbar): https://github.com/flutter/flutter/issues/51142 skip: browserEngine == BrowserEngine.webkit); test('Register Asset twice with comma', () async { const String testFontFamily = 'Ahem ,ahem'; final List<String> fontFamilyList = <String>[]; final HtmlFontCollection collection = HtmlFontCollection(); await collection.loadAssetFonts(FontManifest(<FontFamily>[ FontFamily(testFontFamily, <FontAsset>[ FontAsset(testFontUrl, <String, String>{}) ]) ])); domDocument.fonts! .forEach((DomFontFace f, DomFontFace f2, DomFontFaceSet s) { fontFamilyList.add(f.family!); }); if (browserEngine != BrowserEngine.firefox) { expect(fontFamilyList.length, equals(2)); expect(fontFamilyList, contains("'Ahem ,ahem'")); expect(fontFamilyList, contains('Ahem ,ahem')); } else { expect(fontFamilyList.length, equals(1)); expect(fontFamilyList.first, '"Ahem ,ahem"'); } }, // TODO(mdebbar): https://github.com/flutter/flutter/issues/51142 skip: browserEngine == BrowserEngine.webkit); test('Register Asset twice with a digit at the start of a token', () async { const String testFontFamily = 'Ahem 1998'; final List<String> fontFamilyList = <String>[]; final HtmlFontCollection collection = HtmlFontCollection(); await collection.loadAssetFonts(FontManifest(<FontFamily>[ FontFamily(testFontFamily, <FontAsset>[ FontAsset(testFontUrl, <String, String>{}) ]) ])); domDocument.fonts! .forEach((DomFontFace f, DomFontFace f2, DomFontFaceSet s) { fontFamilyList.add(f.family!); }); if (browserEngine != BrowserEngine.firefox) { expect(fontFamilyList.length, equals(2)); expect(fontFamilyList, contains('Ahem 1998')); expect(fontFamilyList, contains("'Ahem 1998'")); } else { expect(fontFamilyList.length, equals(1)); expect(fontFamilyList.first, '"Ahem 1998"'); } }, // TODO(mdebbar): https://github.com/flutter/flutter/issues/51142 skip: browserEngine == BrowserEngine.webkit); }); }); }
engine/lib/web_ui/test/html/text/font_collection_test.dart/0
{'file_path': 'engine/lib/web_ui/test/html/text/font_collection_test.dart', 'repo_id': 'engine', 'token_count': 3573}
// 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:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; import 'package:ui/ui.dart' as ui; import 'package:ui/ui_web/src/ui_web.dart' as ui_web; import 'package:web_engine_tester/golden_tester.dart'; import '../common/rendering.dart'; import '../common/test_initialization.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } Future<void> testMain() async { setUpUnitTests( withImplicitView: true, emulateTesterEnvironment: false, setUpTestViewDimensions: false, ); const ui.Rect region = ui.Rect.fromLTWH(0, 0, 300, 300); const String platformViewType = 'test-platform-view'; setUp(() { ui_web.platformViewRegistry.registerViewFactory( platformViewType, (int viewId) { final DomElement element = createDomHTMLDivElement(); element.style.backgroundColor = 'blue'; return element; } ); }); tearDown(() { PlatformViewManager.instance.debugClear(); }); test('picture + overlapping platformView', () async { await _createPlatformView(1, platformViewType); final ui.PictureRecorder recorder = ui.PictureRecorder(); final ui.Canvas canvas = ui.Canvas(recorder); canvas.drawCircle( const ui.Offset(50, 50), 50, ui.Paint() ..style = ui.PaintingStyle.fill ..color = const ui.Color(0xFFFF0000) ); final ui.SceneBuilder sb = ui.SceneBuilder(); sb.pushOffset(0, 0); sb.addPicture(const ui.Offset(100, 100), recorder.endRecording()); sb.addPlatformView( 1, offset: const ui.Offset(125, 125), width: 50, height: 50, ); await renderScene(sb.build()); await matchGoldenFile('picture_platformview_overlap.png', region: region); }); test('platformView sandwich', () async { await _createPlatformView(1, platformViewType); final ui.PictureRecorder recorder = ui.PictureRecorder(); final ui.Canvas canvas = ui.Canvas(recorder); canvas.drawCircle( const ui.Offset(50, 50), 50, ui.Paint() ..style = ui.PaintingStyle.fill ..color = const ui.Color(0xFF00FF00) ); final ui.Picture picture = recorder.endRecording(); final ui.SceneBuilder sb = ui.SceneBuilder(); sb.pushOffset(0, 0); sb.addPicture(const ui.Offset(75, 75), picture); sb.addPlatformView( 1, offset: const ui.Offset(100, 100), width: 100, height: 100, ); sb.addPicture(const ui.Offset(125, 125), picture); await renderScene(sb.build()); await matchGoldenFile('picture_platformview_sandwich.png', region: region); }); test('transformed platformview', () async { await _createPlatformView(1, platformViewType); final ui.PictureRecorder recorder = ui.PictureRecorder(); final ui.Canvas canvas = ui.Canvas(recorder); canvas.drawCircle( const ui.Offset(50, 50), 50, ui.Paint() ..style = ui.PaintingStyle.fill ..color = const ui.Color(0xFFFF0000) ); final ui.SceneBuilder sb = ui.SceneBuilder(); sb.pushOffset(0, 0); sb.addPicture(const ui.Offset(100, 100), recorder.endRecording()); sb.pushTransform(Matrix4.rotationZ(0.1).toFloat64()); sb.addPlatformView( 1, offset: const ui.Offset(125, 125), width: 50, height: 50, ); await renderScene(sb.build()); await matchGoldenFile('platformview_transformed.png', region: region); }); test('platformview with opacity', () async { await _createPlatformView(1, platformViewType); final ui.PictureRecorder recorder = ui.PictureRecorder(); final ui.Canvas canvas = ui.Canvas(recorder); canvas.drawCircle( const ui.Offset(50, 50), 50, ui.Paint() ..style = ui.PaintingStyle.fill ..color = const ui.Color(0xFFFF0000) ); final ui.SceneBuilder sb = ui.SceneBuilder(); sb.pushOffset(0, 0); sb.addPicture(const ui.Offset(100, 100), recorder.endRecording()); sb.pushOpacity(127); sb.addPlatformView( 1, offset: const ui.Offset(125, 125), width: 50, height: 50, ); await renderScene(sb.build()); await matchGoldenFile('platformview_opacity.png', region: region); }); } // Sends a platform message to create a Platform View with the given id and viewType. Future<void> _createPlatformView(int id, String viewType) { final Completer<void> completer = Completer<void>(); const MethodCodec codec = StandardMethodCodec(); ui.PlatformDispatcher.instance.sendPlatformMessage( 'flutter/platform_views', codec.encodeMethodCall(MethodCall( 'create', <String, dynamic>{ 'id': id, 'viewType': viewType, }, )), (dynamic _) => completer.complete(), ); return completer.future; }
engine/lib/web_ui/test/ui/platform_view_test.dart/0
{'file_path': 'engine/lib/web_ui/test/ui/platform_view_test.dart', 'repo_id': 'engine', 'token_count': 1991}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:ui'; void main(List<String> args) { print('child-view: starting'); TestApp app = TestApp(); app.run(); } class TestApp { static const _yellow = Color.fromARGB(255, 255, 255, 0); static const _pink = Color.fromARGB(255, 255, 0, 255); Color _backgroundColor = _pink; void run() { window.onPointerDataPacket = (PointerDataPacket packet) { this.pointerDataPacket(packet); }; window.onMetricsChanged = () { window.scheduleFrame(); }; window.onBeginFrame = (Duration duration) { this.beginFrame(duration); }; window.scheduleFrame(); } void beginFrame(Duration duration) { final pixelRatio = window.devicePixelRatio; final size = window.physicalSize / pixelRatio; final physicalBounds = Offset.zero & size * pixelRatio; final recorder = PictureRecorder(); final canvas = Canvas(recorder, physicalBounds); canvas.scale(pixelRatio, pixelRatio); final paint = Paint()..color = this._backgroundColor; canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), paint); final picture = recorder.endRecording(); final sceneBuilder = SceneBuilder() ..pushClipRect(physicalBounds) ..addPicture(Offset.zero, picture) ..pop(); window.render(sceneBuilder.build()); } void pointerDataPacket(PointerDataPacket packet) { for (final data in packet.data) { if (data.change == PointerChange.down) { this._backgroundColor = _yellow; } } window.scheduleFrame(); } }
engine/shell/platform/fuchsia/flutter/tests/integration/embedder/child-view/lib/child_view.dart/0
{'file_path': 'engine/shell/platform/fuchsia/flutter/tests/integration/embedder/child-view/lib/child_view.dart', 'repo_id': 'engine', 'token_count': 599}
// Copyright 2020 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert'; import 'dart:typed_data'; import 'dart:ui'; import 'dart:zircon'; void main() { print('Launching mouse-input-view'); MyApp app = MyApp(); app.run(); } class MyApp { static const _red = Color.fromARGB(255, 244, 67, 54); static const _orange = Color.fromARGB(255, 255, 152, 0); static const _yellow = Color.fromARGB(255, 255, 235, 59); static const _green = Color.fromARGB(255, 76, 175, 80); static const _blue = Color.fromARGB(255, 33, 150, 143); static const _purple = Color.fromARGB(255, 156, 39, 176); final List<Color> _colors = <Color>[ _red, _orange, _yellow, _green, _blue, _purple, ]; // Each tap will increment the counter, we then determine what color to choose int _touchCounter = 0; void run() { // Set up window callbacks. window.onPointerDataPacket = (PointerDataPacket packet) { this.pointerDataPacket(packet); }; window.onMetricsChanged = () { window.scheduleFrame(); }; window.onBeginFrame = (Duration duration) { this.beginFrame(duration); }; // The child view should be attached to Scenic now. // Ready to build the scene. window.scheduleFrame(); } void beginFrame(Duration duration) { // Convert physical screen size of device to values final pixelRatio = window.devicePixelRatio; final size = window.physicalSize / pixelRatio; final physicalBounds = Offset.zero & size * pixelRatio; // Set up Canvas that uses the screen size final recorder = PictureRecorder(); final canvas = Canvas(recorder, physicalBounds); canvas.scale(pixelRatio, pixelRatio); // Draw something // Color of the screen is set initially to the first value in _colors // Incrementing _touchCounter will change screen color final paint = Paint()..color = _colors[_touchCounter % _colors.length]; canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), paint); // Build the scene final picture = recorder.endRecording(); final sceneBuilder = SceneBuilder() ..pushClipRect(physicalBounds) ..addPicture(Offset.zero, picture) ..pop(); window.render(sceneBuilder.build()); } void pointerDataPacket(PointerDataPacket packet) async { int nowNanos = System.clockGetMonotonic(); for (PointerData data in packet.data) { print('mouse-input-view received input: ${data.toStringFull()}'); if (data.kind == PointerDeviceKind.mouse) { if (data.change == PointerChange.down) { _touchCounter++; } _reportMouseInput( localX: data.physicalX, localY: data.physicalY, buttons: data.buttons, phase: data.change.name, timeReceived: nowNanos, wheelXPhysicalPixel: data.scrollDeltaX, wheelYPhysicalPixel: data.scrollDeltaY, ); } } window.scheduleFrame(); } void _reportMouseInput( {double localX, double localY, int timeReceived, int buttons, String phase, double wheelXPhysicalPixel, double wheelYPhysicalPixel}) { print('mouse-input-view reporting mouse input to MouseInputListener'); final message = ByteData.sublistView(utf8.encode(json.encode({ 'method': 'MouseInputListener.ReportMouseInput', 'local_x': localX, 'local_y': localY, 'time_received': timeReceived, 'component_name': 'touch-input-view', 'buttons': buttons, 'phase': 'asdf', 'wheel_x_physical_pixel': wheelXPhysicalPixel, 'wheel_y_physical_pixel': wheelYPhysicalPixel, }))); PlatformDispatcher.instance .sendPlatformMessage('fuchsia/input_test', message, null); } }
engine/shell/platform/fuchsia/flutter/tests/integration/mouse-input/mouse-input-view/lib/mouse-input-view.dart/0
{'file_path': 'engine/shell/platform/fuchsia/flutter/tests/integration/mouse-input/mouse-input-view/lib/mouse-input-view.dart', 'repo_id': 'engine', 'token_count': 1471}
name: sky_engine version: 0.0.99 author: Flutter Authors <flutter-dev@googlegroups.com> description: Dart SDK extensions for dart:ui homepage: http://flutter.io # sky_engine requires sdk_ext support in the analyzer which was added in 1.11.x environment: sdk: '>=3.2.0-0 <4.0.0'
engine/sky/packages/sky_engine/pubspec.yaml/0
{'file_path': 'engine/sky/packages/sky_engine/pubspec.yaml', 'repo_id': 'engine', 'token_count': 102}
// Copyright 2021 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:io'; import 'package:litetest/litetest.dart'; import 'http_disallow_http_connections_test.dart'; void main() { test('Normal HTTP request succeeds', () async { final String host = await getLocalHostIP(); await bindServerAndTest(host, (HttpClient httpClient, Uri uri) async { await httpClient.getUrl(uri); }); }); test('We can ban HTTP explicitly.', () async { final String host = await getLocalHostIP(); await bindServerAndTest(host, (HttpClient httpClient, Uri uri) async { asyncExpectThrows<UnsupportedError>( () async => runZoned(() => httpClient.getUrl(uri), zoneValues: <dynamic, dynamic>{#flutter.io.allow_http: false})); }); }); }
engine/testing/dart/http_allow_http_connections_test.dart/0
{'file_path': 'engine/testing/dart/http_allow_http_connections_test.dart', 'repo_id': 'engine', 'token_count': 314}
// 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:io'; import 'package:path/path.dart' as path; String _flutterBuildDirectoryPath() { assert(Platform.environment.containsKey('FLUTTER_BUILD_DIRECTORY')); return Platform.environment['FLUTTER_BUILD_DIRECTORY']!; } const String _testPath = 'gen/flutter/lib/ui/fixtures/shaders'; /// Gets the [Directory] shader files that are generated by `lib/ui/fixtures/shaders`. /// /// `folderName` is a leaf folder within the generated directory. Directory shaderDirectory(String leafFolderName) { return Directory(path.joinAll(<String>[ ...path.split(_flutterBuildDirectoryPath()), ...path.split(_testPath), leafFolderName, ])); }
engine/testing/dart/shader_test_file_utils.dart/0
{'file_path': 'engine/testing/dart/shader_test_file_utils.dart', 'repo_id': 'engine', 'token_count': 255}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:convert'; import 'dart:typed_data'; /// A screenshot from the Android emulator. class Screenshot { Screenshot(this.filename, this.fileContent, this.pixelCount); /// The name of the screenshot. final String filename; /// The binary content of the screenshot. final Uint8List fileContent; /// The number of pixels in the screenshot. final int pixelCount; } /// Takes the input stream and transforms it into [Screenshot]s. class ScreenshotBlobTransformer extends StreamTransformerBase<Uint8List, Screenshot> { const ScreenshotBlobTransformer(); @override Stream<Screenshot> bind(Stream<Uint8List> stream) async* { final BytesBuilder pending = BytesBuilder(); await for (final Uint8List blob in stream) { pending.add(blob); if (pending.length < 12) { continue; } // See ScreenshotUtil#writeFile in ScreenshotUtil.java for producer side. final Uint8List bytes = pending.toBytes(); final ByteData byteData = bytes.buffer.asByteData(); int off = 0; final int fnameLen = byteData.getInt32(off); off += 4; final int fcontentLen = byteData.getInt32(off); off += 4; final int pixelCount = byteData.getInt32(off); off += 4; assert(fnameLen > 0); assert(fcontentLen > 0); assert(pixelCount > 0); if (pending.length < off + fnameLen) { continue; } final String filename = utf8.decode(bytes.buffer.asUint8List(off, fnameLen)); off += fnameLen; if (pending.length < off + fcontentLen) { continue; } final Uint8List fileContent = bytes.buffer.asUint8List(off, fcontentLen); off += fcontentLen; pending.clear(); pending.add(bytes.buffer.asUint8List(off)); yield Screenshot('$filename.png', fileContent, pixelCount); } } }
engine/testing/scenario_app/bin/utils/screenshot_transformer.dart/0
{'file_path': 'engine/testing/scenario_app/bin/utils/screenshot_transformer.dart', 'repo_id': 'engine', 'token_count': 743}
// 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 'dart:ui'; import 'package:vector_math/vector_math_64.dart'; import 'scenario.dart'; /// Sends the received locale data back as semantics information. class LocaleInitialization extends Scenario { /// Constructor LocaleInitialization(super.view); int _tapCount = 0; /// Start off by sending the supported locales list via semantics. @override void onBeginFrame(Duration duration) { // Doesn't matter what we draw. Just paint white. final SceneBuilder builder = SceneBuilder(); final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); canvas.drawRect( Rect.fromLTWH(0, 0, view.physicalSize.width, view.physicalSize.height), Paint()..color = const Color.fromARGB(255, 255, 255, 255), ); final Picture picture = recorder.endRecording(); builder.addPicture( Offset.zero, picture, ); final Scene scene = builder.build(); view.render(scene); scene.dispose(); // On the first frame, pretend that it drew a text field. Send the // corresponding semantics tree comprised of 1 node with the locale data // as the label. final SemanticsUpdateBuilder semanticsUpdateBuilder = SemanticsUpdateBuilder()..updateNode( id: 0, // SemanticsFlag.isTextField. flags: 16, // SemanticsAction.tap. actions: 1, rect: const Rect.fromLTRB(0.0, 0.0, 414.0, 48.0), identifier: '', label: view.platformDispatcher.locales.toString(), labelAttributes: <StringAttribute>[], textDirection: TextDirection.ltr, textSelectionBase: -1, textSelectionExtent: -1, platformViewId: -1, maxValueLength: -1, currentValueLength: 0, scrollChildren: 0, scrollIndex: 0, scrollPosition: 0.0, scrollExtentMax: 0.0, scrollExtentMin: 0.0, transform: Matrix4.identity().storage, elevation: 0.0, thickness: 0.0, hint: '', hintAttributes: <StringAttribute>[], value: '', valueAttributes: <StringAttribute>[], increasedValue: '', increasedValueAttributes: <StringAttribute>[], decreasedValue: '', decreasedValueAttributes: <StringAttribute>[], tooltip: '', childrenInTraversalOrder: Int32List(0), childrenInHitTestOrder: Int32List(0), additionalActions: Int32List(0), ); final SemanticsUpdate semanticsUpdate = semanticsUpdateBuilder.build(); view.updateSemantics(semanticsUpdate); } /// Handle taps. /// /// Send changing information via semantics on each successive tap. @override void onPointerDataPacket(PointerDataPacket packet) { String label = ''; switch(_tapCount) { case 1: { // Set label to string data we wish to pass on first frame. label = '1'; break; } // Expand for other test cases. } final SemanticsUpdateBuilder semanticsUpdateBuilder = SemanticsUpdateBuilder()..updateNode( id: 0, // SemanticsFlag.isTextField. flags: 16, // SemanticsAction.tap. actions: 1, rect: const Rect.fromLTRB(0.0, 0.0, 414.0, 48.0), identifier: '', label: label, labelAttributes: <StringAttribute>[], textDirection: TextDirection.ltr, textSelectionBase: 0, textSelectionExtent: 0, platformViewId: -1, maxValueLength: -1, currentValueLength: 0, scrollChildren: 0, scrollIndex: 0, scrollPosition: 0.0, scrollExtentMax: 0.0, scrollExtentMin: 0.0, transform: Matrix4.identity().storage, elevation: 0.0, thickness: 0.0, hint: '', hintAttributes: <StringAttribute>[], value: '', valueAttributes: <StringAttribute>[], increasedValue: '', increasedValueAttributes: <StringAttribute>[], decreasedValue: '', decreasedValueAttributes: <StringAttribute>[], tooltip: '', childrenInTraversalOrder: Int32List(0), childrenInHitTestOrder: Int32List(0), additionalActions: Int32List(0), ); final SemanticsUpdate semanticsUpdate = semanticsUpdateBuilder.build(); view.updateSemantics(semanticsUpdate); _tapCount++; } }
engine/testing/scenario_app/lib/src/locale_initialization.dart/0
{'file_path': 'engine/testing/scenario_app/lib/src/locale_initialization.dart', 'repo_id': 'engine', 'token_count': 1813}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert' show LineSplitter, utf8; import 'dart:io' as io; import 'package:meta/meta.dart'; import 'package:path/path.dart' as path; import 'package:process_runner/process_runner.dart'; import 'options.dart'; /// The url prefix for issues that must be attached to the directive in files /// that disables linting. const String issueUrlPrefix = 'https://github.com/flutter/flutter/issues'; /// Lint actions to apply to a file. enum LintAction { /// Run the linter over the file. lint, /// Ignore files under third_party/. skipThirdParty, /// Ignore due to a well-formed FLUTTER_NOLINT comment. skipNoLint, /// Fail due to a malformed FLUTTER_NOLINT comment. failMalformedNoLint, /// Ignore because the file doesn't exist locally. skipMissing, } /// A compilation command and methods to generate the lint command and job for /// it. class Command { /// Generate a [Command] from a [Map]. Command.fromMap(Map<String, dynamic> map) : directory = io.Directory(map['directory'] as String).absolute, command = map['command'] as String { filePath = path.normalize(path.join( directory.path, map['file'] as String, )); } /// The working directory of the command. final io.Directory directory; /// The compilation command. final String command ; /// The file on which the command operates. late final String filePath; static final RegExp _pathRegex = RegExp(r'\S*clang/bin/clang'); static final RegExp _argRegex = RegExp(r'-MF \S*'); // Filter out any extra commands that were appended to the compile command. static final RegExp _extraCommandRegex = RegExp(r'&&.*$'); String? _tidyArgs; /// The command line arguments of the command. String get tidyArgs { return _tidyArgs ??= (() { String result = command; result = result.replaceAll(_pathRegex, ''); result = result.replaceAll(_argRegex, ''); result = result.replaceAll(_extraCommandRegex, ''); return result; })(); } String? _tidyPath; /// The command but with clang-tidy instead of clang. String get tidyPath { return _tidyPath ??= _pathRegex.stringMatch(command)?.replaceAll( 'clang/bin/clang', 'clang/bin/clang-tidy', ) ?? ''; } /// Whether this command operates on any of the files in `queries`. bool containsAny(List<io.File> queries) { return queries.indexWhere( (io.File query) => path.equals(query.path, filePath), ) != -1; } static final RegExp _nolintRegex = RegExp( r'//\s*FLUTTER_NOLINT(: https://github.com/flutter/flutter/issues/\d+)?', ); /// The type of lint that is appropriate for this command. late final Future<LintAction> lintAction = getLintAction(filePath); /// Determine the lint action for the file at `path`. @visibleForTesting static Future<LintAction> getLintAction(String filePath) async { if (path.split(filePath).contains('third_party')) { return LintAction.skipThirdParty; } final io.File file = io.File(filePath); if (!file.existsSync()) { return LintAction.skipMissing; } final Stream<String> lines = file.openRead() .transform(utf8.decoder) .transform(const LineSplitter()); return lintActionFromContents(lines); } /// Determine the lint action for the file with contents `lines`. @visibleForTesting static Future<LintAction> lintActionFromContents(Stream<String> lines) async { // Check for FlUTTER_NOLINT at top of file. await for (final String line in lines) { final RegExpMatch? match = _nolintRegex.firstMatch(line); if (match != null) { return match.group(1) != null ? LintAction.skipNoLint : LintAction.failMalformedNoLint; } else if (line.isNotEmpty && line[0] != '\n' && line[0] != '/') { // Quick out once we find a line that isn't empty or a comment. The // FLUTTER_NOLINT must show up before the first real code. return LintAction.lint; } } return LintAction.lint; } /// The job for the process runner for the lint needed for this command. WorkerJob createLintJob(Options options) { final List<String> args = <String>[ filePath, '--warnings-as-errors=${options.warningsAsErrors ?? '*'}', if (options.checks != null) options.checks!, if (options.fix) ...<String>[ '--fix', '--format-style=file', ], if (options.enableCheckProfile) '--enable-check-profile', '--', ]; args.addAll(tidyArgs.split(' ')); final String clangTidyPath = options.clangTidyPath?.path ?? tidyPath; return WorkerJob( <String>[clangTidyPath, ...args], workingDirectory: directory, name: 'clang-tidy on $filePath', printOutput: options.verbose, ); } }
engine/tools/clang_tidy/lib/src/command.dart/0
{'file_path': 'engine/tools/clang_tidy/lib/src/command.dart', 'repo_id': 'engine', 'token_count': 1793}
name: Build on: push: pull_request: schedule: # runs the CI everyday at 10AM - cron: "0 10 * * *" jobs: build: runs-on: ${{ matrix.os }} strategy: matrix: os: [ubuntu-latest, windows-latest] channel: - stable steps: - uses: actions/checkout@v2 - uses: subosito/flutter-action@v1 with: channel: ${{ matrix.channel }} - name: Add pub cache bin to PATH run: echo "$HOME/.pub-cache/bin" >> $GITHUB_PATH - name: Add pub cache to PATH run: echo "PUB_CACHE="$HOME/.pub-cache"" >> $GITHUB_ENV - name: Install dependencies run: dart pub get && cd flutter_package && flutter pub get && cd - - name: Check format run: dart format --set-exit-if-changed . - name: Analyze run: dart analyze - name: Run tests run: dart test - name: Upload coverage to codecov run: curl -s https://codecov.io/bash | bash
expect_error/.github/workflows/build.yml/0
{'file_path': 'expect_error/.github/workflows/build.yml', 'repo_id': 'expect_error', 'token_count': 440}
import 'dart:io'; import 'package:analyzer/dart/analysis/results.dart'; import 'package:analyzer/diagnostic/diagnostic.dart'; import 'package:analyzer/error/error.dart'; import 'package:analyzer/source/source_range.dart'; import 'package:build_test/build_test.dart'; import 'package:collection/collection.dart'; import 'package:package_config/package_config.dart'; import 'package:path/path.dart' as _path; import 'package:pubspec/pubspec.dart'; import 'package:stack_trace/stack_trace.dart'; import 'package:test/expect.dart'; import 'package:test/test.dart'; /// The representation of a dart file within a dart package class Library { /// The representation of a dart file within a dart package Library({ required this.packageName, required this.path, this.packageConfig, }); /// Resolve a [Library] defined in a separate package, obtaining [packageConfig] /// from that package's package_config.json. static Future<Library> custom({ required String packageName, required String path, required String packageRoot, }) async { final packageConfigFile = File(_path.join(packageRoot, '.dart_tool', 'package_config.json')); final packageConfig = PackageConfig.parseString( packageConfigFile.readAsStringSync(), packageConfigFile.absolute.uri, ); return Library( packageName: packageName, path: _path.normalize(path).replaceAll(r'\', '/'), packageConfig: packageConfig, ); } /// Decode the [StackTrace] to try and extract information about the current /// library. /// /// This should only be used within the "main" of a test file. static Future<Library> parseFromStacktrace() async { const testFilePath = '___temporary_test____.dart'; final pubSpec = await PubSpec.load(Directory.current); // Relying on the Stacktrace to obtain the current test file name final stacktrace = Trace.from(StackTrace.current); final mainFrame = stacktrace.frames .lastWhereOrNull((element) => element.uri.isScheme('FILE')); if (mainFrame == null || pubSpec.name == null) { throw StateError('Failed to determine the current test file location'); } final tempTestFilePath = _path.join( Directory.fromUri(Uri.file(mainFrame.library)).parent.path, testFilePath, ); return Library( packageName: pubSpec.name!, path: _path.normalize(tempTestFilePath).replaceAll(r'\', '/'), // packageConfig: null, // use package definition from the current Isolate ); } /// The name of the package that this library belongs to. final String packageName; /// The absolute path to a dart file. final String path; /// The package configuration for this library. final PackageConfig? packageConfig; /// Creates an instance of [Code] from a raw string, to be used by [compiles]. Code withCode(String code) => Code(code: code, library: this); } /// The representation of the source code for a dart file class Code { /// The representation of the source code for a dart file Code({required this.code, required this.library}); /// The file content final String code; /// Metadata about the file final Library library; } /// Analyze a [Code] instance and verify that it has no error. /// /// If the code contains comments under the form of `// expect-error: ERROR_CODE`, /// [compiles] will expect that the very next line of code has an error with /// the matching code. /// /// If an `// expect-error` is added, but the next line doesn't have an error /// with the matching code, the expectation will fail. /// If the code has an error without a matching `// expect-error` on the previous /// line, the expectation will also fail. /// Otherwise, the expectation will pass. /// /// /// A common usage would be: /// /// ```dart /// import 'package:expect_error/src/expect_error.dart'; /// import 'package:test/test.dart'; /// /// Future<void> main() async { /// final library = await Library.parseFromStacktrace(); /// /// test('String is not assignable to int', () async { /// await expectLater(library.withCode(''' /// class Counter { /// int count = 0; /// } /// /// void main() { /// final counter = Counter(); /// // expect-error: INVALID_ASSIGNMENT /// counter.count = 'string'; /// } /// '''), compiles); /// }); /// } /// ``` final compiles = _CompileMatcher(); class _CompileMatcher extends Matcher { @override Description describe(Description description) => description.add('Dart code that compiles'); @override bool matches(covariant Code source, Map<Object?, Object?> matchState) { expectLater(_compile(source), completes); return true; } } class _ExpectErrorCode { _ExpectErrorCode(this.code, {required this.startOffset}); final String code; final int startOffset; bool visited = false; } Future<void> _compile(Code code) async { final source = ''' library main; ${code.code}'''; final expectedErrorRegex = RegExp(r'\/\/ ?expect-error:(.+)$', multiLine: true); final expectErrorCodes = expectedErrorRegex .allMatches(source) .map((match) { return match .group(1)! .split(',') .map((e) => _ExpectErrorCode(e.trim(), startOffset: match.start)); }) .flattened .toList(); bool verifyAnalysisError(AnalysisError error) { final sourceBeforeError = error.source.contents.data.substring(0, error.offset); final previousLineRegex = RegExp(r'([^\n]*)\n.*?$'); final previousLine = previousLineRegex.firstMatch(sourceBeforeError)!; final previousLineRange = SourceRange(previousLine.start, previousLine.group(1)!.length); for (final code in expectErrorCodes) { if (previousLineRange.contains(code.startOffset) && code.code == error.errorCode.name) { code.visited = true; return true; } } return false; } // '.dart' has the length 5 final tempFileName = '${code.library.path.substring(0, code.library.path.length - 5)}_${source.hashCode}.dart'; final main = await resolveSources( {'${code.library.packageName}|$tempFileName': source}, (r) => r.findLibraryByName('main'), packageConfig: code.library.packageConfig, ); final errorResult = await main!.session.getErrors( '/${code.library.packageName}/$tempFileName', ) as ErrorsResult; final criticalErrors = errorResult.errors .where((element) => element.severity == Severity.error) .toList(); for (final error in criticalErrors) { if (!verifyAnalysisError(error)) { fail( 'No expect-error found for code ${error.errorCode.name} ' 'but an error was found: ${error.message}', ); } } for (final expectError in expectErrorCodes) { if (!expectError.visited) { fail( 'Expected error with code ${expectError.code} but none were found', ); } } }
expect_error/lib/src/expect_error.dart/0
{'file_path': 'expect_error/lib/src/expect_error.dart', 'repo_id': 'expect_error', 'token_count': 2338}
import 'package:fast_noise_flutter_example/forms/field.dart'; import 'package:fast_noise_flutter_example/forms/field_wrapper.dart'; import 'package:flutter/material.dart'; class StringField extends Field<String> { const StringField({ required super.title, required super.value, required super.setValue, super.key, super.enabled, }); @override StringFieldState createState() => StringFieldState(); } class StringFieldState extends State<StringField> { final _controller = TextEditingController(); @override void initState() { super.initState(); _controller.text = widget.value; _controller.addListener(() { if (widget.enabled) { widget.setValue(_controller.text); } }); } @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return FieldWrapper( title: widget.title, child: TextField( enabled: widget.enabled, readOnly: !widget.enabled, decoration: InputDecoration( border: const OutlineInputBorder(), fillColor: Colors.grey, filled: !widget.enabled, disabledBorder: const OutlineInputBorder( borderSide: BorderSide(color: Colors.grey), ), enabled: widget.enabled, ), controller: _controller, ), ); } }
fast_noise/example/lib/forms/string_field.dart/0
{'file_path': 'fast_noise/example/lib/forms/string_field.dart', 'repo_id': 'fast_noise', 'token_count': 544}
import 'package:fast_noise/fast_noise.dart'; class SimplexFractalNoise implements Noise2And3, Noise2Int, Noise3Int { final SimplexNoise baseNoise; final int seed; final double frequency; final FractalType fractalType; final int octaves; final double gain; final double lacunarity; final double fractalBounding; SimplexFractalNoise({ this.seed = 1337, this.frequency = .01, this.fractalType = FractalType.fbm, this.octaves = 3, this.gain = .5, this.lacunarity = 2.0, }) : baseNoise = SimplexNoise( seed: seed, frequency: frequency, ), fractalBounding = calculateFractalBounding(octaves, gain); @override double getNoiseInt3(int x, int y, int z) { final xd = x.toDouble(); final yd = y.toDouble(); final zd = z.toDouble(); return getNoise3(xd, yd, zd); } @override double getNoise3(double x, double y, double z) { final dx = (x * frequency).toInt(); final dy = (y * frequency).toInt(); final dz = (z * frequency).toInt(); switch (fractalType) { case FractalType.fbm: return singleSimplexFractalFBM3(dx, dy, dz); case FractalType.billow: return singleSimplexFractalBillow3(dx, dy, dz); case FractalType.rigidMulti: return singleSimplexFractalRigidMulti3(dx, dy, dz); } } double singleSimplexFractalFBM3(int x, int y, int z) { var seed = this.seed; var sum = baseNoise.singleSimplex3(seed, x, y, z); var amp = 1.0; var x1 = x.toDouble(); var y1 = y.toDouble(); var z1 = z.toDouble(); for (var i = 1; i < octaves; i++) { x1 *= lacunarity; y1 *= lacunarity; z1 *= lacunarity; amp *= gain; sum += baseNoise.singleSimplex3(++seed, x1.toInt(), y1.toInt(), z1.toInt()) * amp; } return sum * fractalBounding; } double singleSimplexFractalBillow3(int x, int y, int z) { var seed = this.seed; var sum = baseNoise.singleSimplex3(seed, x, y, z).abs() * 2.0 - 1.0; var amp = 1.0; var x1 = x.toDouble(); var y1 = y.toDouble(); var z1 = z.toDouble(); for (var i = 1; i < octaves; i++) { x1 *= lacunarity; y1 *= lacunarity; z1 *= lacunarity; amp *= gain; sum += (baseNoise .singleSimplex3( ++seed, x1.toInt(), y1.toInt(), z1.toInt(), ) .abs() * 2.0 - 1.0) * amp; } return sum * fractalBounding; } double singleSimplexFractalRigidMulti3(int x, int y, int z) { var seed = this.seed; var sum = 1.0 - baseNoise.singleSimplex3(seed, x, y, z).abs(); var amp = 1.0; var x1 = x.toDouble(); var y1 = y.toDouble(); var z1 = z.toDouble(); for (var i = 1; i < octaves; i++) { x1 *= lacunarity; y1 *= lacunarity; z1 *= lacunarity; amp *= gain; final baseValue = baseNoise.singleSimplex3( ++seed, x1.toInt(), y1.toInt(), z1.toInt(), ); sum -= (1.0 - baseValue.abs()) * amp; } return sum; } @override double getNoiseInt2(int x, int y) { final xd = x.toDouble(); final yd = y.toDouble(); return getNoise2(xd, yd); } @override double getNoise2(double x, double y) { final dx = (x * frequency).toInt(); final dy = (y * frequency).toInt(); switch (fractalType) { case FractalType.fbm: return singleSimplexFractalFBM2(dx, dy); case FractalType.billow: return singleSimplexFractalBillow2(dx, dy); case FractalType.rigidMulti: return singleSimplexFractalRigidMulti2(dx, dy); } } double singleSimplexFractalFBM2(int x, int y) { var seed = this.seed; var sum = baseNoise.singleSimplex2(seed, x, y); var amp = 1.0; var x1 = x.toDouble(); var y1 = y.toDouble(); for (var i = 1; i < octaves; i++) { x1 *= lacunarity; y1 *= lacunarity; amp *= gain; sum += baseNoise.singleSimplex2(++seed, x1.toInt(), y1.toInt()) * amp; } return sum * fractalBounding; } double singleSimplexFractalBillow2(int x, int y) { var seed = this.seed; var sum = baseNoise.singleSimplex2(seed, x, y).abs() * 2.0 - 1.0; var amp = 1.0; var x1 = x.toDouble(); var y1 = y.toDouble(); for (var i = 1; i < octaves; i++) { x1 *= lacunarity; y1 *= lacunarity; amp *= gain; final baseValue = baseNoise.singleSimplex2( ++seed, x1.toInt(), y1.toInt(), ); sum += (baseValue.abs() * 2.0 - 1.0) * amp; } return sum * fractalBounding; } double singleSimplexFractalRigidMulti2(int x, int y) { var seed = this.seed; var sum = 1.0 - baseNoise.singleSimplex2(seed, x, y).abs(); var amp = 1.0; var x1 = x.toDouble(); var y1 = y.toDouble(); for (var i = 1; i < octaves; i++) { x1 *= lacunarity; y1 *= lacunarity; amp *= gain; final baseValue = baseNoise.singleSimplex2( ++seed, x1.toInt(), y1.toInt(), ); sum -= (1.0 - baseValue.abs()) * amp; } return sum; } }
fast_noise/lib/src/noise/simplex_fractal.dart/0
{'file_path': 'fast_noise/lib/src/noise/simplex_fractal.dart', 'repo_id': 'fast_noise', 'token_count': 2583}
include: package:flame_lint/analysis_options.yaml linter: rules: avoid_catches_without_on_clauses: false constant_identifier_names: false
fire-atlas/fire_atlas_editor/analysis_options.yaml/0
{'file_path': 'fire-atlas/fire_atlas_editor/analysis_options.yaml', 'repo_id': 'fire-atlas', 'token_count': 54}
import 'package:fire_atlas_editor/store/actions/atlas_actions.dart'; import 'package:fire_atlas_editor/store/actions/editor_actions.dart'; import 'package:fire_atlas_editor/store/store.dart'; import 'package:fire_atlas_editor/utils/validators.dart'; import 'package:fire_atlas_editor/widgets/button.dart'; import 'package:fire_atlas_editor/widgets/input_text_row.dart'; import 'package:fire_atlas_editor/widgets/text.dart'; import 'package:flame_fire_atlas/flame_fire_atlas.dart'; import 'package:flutter/material.dart'; import 'package:slices/slices.dart'; class SelectionForm extends StatefulWidget { final Offset? selectionStart; final Offset? selectionEnd; final AnimationSelection? editingSelection; const SelectionForm({ super.key, this.selectionStart, this.selectionEnd, this.editingSelection, }); @override State createState() => _SelectionFormState(); } enum SelectionType { SPRITE, ANIMATION, } class _SelectionFormState extends State<SelectionForm> { SelectionType? _selectionType; final selectionNameController = TextEditingController(); final frameCountController = TextEditingController(); final stepTimeController = TextEditingController(); bool _animationLoop = true; @override void initState() { super.initState(); if (widget.editingSelection != null) { final selection = widget.editingSelection!; selectionNameController.text = selection.id; frameCountController.text = selection.frameCount.toString(); stepTimeController.text = (selection.stepTime * 1000).toInt().toString(); _selectionType = SelectionType.ANIMATION; } } void _chooseSelectionType(SelectionType type) { setState(() { _selectionType = type; }); } Selection _fillSelectionBaseValues() { if (widget.selectionEnd == null) { throw 'Selection end is null'; } if (widget.selectionStart == null) { throw 'Selection start is null'; } final selectionEnd = widget.selectionEnd!; final selectionStart = widget.selectionStart!; final w = (selectionEnd.dx - selectionStart.dx).toInt(); final h = (selectionEnd.dy - selectionStart.dy).toInt(); final selection = Selection( id: selectionNameController.text, x: selectionStart.dx.toInt(), y: selectionStart.dy.toInt(), w: w, h: h, ); return selection; } void _createSprite() { final store = SlicesProvider.of<FireAtlasState>(context); if (selectionNameController.text.isNotEmpty) { final info = _fillSelectionBaseValues(); store.dispatch( SetSelectionAction( selection: SpriteSelection(info: info), ), ); store.dispatch(CloseEditorModal()); } else { store.dispatch( CreateMessageAction( type: MessageType.ERROR, message: 'You must inform the selection name', ), ); } } void _createAnimation() { final store = SlicesProvider.of<FireAtlasState>(context); if (selectionNameController.text.isNotEmpty && frameCountController.text.isNotEmpty && stepTimeController.text.isNotEmpty) { if (!isValidNumber(frameCountController.text)) { store.dispatch( CreateMessageAction( type: MessageType.ERROR, message: 'Frame count is not a valid number', ), ); return; } if (!isValidNumber(stepTimeController.text)) { store.dispatch( CreateMessageAction( type: MessageType.ERROR, message: 'Step time is not a valid number', ), ); return; } final frameCount = int.parse(frameCountController.text); final stepTime = int.parse(stepTimeController.text) / 1000; final selectionToSave = widget.editingSelection == null ? AnimationSelection( info: _fillSelectionBaseValues(), frameCount: frameCount, stepTime: stepTime, loop: _animationLoop, ) : widget.editingSelection! ..frameCount = frameCount ..stepTime = stepTime ..loop = _animationLoop; store.dispatch( SetSelectionAction(selection: selectionToSave), ); store.dispatch(CloseEditorModal()); } else { store.dispatch( CreateMessageAction( type: MessageType.ERROR, message: 'All fields are required', ), ); } } @override Widget build(BuildContext ctx) { final children = <Widget>[]; children ..add(const SizedBox(height: 5)) ..add( FTitle( title: '${widget.editingSelection == null ? 'New' : 'Edit'} ' 'selection item', ), ) ..add( InputTextRow( label: 'Selection name:', inputController: selectionNameController, enabled: widget.editingSelection == null, autofocus: true, ), ) ..add(const SizedBox(height: 10)); if (widget.editingSelection == null) { children ..add(const Text('Selection type')) ..add(const SizedBox(height: 10)) ..add( Container( width: 200, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ FButton( label: 'Sprite', selected: _selectionType == SelectionType.SPRITE, onSelect: () => _chooseSelectionType(SelectionType.SPRITE), ), FButton( label: 'Animation', selected: _selectionType == SelectionType.ANIMATION, onSelect: () => _chooseSelectionType(SelectionType.ANIMATION), ), ], ), ), ); } if (_selectionType == SelectionType.SPRITE) { children ..add(const SizedBox(height: 20)) ..add( FButton( label: 'Create sprite', onSelect: _createSprite, ), ); } else if (_selectionType == SelectionType.ANIMATION) { children ..add(const SizedBox(height: 10)) ..add( InputTextRow( label: 'Frame count:', inputController: frameCountController, ), ) ..add(const SizedBox(height: 10)); children ..add( InputTextRow( label: 'Step time (in millis):', inputController: stepTimeController, ), ) ..add(const SizedBox(height: 20)); children ..add(const FLabel(label: 'Loop animation', fontSize: 12)) ..add( Checkbox( value: _animationLoop, onChanged: (v) { if (v != null) { setState(() => _animationLoop = v); } }, ), ) ..add(const SizedBox(height: 20)); children.add( FButton( label: '${widget.editingSelection == null ? 'Create' : 'Save'} ' 'animation', onSelect: _createAnimation, ), ); } return Container( width: 400, padding: const EdgeInsets.only(left: 20, right: 20), child: Column( children: children, ), ); } }
fire-atlas/fire_atlas_editor/lib/screens/editor_screen/widgets/selection_canvas/selection_form.dart/0
{'file_path': 'fire-atlas/fire_atlas_editor/lib/screens/editor_screen/widgets/selection_canvas/selection_form.dart', 'repo_id': 'fire-atlas', 'token_count': 3285}
import 'package:fire_atlas_editor/services/storage/storage.dart'; import 'package:fire_atlas_editor/store/store.dart'; import 'package:flutter/material.dart'; import 'package:slices/slices.dart'; class SetCanvasSelection extends SlicesAction<FireAtlasState> { final Rect selection; SetCanvasSelection(this.selection); @override FireAtlasState perform(_, FireAtlasState state) { return state.copyWith( canvasSelection: Nullable(selection), ); } } class OpenEditorModal extends SlicesAction<FireAtlasState> { final Widget modal; final double width; final double? height; OpenEditorModal(this.modal, this.width, [this.height]); @override FireAtlasState perform(_, FireAtlasState state) { return state.copyWith( modal: Nullable( ModalState( child: modal, width: width, height: height, ), ), ); } } class CloseEditorModal extends SlicesAction<FireAtlasState> { @override FireAtlasState perform(_, FireAtlasState state) { return state.copyWith(modal: Nullable(null)); } } class CreateMessageAction extends SlicesAction<FireAtlasState> { final MessageType type; final String message; CreateMessageAction({ required this.type, required this.message, }); @override FireAtlasState perform(_, FireAtlasState state) { final existent = state.messages.where((m) => m.message == message); final newList = state.messages.toList(); if (existent.isEmpty) { final messageObj = Message( type: type, message: message, ); newList.add(messageObj); } return state.copyWith(messages: newList); } } class DismissMessageAction extends SlicesAction<FireAtlasState> { final Message message; DismissMessageAction({ required this.message, }); @override FireAtlasState perform(_, FireAtlasState state) { final newList = state.messages.toList(); newList.removeWhere((m) => m.message == message.message); return state.copyWith(messages: newList); } } class ToggleThemeAction extends AsyncSlicesAction<FireAtlasState> { @override Future<FireAtlasState> perform( SlicesStore<FireAtlasState> store, FireAtlasState state, ) async { final newTheme = state.currentTheme == ThemeMode.dark ? ThemeMode.light : ThemeMode.dark; final storage = FireAtlasStorage(); await storage.setConfig(kThemeMode, newTheme.toString()); return state.copyWith(currentTheme: newTheme); } }
fire-atlas/fire_atlas_editor/lib/store/actions/editor_actions.dart/0
{'file_path': 'fire-atlas/fire_atlas_editor/lib/store/actions/editor_actions.dart', 'repo_id': 'fire-atlas', 'token_count': 904}
class FirestoreService {}
firebase-crud/lib/services/firestore.dart/0
{'file_path': 'firebase-crud/lib/services/firestore.dart', 'repo_id': 'firebase-crud', 'token_count': 6}
import 'dart:math'; import 'dart:ui'; import 'package:flame/components/mixins/has_game_ref.dart'; import 'package:flame/components/mixins/resizable.dart'; import 'package:flame/components/sprite_component.dart'; import 'package:flame/components/sprite_animation_component.dart'; import 'package:flame/extensions/vector2.dart'; import 'package:flame/flame.dart'; import 'package:flame/game.dart'; import 'package:flame/gestures.dart'; import 'package:flame/palette.dart'; import 'package:flame/text_config.dart'; import 'package:flame_audio/flame_audio.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart' show runApp; const SPEED = 250.0; const CRATE_SIZE = 64.0; final rnd = Random(); final textConfig = TextConfig( color: BasicPalette.white.color, fontSize: 48.0, fontFamily: 'Halo', ); void main() async { await Flame.init(); await Flame.images.loadAll(['explosion.png', 'crate.png']); final game = MyGame(); FlameAudio.loop('music.ogg'); runApp(game.widget); } class Crate extends SpriteComponent with HasGameRef<MyGame>, Resizable { bool explode = false; Crate(Vector2 gameSize) : super.fromImage( Vector2.all(CRATE_SIZE), Flame.images.fromCache('crate.png'), ) { x = rnd.nextDouble() * (gameSize.x - CRATE_SIZE); y = 0.0; } @override void update(double dt) { super.update(dt); y += dt * SPEED; } @override bool destroy() { if (explode) { return true; } if (y == null || gameSize == null) { return false; } final destroy = y >= gameSize.y + CRATE_SIZE / 2; if (destroy) { gameRef.points -= 20; FlameAudio.play('miss.mp3'); } return destroy; } } class Explosion extends SpriteAnimationComponent { static const TIME = 0.75; Explosion(Crate crate) : super.sequenced( Vector2.all(CRATE_SIZE), Flame.images.fromCache('explosion.png'), 7, textureSize: Vector2.all(31), destroyOnFinish: true, ) { position = crate.position.clone(); animation.stepTime = TIME / 7; } } class MyGame extends BaseGame with TapDetector { double creationTimer = 0.0; int points = 0; @override void render(Canvas canvas) { super.render(canvas); final text = points.toString(); textConfig.render(canvas, text, Vector2.all(15)); } @override void update(double dt) { creationTimer += dt; if (creationTimer >= 1) { creationTimer = 0; add(Crate(size)); } super.update(dt); } @override void onTapDown(TapDownDetails details) { final position = details.globalPosition; components.whereType<Crate>().forEach((crate) { final remove = crate.toRect().contains(position); if (remove) { crate.explode = true; add(Explosion(crate)); FlameAudio.play('explosion.mp3'); points += 10; } }); } }
flame-crates-example/lib/main.dart/0
{'file_path': 'flame-crates-example/lib/main.dart', 'repo_id': 'flame-crates-example', 'token_count': 1175}
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flame/game.dart'; import 'package:flame/flame.dart'; import 'package:flame/components/component.dart'; void main() async { await Flame.util.setOrientation(DeviceOrientation.landscapeLeft); runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { final game = MyGame(); return MaterialApp( home: Scaffold( body: Container( color: const Color(0xFF000000), child: Stack(children: [ game.widget, Positioned( left: 10, bottom: 10, child: GameButton( onTapUp: (_) { game.stopMoving(); }, onTapDown: (_) { game.movingLeft(); }, label: 'left')), Positioned( right: 10, bottom: 10, child: GameButton( onTapUp: (_) { game.stopMoving(); }, onTapDown: (_) { game.movingRight(); }, label: 'right')) ])))); } } class GameButton extends StatelessWidget { final String label; final void Function(TapUpDetails) onTapUp; final void Function(TapDownDetails) onTapDown; GameButton({this.label, this.onTapDown, this.onTapUp}); @override Widget build(BuildContext context) { return GestureDetector( onTapUp: onTapUp, onTapDown: onTapDown, child: SizedBox( width: 100, height: 100, child: Container( color: const Color(0xFFe5e5e5), child: Center(child: Text(label))))); } } class Player extends PositionComponent { double direction = 0.0; static final _white = Paint()..color = const Color(0xFFFFFFFF); Player() { width = height = 100; y = 50.0; } @override void update(double dt) { x += 200 * dt * direction; } @override void render(Canvas canvas) { canvas.drawRect(toRect(), _white); } } class MyGame extends BaseGame { Player _player; void stopMoving() { _player.direction = 0; } void movingRight() { _player.direction = 1; } void movingLeft() { _player.direction = -1; } MyGame() { _player = Player(); add(_player); } }
flame-examples/stack_controls/lib/main.dart/0
{'file_path': 'flame-examples/stack_controls/lib/main.dart', 'repo_id': 'flame-examples', 'token_count': 1394}
import 'package:flame/game.dart'; import 'package:flutter/widgets.dart'; import 'package:klondike/step2/klondike_game.dart'; void main() { final game = KlondikeGame(); runApp(GameWidget(game: game)); }
flame/doc/tutorials/klondike/app/lib/step2/main.dart/0
{'file_path': 'flame/doc/tutorials/klondike/app/lib/step2/main.dart', 'repo_id': 'flame', 'token_count': 78}
import 'dart:math'; import 'dart:ui'; import 'package:flame/extensions.dart'; import 'package:flame/palette.dart'; import 'package:flame_forge2d/flame_forge2d.dart' hide Particle, World; import 'package:padracing/padracing_game.dart'; List<Wall> createWalls(Vector2 size) { final topCenter = Vector2(size.x / 2, 0); final bottomCenter = Vector2(size.x / 2, size.y); final leftCenter = Vector2(0, size.y / 2); final rightCenter = Vector2(size.x, size.y / 2); final filledSize = size.clone() + Vector2.all(5); return [ Wall(topCenter, Vector2(filledSize.x, 5)), Wall(leftCenter, Vector2(5, filledSize.y)), Wall(Vector2(52.5, 240), Vector2(5, 380)), Wall(Vector2(200, 50), Vector2(300, 5)), Wall(Vector2(72.5, 300), Vector2(5, 400)), Wall(Vector2(180, 100), Vector2(220, 5)), Wall(Vector2(350, 105), Vector2(5, 115)), Wall(Vector2(310, 160), Vector2(240, 5)), Wall(Vector2(211.5, 400), Vector2(283, 5)), Wall(Vector2(351, 312.5), Vector2(5, 180)), Wall(Vector2(430, 302.5), Vector2(5, 290)), Wall(Vector2(292.5, 450), Vector2(280, 5)), Wall(bottomCenter, Vector2(filledSize.y, 5)), Wall(rightCenter, Vector2(5, filledSize.y)), ]; } class Wall extends BodyComponent<PadRacingGame> { Wall(this.position, this.size) : super(priority: 3); final Vector2 position; final Vector2 size; final Random rng = Random(); late final Image _image; final scale = 10.0; late final _renderPosition = -size.toOffset() / 2; late final _scaledRect = (size * scale).toRect(); late final _renderRect = _renderPosition & size.toSize(); @override Future<void> onLoad() async { await super.onLoad(); paint.color = ColorExtension.fromRGBHexString('#14F596'); final recorder = PictureRecorder(); final canvas = Canvas(recorder, _scaledRect); final drawSize = _scaledRect.size.toVector2(); final center = (drawSize / 2).toOffset(); const step = 1.0; canvas.drawRect( Rect.fromCenter(center: center, width: drawSize.x, height: drawSize.y), BasicPalette.black.paint(), ); paint.style = PaintingStyle.stroke; paint.strokeWidth = step; for (var x = 0; x < 30; x++) { canvas.drawRect( Rect.fromCenter(center: center, width: drawSize.x, height: drawSize.y), paint, ); paint.color = paint.color.darken(0.07); drawSize.x -= step; drawSize.y -= step; } final picture = recorder.endRecording(); _image = await picture.toImage( _scaledRect.width.toInt(), _scaledRect.height.toInt(), ); } @override void render(Canvas canvas) { canvas.drawImageRect( _image, _scaledRect, _renderRect, paint, ); } @override Body createBody() { final def = BodyDef() ..type = BodyType.static ..position = position; final body = world.createBody(def) ..userData = this ..angularDamping = 3.0; final shape = PolygonShape()..setAsBoxXY(size.x / 2, size.y / 2); final fixtureDef = FixtureDef(shape)..restitution = 0.5; return body..createFixture(fixtureDef); } late Rect asRect = Rect.fromCenter( center: position.toOffset(), width: size.x, height: size.y, ); }
flame/examples/games/padracing/lib/wall.dart/0
{'file_path': 'flame/examples/games/padracing/lib/wall.dart', 'repo_id': 'flame', 'token_count': 1289}
import 'package:flame/collisions.dart'; import 'package:flame/components.dart'; import 'package:trex_game/trex_game.dart'; enum PlayerState { crashed, jumping, running, waiting } class Player extends SpriteAnimationGroupComponent<PlayerState> with HasGameRef<TRexGame>, CollisionCallbacks { Player() : super(size: Vector2(90, 88)); final double gravity = 1; final double initialJumpVelocity = -15.0; final double introDuration = 1500.0; final double startXPosition = 50; double _jumpVelocity = 0.0; double get groundYPos { return (gameRef.size.y / 2) - height / 2; } @override Future<void> onLoad() async { // Body hitbox add( RectangleHitbox.relative( Vector2(0.7, 0.6), position: Vector2(0, height / 3), parentSize: size, ), ); // Head hitbox add( RectangleHitbox.relative( Vector2(0.45, 0.35), position: Vector2(width / 2, 0), parentSize: size, ), ); animations = { PlayerState.running: _getAnimation( size: Vector2(88.0, 90.0), frames: [Vector2(1514.0, 4.0), Vector2(1602.0, 4.0)], stepTime: 0.2, ), PlayerState.waiting: _getAnimation( size: Vector2(88.0, 90.0), frames: [Vector2(76.0, 6.0)], ), PlayerState.jumping: _getAnimation( size: Vector2(88.0, 90.0), frames: [Vector2(1339.0, 6.0)], ), PlayerState.crashed: _getAnimation( size: Vector2(88.0, 90.0), frames: [Vector2(1782.0, 6.0)], ), }; current = PlayerState.waiting; } void jump(double speed) { if (current == PlayerState.jumping) { return; } current = PlayerState.jumping; _jumpVelocity = initialJumpVelocity - (speed / 500); } void reset() { y = groundYPos; _jumpVelocity = 0.0; current = PlayerState.running; } @override void update(double dt) { super.update(dt); if (current == PlayerState.jumping) { y += _jumpVelocity; _jumpVelocity += gravity; if (y > groundYPos) { reset(); } } else { y = groundYPos; } if (gameRef.isIntro && x < startXPosition) { x += (startXPosition / introDuration) * dt * 5000; } } @override void onGameResize(Vector2 size) { super.onGameResize(size); y = groundYPos; } @override void onCollisionStart( Set<Vector2> intersectionPoints, PositionComponent other, ) { super.onCollisionStart(intersectionPoints, other); gameRef.gameOver(); } SpriteAnimation _getAnimation({ required Vector2 size, required List<Vector2> frames, double stepTime = double.infinity, }) { return SpriteAnimation.spriteList( frames .map( (vector) => Sprite( gameRef.spriteImage, srcSize: size, srcPosition: vector, ), ) .toList(), stepTime: stepTime, ); } }
flame/examples/games/trex/lib/player.dart/0
{'file_path': 'flame/examples/games/trex/lib/player.dart', 'repo_id': 'flame', 'token_count': 1323}
import 'package:examples/stories/bridge_libraries/forge2d/domino_example.dart'; import 'package:examples/stories/bridge_libraries/forge2d/sprite_body_example.dart'; import 'package:flame/input.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; class CameraExample extends DominoExample { static const String description = ''' This example showcases the possibility to follow BodyComponents with the camera. When the screen is tapped a pizza is added, which the camera will follow. Other than that it is the same as the domino example. '''; @override void onTapDown(TapDownInfo details) { final position = details.eventPosition.game; final pizza = Pizza(position); add(pizza); pizza.mounted.whenComplete(() => camera.followBodyComponent(pizza)); } }
flame/examples/lib/stories/bridge_libraries/forge2d/camera_example.dart/0
{'file_path': 'flame/examples/lib/stories/bridge_libraries/forge2d/camera_example.dart', 'repo_id': 'flame', 'token_count': 245}
import 'package:dashbook/dashbook.dart'; import 'package:examples/commons/commons.dart'; import 'package:examples/stories/camera_and_viewport/camera_component_example.dart'; import 'package:examples/stories/camera_and_viewport/camera_component_properties_example.dart'; import 'package:examples/stories/camera_and_viewport/coordinate_systems_example.dart'; import 'package:examples/stories/camera_and_viewport/fixed_resolution_example.dart'; import 'package:examples/stories/camera_and_viewport/follow_component_example.dart'; import 'package:examples/stories/camera_and_viewport/zoom_example.dart'; import 'package:flame/game.dart'; void addCameraAndViewportStories(Dashbook dashbook) { dashbook.storiesOf('Camera & Viewport') ..add( 'Follow Component', (context) { return GameWidget( game: FollowComponentExample( viewportResolution: Vector2( context.numberProperty('viewport width', 500), context.numberProperty('viewport height', 500), ), ), ); }, codeLink: baseLink('camera_and_viewport/follow_component_example.dart'), info: FollowComponentExample.description, ) ..add( 'Zoom', (context) { return GameWidget( game: ZoomExample( viewportResolution: Vector2( context.numberProperty('viewport width', 500), context.numberProperty('viewport height', 500), ), ), ); }, codeLink: baseLink('camera_and_viewport/zoom_example.dart'), info: ZoomExample.description, ) ..add( 'Fixed Resolution viewport', (context) { return GameWidget( game: FixedResolutionExample( viewportResolution: Vector2( context.numberProperty('viewport width', 600), context.numberProperty('viewport height', 1024), ), ), ); }, codeLink: baseLink('camera_and_viewport/fixed_resolution_example.dart'), info: FixedResolutionExample.description, ) ..add( 'Coordinate Systems', (context) => const CoordinateSystemsWidget(), codeLink: baseLink('camera_and_viewport/coordinate_systems_example.dart'), info: CoordinateSystemsExample.description, ) ..add( 'CameraComponent', (context) => GameWidget(game: CameraComponentExample()), codeLink: baseLink('camera_and_viewport/camera_component_example.dart'), info: CameraComponentExample.description, ) ..add( 'CameraComponent properties', (context) => GameWidget(game: CameraComponentPropertiesExample()), codeLink: baseLink( 'camera_and_viewport/camera_component_properties_example.dart', ), info: CameraComponentPropertiesExample.description, ); }
flame/examples/lib/stories/camera_and_viewport/camera_and_viewport.dart/0
{'file_path': 'flame/examples/lib/stories/camera_and_viewport/camera_and_viewport.dart', 'repo_id': 'flame', 'token_count': 1148}
import 'package:examples/commons/ember.dart'; import 'package:flame/components.dart'; import 'package:flame/effects.dart'; import 'package:flame/game.dart'; import 'package:flame/input.dart'; import 'package:flutter/material.dart'; class ColorEffectExample extends FlameGame with TapDetector { static const String description = ''' In this example we show how the `ColorEffect` can be used. Ember will constantly pulse in and out of a blue color. '''; late final SpriteComponent sprite; @override Future<void> onLoad() async { add( Ember( position: Vector2(180, 230), size: Vector2.all(100), )..add( ColorEffect( Colors.blue, const Offset( 0.0, 0.8, ), // Means, applies from 0% to 80% of the color EffectController( duration: 1.5, reverseDuration: 1.5, infinite: true, ), ), ), ); } }
flame/examples/lib/stories/effects/color_effect_example.dart/0
{'file_path': 'flame/examples/lib/stories/effects/color_effect_example.dart', 'repo_id': 'flame', 'token_count': 446}