code
stringlengths
8
3.25M
repository
stringlengths
15
175
metadata
stringlengths
66
249
name: todos_data_source description: A generic interface for managing todos. version: 0.1.0+1 publish_to: none environment: sdk: ">=2.17.0 <3.0.0" dependencies: equatable: ^2.0.3 json_annotation: ^4.6.0 meta: ^1.7.0 dev_dependencies: build_runner: ^2.2.0 json_serializable: ^6.3.1 mocktail: ^0.3.0 test: ^1.19.2 very_good_analysis: ^3.0.1
dart-todos-backend/packages/todos_data_source/pubspec.yaml/0
{'file_path': 'dart-todos-backend/packages/todos_data_source/pubspec.yaml', 'repo_id': 'dart-todos-backend', 'token_count': 167}
// import 'dart:js_util'; // import 'package:shelf_router/shelf_router.dart' show Router; // import 'package:shelf/src/request.dart' show Request; // import 'package:shelf/src/response.dart' show Response; // import 'package:js/js.dart' as js; // import 'cloudflare_workers_shelf.dart'; // import 'fetch_interop.dart' as interop; // export 'cloudflare_interop.dart' // show // IncomingRequestCfProperties, // IncomingRequestCfPropertiesBotManagement, // IncomingRequestCfPropertiesTLSClientAuth; // export 'package:shelf/src/request.dart' show Request; // export 'package:shelf/src/response.dart' show Response; // export 'package:shelf_router/shelf_router.dart' show Router; // void serve(Router router) { // interop.addEventListener('fetch', // js.allowInterop((interop.FetchEvent event) async { // event.respondWith(interop.futureToPromise(Future(() async { // // final context = { // // // if (event.request.cf != null) 'cf': event.request.cf!, // // }; // final shelfRequest = Request( // event.request.method, Uri.parse(event.request.url), // // context: context, // // TODO other properties // ); // final shelfResponse = await router.call(shelfRequest); // // response.headersAll.forEach((key, values) { // // values.forEach((value) { // // event.respondWith.headers.append(key, value); // // }); // // }); // return interop.Response(await shelfResponse.readAsString()); // }))); // })); // } // extension CloudflareRequest on Request { // IncomingRequestCfProperties? get cf => context['cf'] as IncomingRequestCfProperties?; // }
dart_edge/packages/cloudflare_workers/lib/cloudflare_workers_shelf.dart/0
{'file_path': 'dart_edge/packages/cloudflare_workers/lib/cloudflare_workers_shelf.dart', 'repo_id': 'dart_edge', 'token_count': 668}
import 'dart:async'; import 'dart:js'; import '../../interop/durable_object_interop.dart' as interop; import 'durable_object_id.dart'; import 'durable_object_storage.dart'; class DurableObjectState { final interop.DurableObjectState _delegate; DurableObjectState._(this._delegate); DurableObjectId get id => durableObjectIdFromJsObject(_delegate.id); DurableObjectStorage get storage => durableObjectStorageFromJsObject(_delegate.storage); void waitUntil(Future<void> future) => _delegate.waitUntil(future); Future<T> blockConcurrencyWhile<T>(Future<T> Function() callback) => _delegate.blockConcurrencyWhile(allowInterop(callback)); } DurableObjectState durableObjectStateFromJsObject( interop.DurableObjectState obj) => DurableObjectState._(obj);
dart_edge/packages/cloudflare_workers/lib/public/do/durable_object_state.dart/0
{'file_path': 'dart_edge/packages/cloudflare_workers/lib/public/do/durable_object_state.dart', 'repo_id': 'dart_edge', 'token_count': 261}
name: cloudflare_workers description: Write and deploy Dart functions to Cloudflare Workers. homepage: https://dartedge.dev repository: https://github.com/invertase/dart_edge/tree/main/packages/cloudflare_workers version: 0.0.2 environment: sdk: ">=2.18.5 <3.0.0" dependencies: edge: ^0.0.2 js_bindings: ^0.1.0 js: ^0.6.5 dev_dependencies: lints: ^2.0.0 test: ^1.16.0
dart_edge/packages/cloudflare_workers/pubspec.yaml/0
{'file_path': 'dart_edge/packages/cloudflare_workers/pubspec.yaml', 'repo_id': 'dart_edge', 'token_count': 162}
import 'dart:convert'; import 'dart:io'; import 'package:path/path.dart' as p; import '../compiler.dart'; import '../dev_server.dart'; import 'base_command.dart'; class VercelBuildCommand extends BaseCommand { @override final name = "vercel_edge"; @override final description = "Builds the project."; VercelBuildCommand() { argParser.addFlag( 'dev', help: 'Runs Dart Edge in a local development environment with hot reload via Vercel CLI.', ); } Future<String> _compile( String outputDirectory, { required CompilerLevel level, }) async { final outFileName = 'main.dart.js'; final compiler = Compiler( entryPoint: p.join(Directory.current.path, 'lib', 'main.dart'), outputDirectory: outputDirectory, outputFileName: outFileName, level: level, ); await compiler.compile(); return p.join(outputDirectory, outFileName); } Future<void> runDev() async { final edgeTool = Directory( p.join(Directory.current.path, '.dart_tool', 'edge'), ); final devServer = DevServer( startScript: devAddEventListener, compiler: Compiler( entryPoint: p.join(Directory.current.path, 'lib', 'main.dart'), outputDirectory: edgeTool.path, outputFileName: 'main.dart.js', level: CompilerLevel.O1, ), ); devServer.start(); } Future<void> runBuild() async { final vercelDirectory = Directory( p.join(Directory.current.path, '.vercel'), ); final edgeFunction = Directory( p.join(vercelDirectory.path, 'output', 'functions', 'dart.func'), ); await _compile( edgeFunction.path, level: CompilerLevel.O4, ); final configFile = File(p.join(vercelDirectory.path, 'output', 'config.json')); String configFileValue; if (await configFile.exists()) { // If a config file already exists, merge in the new route. final json = jsonDecode(await configFile.readAsString()); // If there is no routes key, or it is not an iterable, create a new one. if (json['routes'] == null || json['routes'] is! Iterable) { json['routes'] = [ {'src': '/*', 'dest': 'dart'} ]; } else { // Otherwise, check if the route already exists. final route = (json['routes'] as Iterable).firstWhere( (route) => route['dest'] == 'dart', orElse: () => null, ); // If the route does not exist, add it. if (route == null) { json['routes'] = [ ...json['routes'], {'src': '/*', 'dest': 'dart'}, ]; } } configFileValue = jsonEncode(json); } else { // Otherwise create a new config file. configFileValue = configFileDefaultValue; } // Write the config file. await configFile.writeAsString(configFileValue); // Create a File instance of the Edge Function config file. final edgeFunctionConfig = File( p.join(edgeFunction.path, '.vc-config.json'), ); // Write the Edge Function config file. await edgeFunctionConfig.writeAsString(edgeFunctionConfigFileDefaultValue); // Write the Edge Function config file. await File(p.join(edgeFunction.path, 'entry.js')).writeAsString( edgeFunctionEntryFileDefaultValue('main.dart.js'), ); } @override void run() async { final isDev = argResults!['dev'] as bool; if (isDev) { await runDev(); } else { await runBuild(); } } } const configFileDefaultValue = '''{ "version": 3, "routes": [{ "src": "/.*", "dest": "dart" }] } '''; const edgeFunctionConfigFileDefaultValue = '''{ "runtime": "edge", "entrypoint": "entry.js" } '''; const devAddEventListener = '''addEventListener("fetch", async (event) => { if (self.__dartVercelFetchHandler !== undefined) { event.respondWith(self.__dartVercelFetchHandler(event.request)); } }); '''; final edgeFunctionEntryFileDefaultValue = (String fileName) => '''import './${fileName}'; export default (request) => { if (self.__dartVercelFetchHandler !== undefined) { return self.__dartVercelFetchHandler(request); } }; ''';
dart_edge/packages/edge/lib/cli/commands/build_vercel.dart/0
{'file_path': 'dart_edge/packages/edge/lib/cli/commands/build_vercel.dart', 'repo_id': 'dart_edge', 'token_count': 1655}
import 'dart:typed_data'; import 'package:js_bindings/js_bindings.dart' as interop; import 'blob.dart'; import 'readable_stream.dart'; class File implements Blob { final interop.File _delegate; File._(this._delegate); String get name => _delegate.name; int get lastModified => _delegate.lastModified; String? get webkitRelativePath { try { return _delegate.webkitRelativePath; } catch (e) { // Throws a JS error if the `webkitdirectory` attribute was not set on // the input element, but this is accessed. // See: https://developer.mozilla.org/en-US/docs/Web/API/File/webkitRelativePath return null; } } @override Future<ByteBuffer> arrayBuffer() => _delegate.arrayBuffer(); @override int get size => _delegate.size; @override Blob slice([int? start, int? end, String? contentType]) { return blobFromJsObject(_delegate.slice(start, end, contentType)); } @override ReadableStream stream() { return readableStreamFromJsObject(_delegate.stream()); } @override Future<String> text() => _delegate.text(); @override String get type => _delegate.type; } extension FileExtension on File { interop.File get delegate => _delegate; } File fileFromJsObject(interop.File delegate) { return File._(delegate); }
dart_edge/packages/edge/lib/runtime/file.dart/0
{'file_path': 'dart_edge/packages/edge/lib/runtime/file.dart', 'repo_id': 'dart_edge', 'token_count': 457}
import 'dart:js' as js; import 'dart:js_util'; import 'package:js_bindings/js_bindings.dart' as interop; import 'abort.dart'; import 'headers.dart'; import 'interop/scope_interop.dart' as interop; import 'interop/utils_interop.dart' as interop; import 'fetch_event.dart'; import 'resource.dart'; import 'response.dart'; void addFetchEventListener(Null Function(FetchEvent event) listener) { interop.addEventListener( 'fetch', js.allowInterop((interop.ExtendableEvent delegate) { // This needs casting, because the type of the event is not known at compile time. listener(fetchEventFromJsObject(delegate as interop.FetchEvent)); }), ); } Future<Response> fetch( Resource resource, { String? method, Headers? headers, Object? body, String? referrer, interop.ReferrerPolicy? referrerPolicy, interop.RequestMode? mode, interop.RequestCredentials? credentials, interop.RequestCache? cache, interop.RequestRedirect? redirect, String? integrity, bool? keepalive, AbortSignal? signal, interop.RequestDuplex? duplex, }) async { return responseFromJsObject( await promiseToFuture( interop.fetch( interop.requestFromResource(resource), interop.RequestInit( method: method, headers: headers?.delegate, body: body, referrer: referrer, referrerPolicy: referrerPolicy, mode: mode, credentials: credentials, cache: cache, redirect: redirect, integrity: integrity, keepalive: keepalive, signal: signal?.delegate, duplex: duplex, ), ), ), ); } String atob(String encodedData) => interop.atob(encodedData); String btoa(String stringToEncode) => interop.btoa(stringToEncode); int setInterval(void Function() callback, Duration duration) => interop.setInterval(js.allowInterop(callback), duration.inMilliseconds); void clearInterval(int handle) => interop.clearInterval(handle); int setTimeout(void Function() callback, Duration duration) => interop.setTimeout(js.allowInterop(callback), duration.inMilliseconds); void clearTimeout(int handle) => interop.clearTimeout(handle);
dart_edge/packages/edge/lib/runtime/top.dart/0
{'file_path': 'dart_edge/packages/edge/lib/runtime/top.dart', 'repo_id': 'dart_edge', 'token_count': 833}
// import 'package:vercel_edge/vercel_edge.dart'; import 'package:shelf_router/shelf_router.dart'; import 'package:shelf/shelf.dart'; import 'package:vercel_edge/vercel_edge_shelf.dart'; void main() { // VercelEdge(fetch: (request) { // return Response("Hello..."); // }); VercelEdgeShelf(fetch: (request) { final app = Router(); app.get('/hello', (request) { return Response.ok("Hello..."); }); app.all('/<ignored|.*>', (request) { return Response.notFound('Not found'); }); return app(request); }); }
dart_edge/packages/vercel_edge/example/lib/main.dart/0
{'file_path': 'dart_edge/packages/vercel_edge/example/lib/main.dart', 'repo_id': 'dart_edge', 'token_count': 221}
name: dart_frog_prod_server on: pull_request: paths: - ".github/workflows/dart_frog_prod_server.yaml" - "bricks/dart_frog_prod_server/hooks/**" push: branches: - main paths: - ".github/workflows/dart_frog_prod_server.yaml" - "bricks/dart_frog_prod_server/hooks/**" jobs: build: uses: VeryGoodOpenSource/very_good_workflows/.github/workflows/dart_package.yml@v1 with: working_directory: bricks/dart_frog_prod_server/hooks analyze_directories: . report_on: "pre_gen.dart,post_gen.dart"
dart_frog/.github/workflows/dart_frog_prod_server.yaml/0
{'file_path': 'dart_frog/.github/workflows/dart_frog_prod_server.yaml', 'repo_id': 'dart_frog', 'token_count': 261}
const fooPath = ''' # Generated by pub # See https://dart.dev/tools/pub/glossary#lockfile packages: _fe_analyzer_shared: dependency: transitive description: name: _fe_analyzer_shared sha256: "58826e40314219b223f4723dd4205845040161cdc2df3e6a1cdceed5d8165084" url: "https://pub.dev" source: hosted version: "63.0.0" analyzer: dependency: transitive description: name: analyzer sha256: f85566ec7b3d25cbea60f7dd4f157c5025f2f19233ca4feeed33b616c78a26a3 url: "https://pub.dev" source: hosted version: "6.1.0" archive: dependency: transitive description: name: archive sha256: "0c8368c9b3f0abbc193b9d6133649a614204b528982bebc7026372d61677ce3a" url: "https://pub.dev" source: hosted version: "3.3.7" args: dependency: transitive description: name: args sha256: eef6c46b622e0494a36c5a12d10d77fb4e855501a91c1b9ef9339326e58f0596 url: "https://pub.dev" source: hosted version: "2.4.2" async: dependency: transitive description: name: async sha256: "947bfcf187f74dbc5e146c9eb9c0f10c9f8b30743e341481c1e2ed3ecc18c20c" url: "https://pub.dev" source: hosted version: "2.11.0" boolean_selector: dependency: transitive description: name: boolean_selector sha256: "6cfb5af12253eaf2b368f07bacc5a80d1301a071c73360d746b7f2e32d762c66" url: "https://pub.dev" source: hosted version: "2.1.1" checked_yaml: dependency: transitive description: name: checked_yaml sha256: feb6bed21949061731a7a75fc5d2aa727cf160b91af9a3e464c5e3a32e28b5ff url: "https://pub.dev" source: hosted version: "2.0.3" collection: dependency: transitive description: name: collection sha256: ee67cb0715911d28db6bf4af1026078bd6f0128b07a5f66fb2ed94ec6783c09a url: "https://pub.dev" source: hosted version: "1.18.0" convert: dependency: transitive description: name: convert sha256: "0f08b14755d163f6e2134cb58222dd25ea2a2ee8a195e53983d57c075324d592" url: "https://pub.dev" source: hosted version: "3.1.1" coverage: dependency: transitive description: name: coverage sha256: "2fb815080e44a09b85e0f2ca8a820b15053982b2e714b59267719e8a9ff17097" url: "https://pub.dev" source: hosted version: "1.6.3" crypto: dependency: transitive description: name: crypto sha256: ff625774173754681d66daaf4a448684fb04b78f902da9cb3d308c19cc5e8bab url: "https://pub.dev" source: hosted version: "3.0.3" file: dependency: transitive description: name: file sha256: "5fc22d7c25582e38ad9a8515372cd9a93834027aacf1801cf01164dac0ffa08c" url: "https://pub.dev" source: hosted version: "7.0.0" foo: dependency: "direct main" description: path: "../../foo" relative: true source: path version: "0.0.0" frontend_server_client: dependency: transitive description: name: frontend_server_client sha256: "408e3ca148b31c20282ad6f37ebfa6f4bdc8fede5b74bc2f08d9d92b55db3612" url: "https://pub.dev" source: hosted version: "3.2.0" glob: dependency: transitive description: name: glob sha256: "0e7014b3b7d4dac1ca4d6114f82bf1782ee86745b9b42a92c9289c23d8a0ab63" url: "https://pub.dev" source: hosted version: "2.1.2" http: dependency: transitive description: name: http sha256: "759d1a329847dd0f39226c688d3e06a6b8679668e350e2891a6474f8b4bb8525" url: "https://pub.dev" source: hosted version: "1.1.0" http_multi_server: dependency: transitive description: name: http_multi_server sha256: "97486f20f9c2f7be8f514851703d0119c3596d14ea63227af6f7a481ef2b2f8b" url: "https://pub.dev" source: hosted version: "3.2.1" http_parser: dependency: transitive description: name: http_parser sha256: "2aa08ce0341cc9b354a498388e30986515406668dbcc4f7c950c3e715496693b" url: "https://pub.dev" source: hosted version: "4.0.2" io: dependency: transitive description: name: io sha256: "2ec25704aba361659e10e3e5f5d672068d332fc8ac516421d483a11e5cbd061e" url: "https://pub.dev" source: hosted version: "1.0.4" js: dependency: transitive description: name: js sha256: f2c445dce49627136094980615a031419f7f3eb393237e4ecd97ac15dea343f3 url: "https://pub.dev" source: hosted version: "0.6.7" json_annotation: dependency: transitive description: name: json_annotation sha256: b10a7b2ff83d83c777edba3c6a0f97045ddadd56c944e1a23a3fdf43a1bf4467 url: "https://pub.dev" source: hosted version: "4.8.1" logging: dependency: transitive description: name: logging sha256: "623a88c9594aa774443aa3eb2d41807a48486b5613e67599fb4c41c0ad47c340" url: "https://pub.dev" source: hosted version: "1.2.0" mason: dependency: "direct main" description: name: mason sha256: fdc9ea905e7c690fe39d2f9946b7aead86fd976f8edf97d2521a65d260bbf509 url: "https://pub.dev" source: hosted version: "0.1.0-dev.50" mason_logger: dependency: transitive description: name: mason_logger sha256: c12860ae81f0bdc5d05d7914fe473bfb294047e9dc64e8995b5753c7207e81b9 url: "https://pub.dev" source: hosted version: "0.2.8" matcher: dependency: transitive description: name: matcher sha256: "1803e76e6653768d64ed8ff2e1e67bea3ad4b923eb5c56a295c3e634bad5960e" url: "https://pub.dev" source: hosted version: "0.12.16" meta: dependency: transitive description: name: meta sha256: "3c74dbf8763d36539f114c799d8a2d87343b5067e9d796ca22b5eb8437090ee3" url: "https://pub.dev" source: hosted version: "1.9.1" mime: dependency: transitive description: name: mime sha256: e4ff8e8564c03f255408decd16e7899da1733852a9110a58fe6d1b817684a63e url: "https://pub.dev" source: hosted version: "1.0.4" mustache_template: dependency: transitive description: name: mustache_template sha256: a46e26f91445bfb0b60519be280555b06792460b27b19e2b19ad5b9740df5d1c url: "https://pub.dev" source: hosted version: "2.0.0" node_preamble: dependency: transitive description: name: node_preamble sha256: "6e7eac89047ab8a8d26cf16127b5ed26de65209847630400f9aefd7cd5c730db" url: "https://pub.dev" source: hosted version: "2.0.2" package_config: dependency: transitive description: name: package_config sha256: "1c5b77ccc91e4823a5af61ee74e6b972db1ef98c2ff5a18d3161c982a55448bd" url: "https://pub.dev" source: hosted version: "2.1.0" path: dependency: transitive description: name: path sha256: "8829d8a55c13fc0e37127c29fedf290c102f4e40ae94ada574091fe0ff96c917" url: "https://pub.dev" source: hosted version: "1.8.3" pointycastle: dependency: transitive description: name: pointycastle sha256: "7c1e5f0d23c9016c5bbd8b1473d0d3fb3fc851b876046039509e18e0c7485f2c" url: "https://pub.dev" source: hosted version: "3.7.3" pool: dependency: transitive description: name: pool sha256: "20fe868b6314b322ea036ba325e6fc0711a22948856475e2c2b6306e8ab39c2a" url: "https://pub.dev" source: hosted version: "1.5.1" pub_semver: dependency: transitive description: name: pub_semver sha256: "40d3ab1bbd474c4c2328c91e3a7df8c6dd629b79ece4c4bd04bee496a224fb0c" url: "https://pub.dev" source: hosted version: "2.1.4" shelf: dependency: transitive description: name: shelf sha256: ad29c505aee705f41a4d8963641f91ac4cee3c8fad5947e033390a7bd8180fa4 url: "https://pub.dev" source: hosted version: "1.4.1" shelf_packages_handler: dependency: transitive description: name: shelf_packages_handler sha256: "89f967eca29607c933ba9571d838be31d67f53f6e4ee15147d5dc2934fee1b1e" url: "https://pub.dev" source: hosted version: "3.0.2" shelf_static: dependency: transitive description: name: shelf_static sha256: a41d3f53c4adf0f57480578c1d61d90342cd617de7fc8077b1304643c2d85c1e url: "https://pub.dev" source: hosted version: "1.1.2" shelf_web_socket: dependency: transitive description: name: shelf_web_socket sha256: "9ca081be41c60190ebcb4766b2486a7d50261db7bd0f5d9615f2d653637a84c1" url: "https://pub.dev" source: hosted version: "1.0.4" source_map_stack_trace: dependency: transitive description: name: source_map_stack_trace sha256: "84cf769ad83aa6bb61e0aa5a18e53aea683395f196a6f39c4c881fb90ed4f7ae" url: "https://pub.dev" source: hosted version: "2.1.1" source_maps: dependency: transitive description: name: source_maps sha256: "708b3f6b97248e5781f493b765c3337db11c5d2c81c3094f10904bfa8004c703" url: "https://pub.dev" source: hosted version: "0.10.12" source_span: dependency: transitive description: name: source_span sha256: "53e943d4206a5e30df338fd4c6e7a077e02254531b138a15aec3bd143c1a8b3c" url: "https://pub.dev" source: hosted version: "1.10.0" stack_trace: dependency: transitive description: name: stack_trace sha256: "73713990125a6d93122541237550ee3352a2d84baad52d375a4cad2eb9b7ce0b" url: "https://pub.dev" source: hosted version: "1.11.1" stream_channel: dependency: transitive description: name: stream_channel sha256: ba2aa5d8cc609d96bbb2899c28934f9e1af5cddbd60a827822ea467161eb54e7 url: "https://pub.dev" source: hosted version: "2.1.2" string_scanner: dependency: transitive description: name: string_scanner sha256: "556692adab6cfa87322a115640c11f13cb77b3f076ddcc5d6ae3c20242bedcde" url: "https://pub.dev" source: hosted version: "1.2.0" term_glyph: dependency: transitive description: name: term_glyph sha256: a29248a84fbb7c79282b40b8c72a1209db169a2e0542bce341da992fe1bc7e84 url: "https://pub.dev" source: hosted version: "1.2.1" test: dependency: "direct dev" description: name: test sha256: "9b0dd8e36af4a5b1569029949d50a52cb2a2a2fdaa20cebb96e6603b9ae241f9" url: "https://pub.dev" source: hosted version: "1.24.6" test_api: dependency: transitive description: name: test_api sha256: "5c2f730018264d276c20e4f1503fd1308dfbbae39ec8ee63c5236311ac06954b" url: "https://pub.dev" source: hosted version: "0.6.1" test_core: dependency: transitive description: name: test_core sha256: "4bef837e56375537055fdbbbf6dd458b1859881f4c7e6da936158f77d61ab265" url: "https://pub.dev" source: hosted version: "0.5.6" typed_data: dependency: transitive description: name: typed_data sha256: facc8d6582f16042dd49f2463ff1bd6e2c9ef9f3d5da3d9b087e244a7b564b3c url: "https://pub.dev" source: hosted version: "1.3.2" vm_service: dependency: transitive description: name: vm_service sha256: "0fae432c85c4ea880b33b497d32824b97795b04cdaa74d270219572a1f50268d" url: "https://pub.dev" source: hosted version: "11.9.0" watcher: dependency: transitive description: name: watcher sha256: "3d2ad6751b3c16cf07c7fca317a1413b3f26530319181b37e3b9039b84fc01d8" url: "https://pub.dev" source: hosted version: "1.1.0" web_socket_channel: dependency: transitive description: name: web_socket_channel sha256: d88238e5eac9a42bb43ca4e721edba3c08c6354d4a53063afaa568516217621b url: "https://pub.dev" source: hosted version: "2.4.0" webkit_inspection_protocol: dependency: transitive description: name: webkit_inspection_protocol sha256: "67d3a8b6c79e1987d19d848b0892e582dbb0c66c57cc1fef58a177dd2aa2823d" url: "https://pub.dev" source: hosted version: "1.2.0" yaml: dependency: transitive description: name: yaml sha256: "75769501ea3489fca56601ff33454fe45507ea3bfb014161abc3b43ae25989d5" url: "https://pub.dev" source: hosted version: "3.1.2" sdks: dart: ">=3.0.0 <4.0.0" '''; const fooPathWithInternalDependency = ''' # Generated by pub # See https://dart.dev/tools/pub/glossary#lockfile packages: _fe_analyzer_shared: dependency: transitive description: name: _fe_analyzer_shared sha256: "58826e40314219b223f4723dd4205845040161cdc2df3e6a1cdceed5d8165084" url: "https://pub.dev" source: hosted version: "63.0.0" analyzer: dependency: transitive description: name: analyzer sha256: f85566ec7b3d25cbea60f7dd4f157c5025f2f19233ca4feeed33b616c78a26a3 url: "https://pub.dev" source: hosted version: "6.1.0" archive: dependency: transitive description: name: archive sha256: "0c8368c9b3f0abbc193b9d6133649a614204b528982bebc7026372d61677ce3a" url: "https://pub.dev" source: hosted version: "3.3.7" args: dependency: transitive description: name: args sha256: eef6c46b622e0494a36c5a12d10d77fb4e855501a91c1b9ef9339326e58f0596 url: "https://pub.dev" source: hosted version: "2.4.2" async: dependency: transitive description: name: async sha256: "947bfcf187f74dbc5e146c9eb9c0f10c9f8b30743e341481c1e2ed3ecc18c20c" url: "https://pub.dev" source: hosted version: "2.11.0" boolean_selector: dependency: transitive description: name: boolean_selector sha256: "6cfb5af12253eaf2b368f07bacc5a80d1301a071c73360d746b7f2e32d762c66" url: "https://pub.dev" source: hosted version: "2.1.1" checked_yaml: dependency: transitive description: name: checked_yaml sha256: feb6bed21949061731a7a75fc5d2aa727cf160b91af9a3e464c5e3a32e28b5ff url: "https://pub.dev" source: hosted version: "2.0.3" collection: dependency: transitive description: name: collection sha256: ee67cb0715911d28db6bf4af1026078bd6f0128b07a5f66fb2ed94ec6783c09a url: "https://pub.dev" source: hosted version: "1.18.0" convert: dependency: transitive description: name: convert sha256: "0f08b14755d163f6e2134cb58222dd25ea2a2ee8a195e53983d57c075324d592" url: "https://pub.dev" source: hosted version: "3.1.1" coverage: dependency: transitive description: name: coverage sha256: "2fb815080e44a09b85e0f2ca8a820b15053982b2e714b59267719e8a9ff17097" url: "https://pub.dev" source: hosted version: "1.6.3" crypto: dependency: transitive description: name: crypto sha256: ff625774173754681d66daaf4a448684fb04b78f902da9cb3d308c19cc5e8bab url: "https://pub.dev" source: hosted version: "3.0.3" file: dependency: transitive description: name: file sha256: "5fc22d7c25582e38ad9a8515372cd9a93834027aacf1801cf01164dac0ffa08c" url: "https://pub.dev" source: hosted version: "7.0.0" foo: dependency: "direct main" description: path: "../../foo" relative: true source: path version: "0.0.0" bar: dependency: "direct main" description: path: "packages/bar" relative: true source: path version: "0.0.0" frontend_server_client: dependency: transitive description: name: frontend_server_client sha256: "408e3ca148b31c20282ad6f37ebfa6f4bdc8fede5b74bc2f08d9d92b55db3612" url: "https://pub.dev" source: hosted version: "3.2.0" glob: dependency: transitive description: name: glob sha256: "0e7014b3b7d4dac1ca4d6114f82bf1782ee86745b9b42a92c9289c23d8a0ab63" url: "https://pub.dev" source: hosted version: "2.1.2" http: dependency: transitive description: name: http sha256: "759d1a329847dd0f39226c688d3e06a6b8679668e350e2891a6474f8b4bb8525" url: "https://pub.dev" source: hosted version: "1.1.0" http_multi_server: dependency: transitive description: name: http_multi_server sha256: "97486f20f9c2f7be8f514851703d0119c3596d14ea63227af6f7a481ef2b2f8b" url: "https://pub.dev" source: hosted version: "3.2.1" http_parser: dependency: transitive description: name: http_parser sha256: "2aa08ce0341cc9b354a498388e30986515406668dbcc4f7c950c3e715496693b" url: "https://pub.dev" source: hosted version: "4.0.2" io: dependency: transitive description: name: io sha256: "2ec25704aba361659e10e3e5f5d672068d332fc8ac516421d483a11e5cbd061e" url: "https://pub.dev" source: hosted version: "1.0.4" js: dependency: transitive description: name: js sha256: f2c445dce49627136094980615a031419f7f3eb393237e4ecd97ac15dea343f3 url: "https://pub.dev" source: hosted version: "0.6.7" json_annotation: dependency: transitive description: name: json_annotation sha256: b10a7b2ff83d83c777edba3c6a0f97045ddadd56c944e1a23a3fdf43a1bf4467 url: "https://pub.dev" source: hosted version: "4.8.1" logging: dependency: transitive description: name: logging sha256: "623a88c9594aa774443aa3eb2d41807a48486b5613e67599fb4c41c0ad47c340" url: "https://pub.dev" source: hosted version: "1.2.0" mason: dependency: "direct main" description: name: mason sha256: fdc9ea905e7c690fe39d2f9946b7aead86fd976f8edf97d2521a65d260bbf509 url: "https://pub.dev" source: hosted version: "0.1.0-dev.50" mason_logger: dependency: transitive description: name: mason_logger sha256: c12860ae81f0bdc5d05d7914fe473bfb294047e9dc64e8995b5753c7207e81b9 url: "https://pub.dev" source: hosted version: "0.2.8" matcher: dependency: transitive description: name: matcher sha256: "1803e76e6653768d64ed8ff2e1e67bea3ad4b923eb5c56a295c3e634bad5960e" url: "https://pub.dev" source: hosted version: "0.12.16" meta: dependency: transitive description: name: meta sha256: "3c74dbf8763d36539f114c799d8a2d87343b5067e9d796ca22b5eb8437090ee3" url: "https://pub.dev" source: hosted version: "1.9.1" mime: dependency: transitive description: name: mime sha256: e4ff8e8564c03f255408decd16e7899da1733852a9110a58fe6d1b817684a63e url: "https://pub.dev" source: hosted version: "1.0.4" mustache_template: dependency: transitive description: name: mustache_template sha256: a46e26f91445bfb0b60519be280555b06792460b27b19e2b19ad5b9740df5d1c url: "https://pub.dev" source: hosted version: "2.0.0" node_preamble: dependency: transitive description: name: node_preamble sha256: "6e7eac89047ab8a8d26cf16127b5ed26de65209847630400f9aefd7cd5c730db" url: "https://pub.dev" source: hosted version: "2.0.2" package_config: dependency: transitive description: name: package_config sha256: "1c5b77ccc91e4823a5af61ee74e6b972db1ef98c2ff5a18d3161c982a55448bd" url: "https://pub.dev" source: hosted version: "2.1.0" path: dependency: transitive description: name: path sha256: "8829d8a55c13fc0e37127c29fedf290c102f4e40ae94ada574091fe0ff96c917" url: "https://pub.dev" source: hosted version: "1.8.3" pointycastle: dependency: transitive description: name: pointycastle sha256: "7c1e5f0d23c9016c5bbd8b1473d0d3fb3fc851b876046039509e18e0c7485f2c" url: "https://pub.dev" source: hosted version: "3.7.3" pool: dependency: transitive description: name: pool sha256: "20fe868b6314b322ea036ba325e6fc0711a22948856475e2c2b6306e8ab39c2a" url: "https://pub.dev" source: hosted version: "1.5.1" pub_semver: dependency: transitive description: name: pub_semver sha256: "40d3ab1bbd474c4c2328c91e3a7df8c6dd629b79ece4c4bd04bee496a224fb0c" url: "https://pub.dev" source: hosted version: "2.1.4" shelf: dependency: transitive description: name: shelf sha256: ad29c505aee705f41a4d8963641f91ac4cee3c8fad5947e033390a7bd8180fa4 url: "https://pub.dev" source: hosted version: "1.4.1" shelf_packages_handler: dependency: transitive description: name: shelf_packages_handler sha256: "89f967eca29607c933ba9571d838be31d67f53f6e4ee15147d5dc2934fee1b1e" url: "https://pub.dev" source: hosted version: "3.0.2" shelf_static: dependency: transitive description: name: shelf_static sha256: a41d3f53c4adf0f57480578c1d61d90342cd617de7fc8077b1304643c2d85c1e url: "https://pub.dev" source: hosted version: "1.1.2" shelf_web_socket: dependency: transitive description: name: shelf_web_socket sha256: "9ca081be41c60190ebcb4766b2486a7d50261db7bd0f5d9615f2d653637a84c1" url: "https://pub.dev" source: hosted version: "1.0.4" source_map_stack_trace: dependency: transitive description: name: source_map_stack_trace sha256: "84cf769ad83aa6bb61e0aa5a18e53aea683395f196a6f39c4c881fb90ed4f7ae" url: "https://pub.dev" source: hosted version: "2.1.1" source_maps: dependency: transitive description: name: source_maps sha256: "708b3f6b97248e5781f493b765c3337db11c5d2c81c3094f10904bfa8004c703" url: "https://pub.dev" source: hosted version: "0.10.12" source_span: dependency: transitive description: name: source_span sha256: "53e943d4206a5e30df338fd4c6e7a077e02254531b138a15aec3bd143c1a8b3c" url: "https://pub.dev" source: hosted version: "1.10.0" stack_trace: dependency: transitive description: name: stack_trace sha256: "73713990125a6d93122541237550ee3352a2d84baad52d375a4cad2eb9b7ce0b" url: "https://pub.dev" source: hosted version: "1.11.1" stream_channel: dependency: transitive description: name: stream_channel sha256: ba2aa5d8cc609d96bbb2899c28934f9e1af5cddbd60a827822ea467161eb54e7 url: "https://pub.dev" source: hosted version: "2.1.2" string_scanner: dependency: transitive description: name: string_scanner sha256: "556692adab6cfa87322a115640c11f13cb77b3f076ddcc5d6ae3c20242bedcde" url: "https://pub.dev" source: hosted version: "1.2.0" term_glyph: dependency: transitive description: name: term_glyph sha256: a29248a84fbb7c79282b40b8c72a1209db169a2e0542bce341da992fe1bc7e84 url: "https://pub.dev" source: hosted version: "1.2.1" test: dependency: "direct dev" description: name: test sha256: "9b0dd8e36af4a5b1569029949d50a52cb2a2a2fdaa20cebb96e6603b9ae241f9" url: "https://pub.dev" source: hosted version: "1.24.6" test_api: dependency: transitive description: name: test_api sha256: "5c2f730018264d276c20e4f1503fd1308dfbbae39ec8ee63c5236311ac06954b" url: "https://pub.dev" source: hosted version: "0.6.1" test_core: dependency: transitive description: name: test_core sha256: "4bef837e56375537055fdbbbf6dd458b1859881f4c7e6da936158f77d61ab265" url: "https://pub.dev" source: hosted version: "0.5.6" typed_data: dependency: transitive description: name: typed_data sha256: facc8d6582f16042dd49f2463ff1bd6e2c9ef9f3d5da3d9b087e244a7b564b3c url: "https://pub.dev" source: hosted version: "1.3.2" vm_service: dependency: transitive description: name: vm_service sha256: "0fae432c85c4ea880b33b497d32824b97795b04cdaa74d270219572a1f50268d" url: "https://pub.dev" source: hosted version: "11.9.0" watcher: dependency: transitive description: name: watcher sha256: "3d2ad6751b3c16cf07c7fca317a1413b3f26530319181b37e3b9039b84fc01d8" url: "https://pub.dev" source: hosted version: "1.1.0" web_socket_channel: dependency: transitive description: name: web_socket_channel sha256: d88238e5eac9a42bb43ca4e721edba3c08c6354d4a53063afaa568516217621b url: "https://pub.dev" source: hosted version: "2.4.0" webkit_inspection_protocol: dependency: transitive description: name: webkit_inspection_protocol sha256: "67d3a8b6c79e1987d19d848b0892e582dbb0c66c57cc1fef58a177dd2aa2823d" url: "https://pub.dev" source: hosted version: "1.2.0" yaml: dependency: transitive description: name: yaml sha256: "75769501ea3489fca56601ff33454fe45507ea3bfb014161abc3b43ae25989d5" url: "https://pub.dev" source: hosted version: "3.1.2" sdks: dart: ">=3.0.0 <4.0.0" '''; const noPathDependencies = ''' # Generated by pub # See https://dart.dev/tools/pub/glossary#lockfile packages: _fe_analyzer_shared: dependency: transitive description: name: _fe_analyzer_shared sha256: "58826e40314219b223f4723dd4205845040161cdc2df3e6a1cdceed5d8165084" url: "https://pub.dev" source: hosted version: "63.0.0" analyzer: dependency: transitive description: name: analyzer sha256: f85566ec7b3d25cbea60f7dd4f157c5025f2f19233ca4feeed33b616c78a26a3 url: "https://pub.dev" source: hosted version: "6.1.0" archive: dependency: transitive description: name: archive sha256: "0c8368c9b3f0abbc193b9d6133649a614204b528982bebc7026372d61677ce3a" url: "https://pub.dev" source: hosted version: "3.3.7" args: dependency: transitive description: name: args sha256: eef6c46b622e0494a36c5a12d10d77fb4e855501a91c1b9ef9339326e58f0596 url: "https://pub.dev" source: hosted version: "2.4.2" async: dependency: transitive description: name: async sha256: "947bfcf187f74dbc5e146c9eb9c0f10c9f8b30743e341481c1e2ed3ecc18c20c" url: "https://pub.dev" source: hosted version: "2.11.0" boolean_selector: dependency: transitive description: name: boolean_selector sha256: "6cfb5af12253eaf2b368f07bacc5a80d1301a071c73360d746b7f2e32d762c66" url: "https://pub.dev" source: hosted version: "2.1.1" checked_yaml: dependency: transitive description: name: checked_yaml sha256: feb6bed21949061731a7a75fc5d2aa727cf160b91af9a3e464c5e3a32e28b5ff url: "https://pub.dev" source: hosted version: "2.0.3" collection: dependency: transitive description: name: collection sha256: ee67cb0715911d28db6bf4af1026078bd6f0128b07a5f66fb2ed94ec6783c09a url: "https://pub.dev" source: hosted version: "1.18.0" convert: dependency: transitive description: name: convert sha256: "0f08b14755d163f6e2134cb58222dd25ea2a2ee8a195e53983d57c075324d592" url: "https://pub.dev" source: hosted version: "3.1.1" coverage: dependency: transitive description: name: coverage sha256: "2fb815080e44a09b85e0f2ca8a820b15053982b2e714b59267719e8a9ff17097" url: "https://pub.dev" source: hosted version: "1.6.3" crypto: dependency: transitive description: name: crypto sha256: ff625774173754681d66daaf4a448684fb04b78f902da9cb3d308c19cc5e8bab url: "https://pub.dev" source: hosted version: "3.0.3" file: dependency: transitive description: name: file sha256: "5fc22d7c25582e38ad9a8515372cd9a93834027aacf1801cf01164dac0ffa08c" url: "https://pub.dev" source: hosted version: "7.0.0" frontend_server_client: dependency: transitive description: name: frontend_server_client sha256: "408e3ca148b31c20282ad6f37ebfa6f4bdc8fede5b74bc2f08d9d92b55db3612" url: "https://pub.dev" source: hosted version: "3.2.0" glob: dependency: transitive description: name: glob sha256: "0e7014b3b7d4dac1ca4d6114f82bf1782ee86745b9b42a92c9289c23d8a0ab63" url: "https://pub.dev" source: hosted version: "2.1.2" http: dependency: transitive description: name: http sha256: "759d1a329847dd0f39226c688d3e06a6b8679668e350e2891a6474f8b4bb8525" url: "https://pub.dev" source: hosted version: "1.1.0" http_multi_server: dependency: transitive description: name: http_multi_server sha256: "97486f20f9c2f7be8f514851703d0119c3596d14ea63227af6f7a481ef2b2f8b" url: "https://pub.dev" source: hosted version: "3.2.1" http_parser: dependency: transitive description: name: http_parser sha256: "2aa08ce0341cc9b354a498388e30986515406668dbcc4f7c950c3e715496693b" url: "https://pub.dev" source: hosted version: "4.0.2" io: dependency: transitive description: name: io sha256: "2ec25704aba361659e10e3e5f5d672068d332fc8ac516421d483a11e5cbd061e" url: "https://pub.dev" source: hosted version: "1.0.4" js: dependency: transitive description: name: js sha256: f2c445dce49627136094980615a031419f7f3eb393237e4ecd97ac15dea343f3 url: "https://pub.dev" source: hosted version: "0.6.7" json_annotation: dependency: transitive description: name: json_annotation sha256: b10a7b2ff83d83c777edba3c6a0f97045ddadd56c944e1a23a3fdf43a1bf4467 url: "https://pub.dev" source: hosted version: "4.8.1" logging: dependency: transitive description: name: logging sha256: "623a88c9594aa774443aa3eb2d41807a48486b5613e67599fb4c41c0ad47c340" url: "https://pub.dev" source: hosted version: "1.2.0" mason: dependency: "direct main" description: name: mason sha256: fdc9ea905e7c690fe39d2f9946b7aead86fd976f8edf97d2521a65d260bbf509 url: "https://pub.dev" source: hosted version: "0.1.0-dev.50" mason_logger: dependency: transitive description: name: mason_logger sha256: c12860ae81f0bdc5d05d7914fe473bfb294047e9dc64e8995b5753c7207e81b9 url: "https://pub.dev" source: hosted version: "0.2.8" matcher: dependency: transitive description: name: matcher sha256: "1803e76e6653768d64ed8ff2e1e67bea3ad4b923eb5c56a295c3e634bad5960e" url: "https://pub.dev" source: hosted version: "0.12.16" meta: dependency: transitive description: name: meta sha256: "3c74dbf8763d36539f114c799d8a2d87343b5067e9d796ca22b5eb8437090ee3" url: "https://pub.dev" source: hosted version: "1.9.1" mime: dependency: transitive description: name: mime sha256: e4ff8e8564c03f255408decd16e7899da1733852a9110a58fe6d1b817684a63e url: "https://pub.dev" source: hosted version: "1.0.4" mustache_template: dependency: transitive description: name: mustache_template sha256: a46e26f91445bfb0b60519be280555b06792460b27b19e2b19ad5b9740df5d1c url: "https://pub.dev" source: hosted version: "2.0.0" node_preamble: dependency: transitive description: name: node_preamble sha256: "6e7eac89047ab8a8d26cf16127b5ed26de65209847630400f9aefd7cd5c730db" url: "https://pub.dev" source: hosted version: "2.0.2" package_config: dependency: transitive description: name: package_config sha256: "1c5b77ccc91e4823a5af61ee74e6b972db1ef98c2ff5a18d3161c982a55448bd" url: "https://pub.dev" source: hosted version: "2.1.0" path: dependency: transitive description: name: path sha256: "8829d8a55c13fc0e37127c29fedf290c102f4e40ae94ada574091fe0ff96c917" url: "https://pub.dev" source: hosted version: "1.8.3" pointycastle: dependency: transitive description: name: pointycastle sha256: "7c1e5f0d23c9016c5bbd8b1473d0d3fb3fc851b876046039509e18e0c7485f2c" url: "https://pub.dev" source: hosted version: "3.7.3" pool: dependency: transitive description: name: pool sha256: "20fe868b6314b322ea036ba325e6fc0711a22948856475e2c2b6306e8ab39c2a" url: "https://pub.dev" source: hosted version: "1.5.1" pub_semver: dependency: transitive description: name: pub_semver sha256: "40d3ab1bbd474c4c2328c91e3a7df8c6dd629b79ece4c4bd04bee496a224fb0c" url: "https://pub.dev" source: hosted version: "2.1.4" shelf: dependency: transitive description: name: shelf sha256: ad29c505aee705f41a4d8963641f91ac4cee3c8fad5947e033390a7bd8180fa4 url: "https://pub.dev" source: hosted version: "1.4.1" shelf_packages_handler: dependency: transitive description: name: shelf_packages_handler sha256: "89f967eca29607c933ba9571d838be31d67f53f6e4ee15147d5dc2934fee1b1e" url: "https://pub.dev" source: hosted version: "3.0.2" shelf_static: dependency: transitive description: name: shelf_static sha256: a41d3f53c4adf0f57480578c1d61d90342cd617de7fc8077b1304643c2d85c1e url: "https://pub.dev" source: hosted version: "1.1.2" shelf_web_socket: dependency: transitive description: name: shelf_web_socket sha256: "9ca081be41c60190ebcb4766b2486a7d50261db7bd0f5d9615f2d653637a84c1" url: "https://pub.dev" source: hosted version: "1.0.4" source_map_stack_trace: dependency: transitive description: name: source_map_stack_trace sha256: "84cf769ad83aa6bb61e0aa5a18e53aea683395f196a6f39c4c881fb90ed4f7ae" url: "https://pub.dev" source: hosted version: "2.1.1" source_maps: dependency: transitive description: name: source_maps sha256: "708b3f6b97248e5781f493b765c3337db11c5d2c81c3094f10904bfa8004c703" url: "https://pub.dev" source: hosted version: "0.10.12" source_span: dependency: transitive description: name: source_span sha256: "53e943d4206a5e30df338fd4c6e7a077e02254531b138a15aec3bd143c1a8b3c" url: "https://pub.dev" source: hosted version: "1.10.0" stack_trace: dependency: transitive description: name: stack_trace sha256: "73713990125a6d93122541237550ee3352a2d84baad52d375a4cad2eb9b7ce0b" url: "https://pub.dev" source: hosted version: "1.11.1" stream_channel: dependency: transitive description: name: stream_channel sha256: ba2aa5d8cc609d96bbb2899c28934f9e1af5cddbd60a827822ea467161eb54e7 url: "https://pub.dev" source: hosted version: "2.1.2" string_scanner: dependency: transitive description: name: string_scanner sha256: "556692adab6cfa87322a115640c11f13cb77b3f076ddcc5d6ae3c20242bedcde" url: "https://pub.dev" source: hosted version: "1.2.0" term_glyph: dependency: transitive description: name: term_glyph sha256: a29248a84fbb7c79282b40b8c72a1209db169a2e0542bce341da992fe1bc7e84 url: "https://pub.dev" source: hosted version: "1.2.1" test: dependency: "direct main" description: name: test sha256: "9b0dd8e36af4a5b1569029949d50a52cb2a2a2fdaa20cebb96e6603b9ae241f9" url: "https://pub.dev" source: hosted version: "1.24.6" test_api: dependency: transitive description: name: test_api sha256: "5c2f730018264d276c20e4f1503fd1308dfbbae39ec8ee63c5236311ac06954b" url: "https://pub.dev" source: hosted version: "0.6.1" test_core: dependency: transitive description: name: test_core sha256: "4bef837e56375537055fdbbbf6dd458b1859881f4c7e6da936158f77d61ab265" url: "https://pub.dev" source: hosted version: "0.5.6" typed_data: dependency: transitive description: name: typed_data sha256: facc8d6582f16042dd49f2463ff1bd6e2c9ef9f3d5da3d9b087e244a7b564b3c url: "https://pub.dev" source: hosted version: "1.3.2" vm_service: dependency: transitive description: name: vm_service sha256: "0fae432c85c4ea880b33b497d32824b97795b04cdaa74d270219572a1f50268d" url: "https://pub.dev" source: hosted version: "11.9.0" watcher: dependency: transitive description: name: watcher sha256: "3d2ad6751b3c16cf07c7fca317a1413b3f26530319181b37e3b9039b84fc01d8" url: "https://pub.dev" source: hosted version: "1.1.0" web_socket_channel: dependency: transitive description: name: web_socket_channel sha256: d88238e5eac9a42bb43ca4e721edba3c08c6354d4a53063afaa568516217621b url: "https://pub.dev" source: hosted version: "2.4.0" webkit_inspection_protocol: dependency: transitive description: name: webkit_inspection_protocol sha256: "67d3a8b6c79e1987d19d848b0892e582dbb0c66c57cc1fef58a177dd2aa2823d" url: "https://pub.dev" source: hosted version: "1.2.0" yaml: dependency: transitive description: name: yaml sha256: "75769501ea3489fca56601ff33454fe45507ea3bfb014161abc3b43ae25989d5" url: "https://pub.dev" source: hosted version: "3.1.2" sdks: dart: ">=3.0.0 <4.0.0" ''';
dart_frog/bricks/dart_frog_prod_server/hooks/test/pubspeck_locks.dart/0
{'file_path': 'dart_frog/bricks/dart_frog_prod_server/hooks/test/pubspeck_locks.dart', 'repo_id': 'dart_frog', 'token_count': 18907}
import 'package:bearer_authentication/hash_extension.dart'; import 'package:equatable/equatable.dart'; import 'package:meta/meta.dart'; /// {@template session} /// /// Represents a user session. /// /// {@endtemplate} class Session extends Equatable { /// {@macro session} const Session({ required this.token, required this.userId, required this.expiryDate, required this.createdAt, }); /// The session token. final String token; /// The user id. final String userId; /// The session expiration date. final DateTime expiryDate; /// The session creation date. final DateTime createdAt; @override List<Object?> get props => [token, userId, expiryDate, createdAt]; } /// In memory database of sessions. @visibleForTesting Map<String, Session> sessionDb = {}; /// {@template session_repository} /// Repository which manages sessions. /// {@endtemplate} class SessionRepository { /// {@macro session_repository} /// /// The [now] function is used to get the current date and time. const SessionRepository({ DateTime Function()? now, }) : _now = now ?? DateTime.now; final DateTime Function() _now; /// Creates a new session for the user with the given [userId]. Future<Session> createSession(String userId) async { final now = _now(); final session = Session( token: '${userId}_${now.toIso8601String()}'.hashValue, userId: userId, expiryDate: now.add(const Duration(days: 1)), createdAt: now, ); sessionDb[session.token] = session; return session; } /// Searches and return a session by its [token]. /// /// If the session is not found or is expired, returns `null`. Future<Session?> sessionFromToken(String token) async { final session = sessionDb[token]; if (session != null && session.expiryDate.isAfter(_now())) { return session; } return null; } }
dart_frog/examples/bearer_authentication/lib/session_repository.dart/0
{'file_path': 'dart_frog/examples/bearer_authentication/lib/session_repository.dart', 'repo_id': 'dart_frog', 'token_count': 628}
import 'dart:io'; import 'package:http/http.dart' as http; import 'package:test/test.dart'; void main() { group('E2E (/pets)', () { const greeting = 'Hello'; test('GET /api/pets responds with unauthorized when header is missing', () async { final response = await http.get( Uri.parse('http://localhost:8080/api/pets'), ); expect(response.statusCode, equals(HttpStatus.unauthorized)); }); test('GET /api/pets responds with "Hello pets"', () async { final response = await http.get( Uri.parse('http://localhost:8080/api/pets'), headers: {HttpHeaders.authorizationHeader: 'token'}, ); expect(response.statusCode, equals(HttpStatus.ok)); expect(response.body, equals('$greeting pets')); }); test('GET /api/pets/<name> responds with "Hello <name>"', () async { const name = 'Frog'; final response = await http.get( Uri.parse('http://localhost:8080/api/pets/$name'), headers: {HttpHeaders.authorizationHeader: 'token'}, ); expect(response.statusCode, equals(HttpStatus.ok)); expect(response.body, equals('$greeting $name')); }); }); }
dart_frog/examples/kitchen_sink/e2e/pets_test.dart/0
{'file_path': 'dart_frog/examples/kitchen_sink/e2e/pets_test.dart', 'repo_id': 'dart_frog', 'token_count': 467}
import 'package:dart_frog/dart_frog.dart'; Response onRequest(RequestContext context, String id, String name) { final greeting = context.read<String>(); return Response(body: '$greeting $name (user $id)'); }
dart_frog/examples/kitchen_sink/routes/users/[id]/[name].dart/0
{'file_path': 'dart_frog/examples/kitchen_sink/routes/users/[id]/[name].dart', 'repo_id': 'dart_frog', 'token_count': 69}
/// A generic interface for managing todos. library todos_data_source; export 'src/models/models.dart'; export 'src/todos_data_source.dart';
dart_frog/examples/todos/packages/todos_data_source/lib/todos_data_source.dart/0
{'file_path': 'dart_frog/examples/todos/packages/todos_data_source/lib/todos_data_source.dart', 'repo_id': 'dart_frog', 'token_count': 48}
import 'package:broadcast_bloc/broadcast_bloc.dart'; /// {@template counter_cubit} /// A cubit which manages the value of a count. /// {@endtemplate} class CounterCubit extends BroadcastCubit<int> { /// {@macro counter_cubit} CounterCubit() : super(0); /// Increment the current state. void increment() => emit(state + 1); /// Decrement the current state. void decrement() => emit(state - 1); }
dart_frog/examples/web_socket_counter/lib/counter/cubit/counter_cubit.dart/0
{'file_path': 'dart_frog/examples/web_socket_counter/lib/counter/cubit/counter_cubit.dart', 'repo_id': 'dart_frog', 'token_count': 134}
export 'form_data.dart';
dart_frog/packages/dart_frog/lib/src/body_parsers/body_parsers.dart/0
{'file_path': 'dart_frog/packages/dart_frog/lib/src/body_parsers/body_parsers.dart', 'repo_id': 'dart_frog', 'token_count': 10}
part of '_internal.dart'; /// Convert from [shelf.Middleware] into [Middleware]. Middleware fromShelfMiddleware(shelf.Middleware middleware) { return (handler) { return (context) async { final response = await middleware( (request) async { final response = await handler(RequestContext._(request)); return response._response; }, )(context.request._request); return Response._(response); }; }; } /// Convert from [Middleware] into [shelf.Middleware]. shelf.Middleware toShelfMiddleware(Middleware middleware) { return (innerHandler) { return (request) async { final response = await middleware((context) async { final response = await innerHandler(context.request._request); return Response._(response); })(RequestContext._(request)); return response._response; }; }; } /// Convert from a [shelf.Handler] into a [Handler]. Handler fromShelfHandler(shelf.Handler handler) { return (context) async { final response = await handler(context.request._request); return Response._(response); }; } /// Convert from a [Handler] into a [shelf.Handler]. shelf.Handler toShelfHandler(Handler handler) { return (request) async { final context = RequestContext._(request); final response = await handler.call(context); return response._response; }; }
dart_frog/packages/dart_frog/lib/src/shelf_adapters.dart/0
{'file_path': 'dart_frog/packages/dart_frog/lib/src/shelf_adapters.dart', 'repo_id': 'dart_frog', 'token_count': 460}
import 'dart:io'; import 'package:test/test.dart'; import 'run_process.dart'; Future<void> dartFrogNewRoute( String routePath, { required Directory directory, }) => _dartFrogNew( routePath: routePath, what: 'route', directory: directory, ); Future<void> dartFrogNewMiddleware( String routePath, { required Directory directory, }) => _dartFrogNew( routePath: routePath, what: 'middleware', directory: directory, ); Future<void> _dartFrogNew({ required String routePath, required String what, required Directory directory, }) async { await runProcess( 'dart_frog', ['new', what, routePath], workingDirectory: directory.path, runInShell: true, ); } Matcher failsWith({required String stderr}) { return throwsA( isA<RunProcessException>().having( (e) => (e.processResult.stderr as String).trim(), 'stderr', stderr, ), ); }
dart_frog/packages/dart_frog_cli/e2e/test/helpers/dart_frog_new.dart/0
{'file_path': 'dart_frog/packages/dart_frog_cli/e2e/test/helpers/dart_frog_new.dart', 'repo_id': 'dart_frog', 'token_count': 368}
/// {@template dart_frog_daemon_exception} /// An exception thrown when the daemon fails. /// {@endtemplate} abstract class DartFrogDaemonException implements Exception { /// {@macro dart_frog_daemon_exception} const DartFrogDaemonException(this.message); /// The exception message. final String message; } /// {@template dart_frog_daemon_message_exception} /// An exception thrown when the daemon fails to parse a message. /// {@endtemplate} class DartFrogDaemonMessageException extends DartFrogDaemonException { /// {@macro dart_frog_daemon_message_exception} const DartFrogDaemonMessageException(super.message); } /// {@template dart_frog_daemon_malformed_message_exception} /// An exception thrown when the daemon fails to parse the /// structure of a message. /// {@endtemplate} class DartFrogDaemonMalformedMessageException extends DartFrogDaemonMessageException { /// {@macro dart_frog_daemon_malformed_message_exception} const DartFrogDaemonMalformedMessageException(String message) : super('Malformed message, $message'); }
dart_frog/packages/dart_frog_cli/lib/src/daemon/exceptions.dart/0
{'file_path': 'dart_frog/packages/dart_frog_cli/lib/src/daemon/exceptions.dart', 'repo_id': 'dart_frog', 'token_count': 310}
import 'dart:convert'; import 'dart:io'; import 'package:dart_frog_cli/src/dev_server_runner/restorable_directory_generator_target.dart'; import 'package:mason/mason.dart'; import 'package:mocktail/mocktail.dart'; import 'package:test/test.dart'; class _FakeGeneratedFile extends Fake implements GeneratedFile {} void main() { group('$CachedFile', () { test('can be instantiated', () { const path = './path'; final contents = <int>[]; final instance = CachedFile(path: path, contents: contents); expect(instance.path, equals(path)); expect(instance.contents, equals(contents)); }); }); group('$RestorableDirectoryGeneratorTarget', () { late RestorableDirectoryGeneratorTarget generatorTarget; late Directory directory; setUpAll(() { directory = Directory.systemTemp.createTempSync(); }); test('caches and restores snapshots when available', () async { const path = './path'; final contents = utf8.encode('contents'); final createdFiles = <CachedFile>[]; generatorTarget = RestorableDirectoryGeneratorTarget( directory, createFile: (path, contents, {logger, overwriteRule}) async { createdFiles.add(CachedFile(path: path, contents: contents)); return _FakeGeneratedFile(); }, ); await generatorTarget.createFile(path, contents); expect(createdFiles.length, equals(1)); createdFiles.clear(); generatorTarget.cacheLatestSnapshot(); const otherPath = './other/path'; await generatorTarget.createFile(otherPath, contents); expect(createdFiles.length, equals(1)); expect(createdFiles.first.path, equals(otherPath)); expect(createdFiles.first.contents, equals(contents)); createdFiles.clear(); await generatorTarget.rollback(); expect(createdFiles.length, equals(1)); expect(createdFiles.first.path, equals(path)); expect(createdFiles.first.contents, equals(contents)); }); test('caches only previous 2 snapshots', () async { const path = './path'; final contents = utf8.encode('contents'); final createdFiles = <CachedFile>[]; generatorTarget = RestorableDirectoryGeneratorTarget( directory, createFile: (path, contents, {logger, overwriteRule}) async { createdFiles.add(CachedFile(path: path, contents: contents)); return _FakeGeneratedFile(); }, ); await generatorTarget.createFile(path, contents); generatorTarget.cacheLatestSnapshot(); expect(createdFiles.length, equals(1)); const otherPath = './other/path'; await generatorTarget.createFile(otherPath, contents); generatorTarget.cacheLatestSnapshot(); expect(createdFiles.length, equals(2)); expect(createdFiles.first.path, equals(path)); expect(createdFiles.first.contents, equals(contents)); expect(createdFiles.last.path, equals(otherPath)); expect(createdFiles.last.contents, equals(contents)); const anotherPath = './another/path'; await generatorTarget.createFile(anotherPath, contents); generatorTarget.cacheLatestSnapshot(); expect(createdFiles.length, equals(3)); expect(createdFiles.first.path, equals(path)); expect(createdFiles.first.contents, equals(contents)); expect(createdFiles[1].path, equals(otherPath)); expect(createdFiles[1].contents, equals(contents)); expect(createdFiles.last.path, equals(anotherPath)); expect(createdFiles.last.contents, equals(contents)); createdFiles.clear(); for (var i = 0; i < 3; i++) { await generatorTarget.rollback(); } expect(createdFiles.length, equals(3)); expect(createdFiles.first.path, equals(otherPath)); expect(createdFiles.first.contents, equals(contents)); expect(createdFiles[1].path, equals(otherPath)); expect(createdFiles[1].contents, equals(contents)); expect(createdFiles.last.path, equals(otherPath)); expect(createdFiles.last.contents, equals(contents)); }); test('restore does nothing when snapshot not available', () async { const path = './path'; final contents = utf8.encode('contents'); final createdFiles = <CachedFile>[]; generatorTarget = RestorableDirectoryGeneratorTarget( directory, createFile: (path, contents, {logger, overwriteRule}) async { createdFiles.add(CachedFile(path: path, contents: contents)); return _FakeGeneratedFile(); }, ); await generatorTarget.createFile(path, contents); expect(createdFiles.length, equals(1)); createdFiles.clear(); const otherPath = './other/path'; await generatorTarget.createFile(otherPath, contents); expect(createdFiles.length, equals(1)); expect(createdFiles.first.path, equals(otherPath)); expect(createdFiles.first.contents, equals(contents)); createdFiles.clear(); await generatorTarget.rollback(); expect(createdFiles, isEmpty); }); test( 'rollback does not remove snapshot ' 'when there is only one snapshot', () async { const path = './path'; final contents = utf8.encode('contents'); final createdFiles = <CachedFile>[]; generatorTarget = RestorableDirectoryGeneratorTarget( directory, createFile: (path, contents, {logger, overwriteRule}) async { createdFiles.add(CachedFile(path: path, contents: contents)); return _FakeGeneratedFile(); }, ); await generatorTarget.createFile(path, contents); expect(createdFiles.length, equals(1)); createdFiles.clear(); generatorTarget.cacheLatestSnapshot(); await generatorTarget.rollback(); createdFiles.clear(); const otherPath = './other/path'; await generatorTarget.createFile(otherPath, contents); expect(createdFiles.length, equals(1)); expect(createdFiles.first.path, equals(otherPath)); expect(createdFiles.first.contents, equals(contents)); createdFiles.clear(); await generatorTarget.rollback(); expect(createdFiles.length, equals(1)); expect(createdFiles.first.path, equals(path)); expect(createdFiles.first.contents, equals(contents)); }, ); test( 'rollback removes latest snapshot ' 'when there is more than one snapshot', () async { const path = './path'; final contents = utf8.encode('contents'); final createdFiles = <CachedFile>[]; generatorTarget = RestorableDirectoryGeneratorTarget( directory, createFile: (path, contents, {logger, overwriteRule}) async { createdFiles.add(CachedFile(path: path, contents: contents)); return _FakeGeneratedFile(); }, ); await generatorTarget.createFile(path, contents); expect(createdFiles.length, equals(1)); generatorTarget.cacheLatestSnapshot(); const otherPath = './other/path'; await generatorTarget.createFile(otherPath, contents); generatorTarget.cacheLatestSnapshot(); expect(createdFiles.length, equals(2)); expect(createdFiles.first.path, equals(path)); expect(createdFiles.first.contents, equals(contents)); expect(createdFiles.last.path, equals(otherPath)); expect(createdFiles.last.contents, equals(contents)); await generatorTarget.rollback(); createdFiles.clear(); await generatorTarget.rollback(); expect(createdFiles.length, equals(1)); expect(createdFiles.first.path, equals(path)); expect(createdFiles.first.contents, equals(contents)); }, ); }); }
dart_frog/packages/dart_frog_cli/test/src/commands/dev_server_runner/restorable_directory_generator_target_test.dart/0
{'file_path': 'dart_frog/packages/dart_frog_cli/test/src/commands/dev_server_runner/restorable_directory_generator_target_test.dart', 'repo_id': 'dart_frog', 'token_count': 2902}
import 'package:dart_frog_gen/dart_frog_gen.dart'; import 'package:mocktail/mocktail.dart'; import 'package:path/path.dart' as p; import 'package:test/test.dart'; class _MockRouteConfiguration extends Mock implements RouteConfiguration {} void main() { group('reportRogueRoutes', () { late RouteConfiguration configuration; late bool violationStartCalled; late bool violationEndCalled; late List<String> rogueRoutes; setUp(() { configuration = _MockRouteConfiguration(); violationStartCalled = false; violationEndCalled = false; rogueRoutes = []; }); test('reports nothing when there are no rogue routes', () { when(() => configuration.rogueRoutes).thenReturn([]); reportRogueRoutes( configuration, onViolationStart: () { violationStartCalled = true; }, onRogueRoute: (filePath, idealPath) { rogueRoutes.add(filePath); }, onViolationEnd: () { violationEndCalled = true; }, ); expect(violationStartCalled, isFalse); expect(violationEndCalled, isFalse); expect(rogueRoutes, isEmpty); }); test('reports single rogue route', () { when(() => configuration.rogueRoutes).thenReturn( const [ RouteFile( name: 'hello', path: 'hello.dart', route: '/hello', params: [], wildcard: false, ), ], ); reportRogueRoutes( configuration, onViolationStart: () { violationStartCalled = true; }, onRogueRoute: (filePath, idealPath) { rogueRoutes.add(filePath); }, onViolationEnd: () { violationEndCalled = true; }, ); expect(violationStartCalled, isTrue); expect(violationEndCalled, isTrue); expect(rogueRoutes, [p.join('routes', 'hello.dart')]); }); test('reports multiple rogue routes', () { when(() => configuration.rogueRoutes).thenReturn( const [ RouteFile( name: 'hello', path: 'hello.dart', route: '/hello', params: [], wildcard: false, ), RouteFile( name: 'hi', path: 'hi.dart', route: '/hi', params: [], wildcard: false, ), ], ); reportRogueRoutes( configuration, onViolationStart: () { violationStartCalled = true; }, onRogueRoute: (filePath, idealPath) { rogueRoutes.add(filePath); }, onViolationEnd: () { violationEndCalled = true; }, ); expect(violationStartCalled, isTrue); expect(violationEndCalled, isTrue); expect(rogueRoutes, [ p.join('routes', 'hello.dart'), p.join('routes', 'hi.dart'), ]); }); }); }
dart_frog/packages/dart_frog_gen/test/src/validate_route_configuration/rogue_routes_test.dart/0
{'file_path': 'dart_frog/packages/dart_frog_gen/test/src/validate_route_configuration/rogue_routes_test.dart', 'repo_id': 'dart_frog', 'token_count': 1417}
import 'package:sealed_unions/generic/union_9_eighth.dart'; import 'package:sealed_unions/generic/union_9_fifth.dart'; import 'package:sealed_unions/generic/union_9_first.dart'; import 'package:sealed_unions/generic/union_9_fourth.dart'; import 'package:sealed_unions/generic/union_9_ninth.dart'; import 'package:sealed_unions/generic/union_9_second.dart'; import 'package:sealed_unions/generic/union_9_seventh.dart'; import 'package:sealed_unions/generic/union_9_sixth.dart'; import 'package:sealed_unions/generic/union_9_third.dart'; import 'package:sealed_unions/union_9.dart'; // Creator class for Union9 abstract class Factory9<A, B, C, D, E, F, G, H, I> { Union9<A, B, C, D, E, F, G, H, I> first(A first); Union9<A, B, C, D, E, F, G, H, I> second(B second); Union9<A, B, C, D, E, F, G, H, I> third(C third); Union9<A, B, C, D, E, F, G, H, I> fourth(D fourth); Union9<A, B, C, D, E, F, G, H, I> fifth(E fifth); Union9<A, B, C, D, E, F, G, H, I> sixth(F sixth); Union9<A, B, C, D, E, F, G, H, I> seventh(G seventh); Union9<A, B, C, D, E, F, G, H, I> eighth(H eighth); Union9<A, B, C, D, E, F, G, H, I> ninth(I ninth); } class Nonet<A, B, C, D, E, F, G, H, I> implements Factory9<A, B, C, D, E, F, G, H, I> { const Nonet(); @override Union9<A, B, C, D, E, F, G, H, I> first(A first) => new Union9First<A, B, C, D, E, F, G, H, I>(first); @override Union9<A, B, C, D, E, F, G, H, I> second(B second) => new Union9Second<A, B, C, D, E, F, G, H, I>(second); @override Union9<A, B, C, D, E, F, G, H, I> third(C third) => new Union9Third<A, B, C, D, E, F, G, H, I>(third); @override Union9<A, B, C, D, E, F, G, H, I> fourth(D fourth) => new Union9Fourth<A, B, C, D, E, F, G, H, I>(fourth); @override Union9<A, B, C, D, E, F, G, H, I> fifth(E fifth) => new Union9Fifth<A, B, C, D, E, F, G, H, I>(fifth); @override Union9<A, B, C, D, E, F, G, H, I> sixth(F sixth) => new Union9Sixth<A, B, C, D, E, F, G, H, I>(sixth); @override Union9<A, B, C, D, E, F, G, H, I> seventh(G seventh) => new Union9Seventh<A, B, C, D, E, F, G, H, I>(seventh); @override Union9<A, B, C, D, E, F, G, H, I> eighth(H eighth) => new Union9Eighth<A, B, C, D, E, F, G, H, I>(eighth); @override Union9<A, B, C, D, E, F, G, H, I> ninth(I ninth) => new Union9Ninth<A, B, C, D, E, F, G, H, I>(ninth); }
dart_sealed_unions/lib/factories/nonet_factory.dart/0
{'file_path': 'dart_sealed_unions/lib/factories/nonet_factory.dart', 'repo_id': 'dart_sealed_unions', 'token_count': 1161}
import 'package:sealed_unions/union_3.dart'; class Union3Third<T, U, V> implements Union3<T, U, V> { final V _value; Union3Third(this._value); @override void continued( Function(T) continuationFirst, Function(U) continuationSecond, Function(V) continuationThird, ) { continuationThird(_value); } @override R join<R>( R Function(T) mapFirst, R Function(U) mapSecond, R Function(V) mapThird) { return mapThird(_value); } @override bool operator ==(Object other) => identical(this, other) || other is Union3Third && runtimeType == other.runtimeType && _value == other._value; @override int get hashCode => _value.hashCode; @override String toString() => _value.toString(); }
dart_sealed_unions/lib/generic/union_3_third.dart/0
{'file_path': 'dart_sealed_unions/lib/generic/union_3_third.dart', 'repo_id': 'dart_sealed_unions', 'token_count': 287}
import 'package:sealed_unions/union_7.dart'; class Union7Fifth<A, B, C, D, E, F, G> implements Union7<A, B, C, D, E, F, G> { final E _value; Union7Fifth(this._value); @override void continued( Function(A) continuationFirst, Function(B) continuationSecond, Function(C) continuationThird, Function(D) continuationFourth, Function(E) continuationFifth, Function(F) continuationSixth, Function(G) continuationSeventh, ) { continuationFifth(_value); } @override R join<R>( R Function(A) mapFirst, R Function(B) mapSecond, R Function(C) mapThird, R Function(D) mapFourth, R Function(E) mapFifth, R Function(F) mapSixth, R Function(G) mapSeventh, ) { return mapFifth(_value); } @override bool operator ==(Object other) => identical(this, other) || other is Union7Fifth && runtimeType == other.runtimeType && _value == other._value; @override int get hashCode => _value.hashCode; @override String toString() => _value.toString(); }
dart_sealed_unions/lib/generic/union_7_fifth.dart/0
{'file_path': 'dart_sealed_unions/lib/generic/union_7_fifth.dart', 'repo_id': 'dart_sealed_unions', 'token_count': 415}
import 'package:sealed_unions/union_8.dart'; class Union8Impl<A, B, C, D, E, F, G, H> implements Union8<A, B, C, D, E, F, G, H> { final Union8<A, B, C, D, E, F, G, H> _union; Union8Impl(Union8<A, B, C, D, E, F, G, H> union) : _union = union; @override void continued( Function(A) continuationFirst, Function(B) continuationSecond, Function(C) continuationThird, Function(D) continuationFourth, Function(E) continuationFifth, Function(F) continuationSixth, Function(G) continuationSeventh, Function(H) continuationEighth) { _union.continued( continuationFirst, continuationSecond, continuationThird, continuationFourth, continuationFifth, continuationSixth, continuationSeventh, continuationEighth); } @override R join<R>( R Function(A) mapFirst, R Function(B) mapSecond, R Function(C) mapThird, R Function(D) mapFourth, R Function(E) mapFifth, R Function(F) mapSixth, R Function(G) mapSeventh, R Function(H) mapEighth) { return _union.join(mapFirst, mapSecond, mapThird, mapFourth, mapFifth, mapSixth, mapSeventh, mapEighth); } @override bool operator ==(Object other) => identical(this, other) || other is Union8Impl && runtimeType == other.runtimeType && _union == other._union; @override int get hashCode => _union.hashCode; }
dart_sealed_unions/lib/implementations/union_8_impl.dart/0
{'file_path': 'dart_sealed_unions/lib/implementations/union_8_impl.dart', 'repo_id': 'dart_sealed_unions', 'token_count': 621}
class Fifteen { @override bool operator ==(Object other) => identical(this, other) || other is Fifteen && runtimeType == other.runtimeType; @override int get hashCode => 15; }
dart_sealed_unions/tennis/lib/fifteen.dart/0
{'file_path': 'dart_sealed_unions/tennis/lib/fifteen.dart', 'repo_id': 'dart_sealed_unions', 'token_count': 86}
# See https://github.com/amannn/action-semantic-pull-request name: 'PR Title is Conventional' on: pull_request_target: types: - opened - edited - synchronize jobs: main: name: Validate PR title runs-on: ubuntu-latest steps: - uses: amannn/action-semantic-pull-request@v4 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: types: | build chore ci docs feat fix perf refactor revert style test subjectPattern: ^[A-Z].+$ subjectPatternError: | The subject of the PR must begin with an uppercase letter.
dartdoc_json/.github/workflows/title_validation.yaml/0
{'file_path': 'dartdoc_json/.github/workflows/title_validation.yaml', 'repo_id': 'dartdoc_json', 'token_count': 402}
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/enum_constant_declaration.dart'; import 'package:dartdoc_json/src/implements_clause.dart'; import 'package:dartdoc_json/src/member_list.dart'; import 'package:dartdoc_json/src/type_parameter_list.dart'; import 'package:dartdoc_json/src/utils.dart'; import 'package:dartdoc_json/src/with_clause.dart'; /// Converts an EnumDeclaration into a json-compatible object. Map<String, dynamic>? serializeEnumDeclaration(EnumDeclaration enum_) { final annotations = serializeAnnotations(enum_.metadata); if (enum_.name.lexeme.startsWith('_') || hasPrivateAnnotation(annotations)) { return null; } return filterMap(<String, dynamic>{ 'kind': 'enum', 'name': enum_.name.lexeme, 'typeParameters': serializeTypeParameterList(enum_.typeParameters), 'with': serializeWithClause(enum_.withClause), 'implements': serializeImplementsClause(enum_.implementsClause), 'annotations': annotations, 'description': serializeComment(enum_.documentationComment), 'values': [ for (final value in enum_.constants) serializeEnumConstantDeclaration(value), ]..removeWhere((dynamic item) => item == null), 'members': serializeMemberList(enum_.members), }); }
dartdoc_json/lib/src/enum_declaration.dart/0
{'file_path': 'dartdoc_json/lib/src/enum_declaration.dart', 'repo_id': 'dartdoc_json', 'token_count': 483}
import 'package:analyzer/dart/ast/ast.dart'; import 'package:dartdoc_json/src/utils.dart'; Map<String, dynamic> serializePartDirective(PartDirective part) { return filterMap(<String, dynamic>{ 'kind': 'part', 'uri': part.uri.stringValue, }); } Map<String, dynamic> serializePartOfDirective(PartOfDirective partOf) { return filterMap(<String, dynamic>{ 'kind': 'part-of', 'uri': partOf.uri?.stringValue, 'name': partOf.libraryName?.name, }); }
dartdoc_json/lib/src/part_directive.dart/0
{'file_path': 'dartdoc_json/lib/src/part_directive.dart', 'repo_id': 'dartdoc_json', 'token_count': 181}
import 'package:test/test.dart'; import 'utils.dart'; void main() { group('LibraryDirective', () { test('simple library', () { expect( parseAsJson('library foo;'), {'kind': 'library', 'name': 'foo'}, ); }); }); }
dartdoc_json/test/library_directive_test.dart/0
{'file_path': 'dartdoc_json/test/library_directive_test.dart', 'repo_id': 'dartdoc_json', 'token_count': 112}
part of dartx_io; extension FileX on File { /// Appends an array of [bytes] to the content of this file. Future<void> appendBytes(List<int> bytes) async { var raf = await open(mode: FileMode.writeOnlyAppend); await raf.writeFrom(bytes); await raf.close(); } /// Appends a [string] to the content of this file using UTF-8 or the /// specified [encoding]. Future<void> appendString(String string, {Encoding encoding = utf8}) async { var raf = await open(mode: FileMode.writeOnlyAppend); await raf.writeString(string); await raf.close(); } /// Reads file by byte blocks and calls [action] for each block read. /// /// This functions passes the byte buffer to the [action] function. /// /// You can use this function for huge files. Future<Null> forEachBlock( int blockSize, void Function(Uint8List buffer) action) async { var raf = await open(mode: FileMode.read); while (true) { var buffer = await raf.read(blockSize); if (buffer.length == blockSize) { action(buffer); } else if (buffer.isNotEmpty) { action(buffer); break; } else { break; } } await raf.close(); } }
dartx/lib/src/io/file.dart/0
{'file_path': 'dartx/lib/src/io/file.dart', 'repo_id': 'dartx', 'token_count': 442}
import 'package:dartx/dartx.dart'; import 'package:test/test.dart'; void main() { group('rangeTo', () { test('upwards', () { expect(5.rangeTo(10).toList(), [5, 6, 7, 8, 9, 10]); }); test('downwards', () { expect(6.rangeTo(3).toList(), [6, 5, 4, 3]); }); test('empty when start == end', () { expect(6.rangeTo(6).toList(), []); }); }); group('rangeTo with step()', () { test('upwards', () { expect(5.rangeTo(10).step(2).toList(), [5, 7, 9]); }); test('downwards', () { expect(6.rangeTo(3).step(2).toList(), [6, 4]); }); test('step must be positive', () { expect(() => 1.rangeTo(10).step(0), throwsA(isA<RangeError>())); expect(() => 1.rangeTo(10).step(-2), throwsA(isA<RangeError>())); }); }); group('IntRange properties', () { test('first', () { expect(3.rangeTo(7).first, 3); }); test('last', () { expect(3.rangeTo(6).last, 6); expect(3.rangeTo(6).step(2).last, 5); }); test('stepSize', () { expect(3.rangeTo(6).stepSize, 1); expect(3.rangeTo(6).step(2).stepSize, 2); }); }); group('IntRange contains', () { test('contains', () { expect(0.rangeTo(10).step(2).contains(1), isFalse); expect(0.rangeTo(10).step(2).contains(0), isTrue); expect(0.rangeTo(10).step(2).contains(10), isTrue); }); }); }
dartx/test/range_test.dart/0
{'file_path': 'dartx/test/range_test.dart', 'repo_id': 'dartx', 'token_count': 636}
import 'package:dashbook/dashbook.dart'; import 'package:flutter/material.dart'; void addTextStories(Dashbook dashbook) { dashbook .storiesOf('Text') .decorator(CenterDecorator()) .add( 'default', (context) => Text( context.textProperty('text', 'Hello'), ), ) .add( 'with style', (_) => const Text( 'Hello world', style: TextStyle( color: Colors.blue, fontSize: 20, fontWeight: FontWeight.bold, ), ), ) .add( 'with overflow', (_) => const SizedBox( width: 100, child: Text( 'Hello world' 'Hello world' 'Hello world' 'Hello world' 'Hello world' 'Hello world' 'Hello world' 'Hello world' 'Hello world' 'Hello world' 'Hello world' 'Hello world' 'Hello world', overflow: TextOverflow.ellipsis, ), ), ); }
dashbook/bricks/dashbook_gallery/__brick__/gallery/lib/widgets/text.dart/0
{'file_path': 'dashbook/bricks/dashbook_gallery/__brick__/gallery/lib/widgets/text.dart', 'repo_id': 'dashbook', 'token_count': 613}
import 'package:dashbook/src/widgets/dashbook_icon.dart'; import 'package:dashbook/src/widgets/helpers.dart'; import 'package:dashbook/src/widgets/keys.dart'; import 'package:dashbook/src/widgets/select_device/custom_device.dart'; import 'package:dashbook/src/widgets/select_device/device_settings.dart'; import 'package:dashbook/src/widgets/select_device/select_device.dart'; import 'package:dashbook/src/widgets/side_bar_panel.dart'; import 'package:device_frame/device_frame.dart'; import 'package:flutter/material.dart'; class DeviceSettingsContainer extends StatefulWidget { final VoidCallback onCancel; const DeviceSettingsContainer({ Key? key, required this.onCancel, }) : super(key: key); @override State<DeviceSettingsContainer> createState() => _DeviceSettingsContainerState(); } class _DeviceSettingsContainerState extends State<DeviceSettingsContainer> { final _formKey = GlobalKey<FormState>(); bool _isCustom = false; @override void initState() { super.initState(); } void _setIsCustom(bool isCustom) { setState(() { _isCustom = isCustom; DeviceSettings.of(context, listen: false).updateDevice( isCustom ? Devices.android.largeTablet : null, ); }); } @override Widget build(BuildContext context) { return SideBarPanel( title: 'Properties', onCloseKey: kDevicePreviewCloseIcon, width: sideBarSizeProperties(context), onCancel: widget.onCancel, child: Padding( padding: const EdgeInsets.all(20), child: Column( mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.center, children: [ const _DeviceToggles(), CheckboxListTile( value: _isCustom, key: kCustomDeviceToggle, title: const Text('Custom device'), contentPadding: EdgeInsets.zero, onChanged: (value) => _setIsCustom(value!), ), if (_isCustom) CustomDevice( formKey: _formKey, changeToList: () { _setIsCustom(false); }, ) else const SelectDevice(), ], ), ), ); } } class _DeviceToggles extends StatelessWidget { const _DeviceToggles(); @override Widget build(BuildContext context) { final deviceSettings = DeviceSettings.of(context); return Row( children: [ DashbookIcon( key: kRotateIcon, tooltip: 'Orientation', icon: Icons.screen_rotation_outlined, onClick: deviceSettings.settings.deviceInfo != null ? deviceSettings.rotate : null, ), DashbookIcon( key: kHideFrameIcon, tooltip: 'Device frame', icon: Icons.mobile_off_outlined, onClick: deviceSettings.settings.deviceInfo != null ? deviceSettings.toggleDeviceFrame : null, ), const Spacer(), TextButton( onPressed: deviceSettings.reset, child: const Text('Reset'), ), ], ); } }
dashbook/lib/src/widgets/device_settings_container.dart/0
{'file_path': 'dashbook/lib/src/widgets/device_settings_container.dart', 'repo_id': 'dashbook', 'token_count': 1402}
import 'package:dashbook/src/widgets/property_widgets/widgets/property_dialog.dart'; import 'package:flutter/material.dart'; typedef ConfirmEditionFucntion = bool Function( bool, String, String, String, String, String, ); class FourIntegerForm extends StatefulWidget { final ConfirmEditionFucntion _confirmEdition; final int _value1; final int _value2; final int _value3; final int _value4; final String _label1; final String _label2; final String _label3; final String _label4; const FourIntegerForm( this._confirmEdition, this._value1, this._value2, this._value3, this._value4, this._label1, this._label2, this._label3, this._label4, { Key? key, }) : super(key: key); @override State createState() { return _FourIntegerFormState(); } } class _FourIntegerFormState extends State<FourIntegerForm> { bool _validValues = true; bool _useValueToAll = false; final _uniqueValueController = TextEditingController(); final _firstFieldController = TextEditingController(); final _secondFieldController = TextEditingController(); final _thirdFieldController = TextEditingController(); final _fourthFieldController = TextEditingController(); @override void initState() { super.initState(); _uniqueValueController.text = widget._value1.toString(); if (_allValueEqual()) { _useValueToAll = true; _firstFieldController.text = _uniqueValueController.text; _secondFieldController.text = _uniqueValueController.text; _thirdFieldController.text = _uniqueValueController.text; _fourthFieldController.text = _uniqueValueController.text; } else { _firstFieldController.text = widget._value1.toString(); _secondFieldController.text = widget._value2.toString(); _thirdFieldController.text = widget._value3.toString(); _fourthFieldController.text = widget._value4.toString(); } } bool _allValueEqual() { final values = <int>[ widget._value1, widget._value2, widget._value3, widget._value4, ]; return values.every((v) => v == values[0]); } @override Widget build(_) { return PropertyDialog( title: 'Set values:', content: Column( children: [ if (_validValues) Container() else const Text('Invalid values!'), Row( children: [ const Text( 'Same value to all:', ), Switch( value: _useValueToAll, onChanged: (bool isOn) => setState(() => _useValueToAll = isOn), activeColor: Colors.blue, inactiveTrackColor: Colors.grey, inactiveThumbColor: Colors.grey, ), ], ), if (_useValueToAll) SizedBox( width: 100, child: TextField(controller: _uniqueValueController), ) else Column( children: [ _FieldWithLabel( label: widget._label1, fieldController: _firstFieldController, ), _FieldWithLabel( label: widget._label2, fieldController: _secondFieldController, ), _FieldWithLabel( label: widget._label3, fieldController: _thirdFieldController, ), _FieldWithLabel( label: widget._label4, fieldController: _fourthFieldController, ), ], ), ], ), actions: [ TextButton( child: const Text('Got it'), onPressed: () { final validValues = widget._confirmEdition( _useValueToAll, _uniqueValueController.text, _firstFieldController.text, _secondFieldController.text, _thirdFieldController.text, _fourthFieldController.text, ); if (validValues) { setState(() { _validValues = true; }); Navigator.of(context).pop(); } else { setState(() => _validValues = false); } }, ), ], ); } } class _FieldWithLabel extends StatelessWidget { final String label; final TextEditingController fieldController; const _FieldWithLabel({required this.label, required this.fieldController}); @override Widget build(_) { return Row( children: [ SizedBox(width: 105, child: Text('$label:')), SizedBox(width: 90, child: TextField(controller: fieldController)), ], ); } }
dashbook/lib/src/widgets/property_widgets/widgets/property_4_integer_form.dart/0
{'file_path': 'dashbook/lib/src/widgets/property_widgets/widgets/property_4_integer_form.dart', 'repo_id': 'dashbook', 'token_count': 2180}
dartdoc: favicon: "assets/favicon.png"
dashtronaut/dartdoc_options.yaml/0
{'file_path': 'dashtronaut/dartdoc_options.yaml', 'repo_id': 'dashtronaut', 'token_count': 18}
import 'package:dashtronaut/models/position.dart'; import 'package:dashtronaut/presentation/common/animations/utils/animations_manager.dart'; import 'package:dashtronaut/presentation/layout/background_layer_layout.dart'; import 'package:flutter/material.dart'; class AnimatedBackgroundLayer extends StatefulWidget { final BackgroundLayerLayout layer; const AnimatedBackgroundLayer({ Key? key, required this.layer, }) : super(key: key); @override _AnimatedBackgroundLayerState createState() => _AnimatedBackgroundLayerState(); } class _AnimatedBackgroundLayerState extends State<AnimatedBackgroundLayer> with SingleTickerProviderStateMixin { late final AnimationController _animationController; late final Animation<Position> _position; @override void initState() { _animationController = AnimationController( duration: AnimationsManager.bgLayer(widget.layer).duration, vsync: this, ); _position = AnimationsManager.bgLayer(widget.layer).tween.animate( CurvedAnimation( parent: _animationController, curve: AnimationsManager.bgLayer(widget.layer).curve, ), ); Future.delayed(const Duration(milliseconds: 400), () { _animationController.forward(); }); super.initState(); } @override void dispose() { _animationController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return AnimatedBuilder( animation: _position, child: Image.asset( widget.layer.assetUrl, width: widget.layer.size.width, ), builder: (c, image) => Positioned( left: _position.isCompleted ? widget.layer.position.left : _position.value.left, top: _position.isCompleted ? widget.layer.position.top : _position.value.top, right: _position.isCompleted ? widget.layer.position.right : _position.value.right, bottom: _position.isCompleted ? widget.layer.position.bottom : _position.value.bottom, child: image!, ), ); } }
dashtronaut/lib/presentation/background/widgets/animated_background_layer.dart/0
{'file_path': 'dashtronaut/lib/presentation/background/widgets/animated_background_layer.dart', 'repo_id': 'dashtronaut', 'token_count': 824}
import 'package:dashtronaut/presentation/layout/phrase_bubble_layout.dart'; import 'package:dashtronaut/presentation/styles/app_colors.dart'; import 'package:dashtronaut/presentation/styles/app_text_styles.dart'; import 'package:dashtronaut/providers/phrases_provider.dart'; import 'package:dashtronaut/providers/puzzle_provider.dart'; import 'package:dashtronaut/providers/stop_watch_provider.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; class PuzzleSizeItem extends StatelessWidget { final int size; const PuzzleSizeItem({required this.size, Key? key}) : super(key: key); @override Widget build(BuildContext context) { StopWatchProvider stopWatchProvider = Provider.of<StopWatchProvider>(context, listen: false); PhrasesProvider phrasesProvider = Provider.of<PhrasesProvider>(context, listen: false); return Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ Consumer<PuzzleProvider>( builder: (c, puzzleProvider, _) { bool isSelected = puzzleProvider.n == size; return ElevatedButton( onPressed: () { if (!isSelected) { puzzleProvider.resetPuzzleSize(size); stopWatchProvider.stop(); if (size > 4) { phrasesProvider .setPhraseState(PhraseState.hardPuzzleSelected); } if (Scaffold.of(context).hasDrawer && Scaffold.of(context).isDrawerOpen) { Navigator.of(context).pop(); } } }, style: ElevatedButton.styleFrom( padding: const EdgeInsets.all(0), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(12), side: const BorderSide(width: 1, color: Colors.white), ), minimumSize: const Size.fromHeight(50), backgroundColor: isSelected ? Colors.white : null, ), child: Text( '$size x $size', style: AppTextStyles.buttonSm.copyWith( color: isSelected ? AppColors.primary : Colors.white), ), ); }, ), const SizedBox(height: 5), Text('${(size * size) - 1} Tiles', style: AppTextStyles.bodyXxs), ], ); } }
dashtronaut/lib/presentation/drawer/puzzle_size_item.dart/0
{'file_path': 'dashtronaut/lib/presentation/drawer/puzzle_size_item.dart', 'repo_id': 'dashtronaut', 'token_count': 1199}
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 CorrectTilesCount extends StatelessWidget { const CorrectTilesCount({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Consumer<PuzzleProvider>( builder: (c, puzzleProvider, _) => RichText( text: TextSpan( text: 'Correct Tiles: ', style: AppTextStyles.body.copyWith(color: Colors.white), children: <TextSpan>[ TextSpan( text: '${puzzleProvider.correctTilesCount}/${puzzleProvider.puzzle.tiles.length - 1}', style: AppTextStyles.bodyBold.copyWith(color: Colors.white), ), ], ), ), ); } }
dashtronaut/lib/presentation/puzzle/ui/correct_tiles_count.dart/0
{'file_path': 'dashtronaut/lib/presentation/puzzle/ui/correct_tiles_count.dart', 'repo_id': 'dashtronaut', 'token_count': 390}
import 'package:dashtronaut/services/storage/storage_service.dart'; import 'package:hive_flutter/hive_flutter.dart'; class HiveStorageService implements StorageService { late Box _hiveBox; @override Future<void> init() async { await Hive.initFlutter(); _hiveBox = await Hive.openBox('dashtronaut'); } @override Future<void> remove(String key) async { _hiveBox.delete(key); } @override dynamic get(String key) { return _hiveBox.get(key); } @override bool has(String key) { return _hiveBox.containsKey(key); } @override Future<void> set(String? key, dynamic data) async { _hiveBox.put(key, data); } @override Future<void> clear() async { await _hiveBox.clear(); } }
dashtronaut/lib/services/storage/hive_storage_service.dart/0
{'file_path': 'dashtronaut/lib/services/storage/hive_storage_service.dart', 'repo_id': 'dashtronaut', 'token_count': 279}
import 'package:dashtronaut/models/location.dart'; import 'package:dashtronaut/models/position.dart'; import 'package:dashtronaut/models/tile.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { Tile tile = const Tile( value: 2, currentLocation: Location(x: 1, y: 3), correctLocation: Location(x: 2, y: 1), ); group('Tile Model', () { test('Checks if tile is at correct location', () { Tile correctLocationTile = const Tile( value: 2, correctLocation: Location(x: 2, y: 1), currentLocation: Location(x: 2, y: 1), ); Tile incorrectLocationTile = const Tile( value: 1, correctLocation: Location(x: 1, y: 1), currentLocation: Location(x: 2, y: 1), ); expect(correctLocationTile.isAtCorrectLocation, true); expect(incorrectLocationTile.isAtCorrectLocation, false); }); testWidgets( 'Returns current position of tile in a Stack based on its width', (WidgetTester tester) async { await tester.pumpWidget( Builder(builder: (BuildContext context) { expect( tile.getPosition(context, 100), const Position(top: 200, left: 0), ); return const Placeholder(); }), ); }, ); test('Returns correct model from json map', () { Map<String, dynamic> tileJson = { 'value': 1, 'tileIsWhiteSpace': false, 'currentLocation': {'x': 1, 'y': 1}, 'correctLocation': {'x': 1, 'y': 1}, }; Tile expectedTile = const Tile( value: 1, currentLocation: Location(x: 1, y: 1), correctLocation: Location(x: 1, y: 1), ); expect(Tile.fromJson(tileJson), expectedTile); }); test('Returns json map from model', () { Tile tile = const Tile( value: 1, currentLocation: Location(x: 1, y: 1), correctLocation: Location(x: 1, y: 1), ); Map<String, dynamic> expectedTileJson = { 'value': 1, 'tileIsWhiteSpace': false, 'currentLocation': {'x': 1, 'y': 1}, 'correctLocation': {'x': 1, 'y': 1}, }; expect(tile.toJson(), expectedTileJson); }); test('toString prints correctly', () { expect( tile.toString(), equals( 'Tile(value: 2, correctLocation: (1, 2), currentLocation: (3, 1))')); }); test('copyWith updates tile', () { expect( tile.copyWith().currentLocation, equals(const Location(x: 1, y: 3))); expect( tile .copyWith(currentLocation: const Location(x: 2, y: 1)) .currentLocation, equals(const Location(x: 2, y: 1)), ); }); }); }
dashtronaut/test/models/tile_test.dart/0
{'file_path': 'dashtronaut/test/models/tile_test.dart', 'repo_id': 'dashtronaut', 'token_count': 1237}
import 'package:declarative_reactivity_workshop/log.dart'; import 'package:declarative_reactivity_workshop/src/atom.dart'; import 'package:declarative_reactivity_workshop/state.dart'; void main() { final container = AtomContainer() // ..onDispose(() => log('on-dispose-container', 0)); container.listen(personState.select((_) => _.id), (previous, value) { log('listen-person-state-id', (previous, value)); }); container.listen(personState.select((_) => _.canDrive), (previous, value) { log('listen-person-state-canDrive', (previous, value)); }); container.listen(personState.select((_) => _.fullname), (previous, value) { log('listen-person-state-fullname', (previous, value)); }); for (var i = 0; i < 10; i++) { container.mutate(passThrough(1), (value) => 2); container.mutate(lastname, (value) => 'v. Last'); container.mutate(age, (_) => 5); } container.dispose(); }
declarative_reactivity_workshop/bin/state_selectors.dart/0
{'file_path': 'declarative_reactivity_workshop/bin/state_selectors.dart', 'repo_id': 'declarative_reactivity_workshop', 'token_count': 335}
import 'package:flutter/material.dart'; import 'package:flutter_demo/countervisual.dart'; class Counter extends StatefulWidget { const Counter({Key key, this.duration}) : super(key: key); final Duration duration; @override _CounterState createState() => _CounterState(); } class _CounterState extends State<Counter> with TickerProviderStateMixin { int counter = 0; int counter2 = 0; AnimationController animationController; AnimationController animationController2; Animation<int> animatedCounter = const AlwaysStoppedAnimation(0); Animation<int> animatedCounter2 = const AlwaysStoppedAnimation(0); @override void initState() { super.initState(); animationController = AnimationController( duration: widget.duration, vsync: this, ); animationController2 = AnimationController( duration: widget.duration * 2, vsync: this, ); } @override void didUpdateWidget(Counter oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.duration != widget.duration) { animationController.duration = widget.duration; animationController2.duration = widget.duration * 2; } } @override void dispose() { animationController.dispose(); animationController2.dispose(); super.dispose(); } void _increment() { setState(() { counter += 100; animatedCounter = IntTween( begin: animatedCounter.value, end: counter, ).animate(animationController); }); animationController.forward(from: 0); } void _increment2() { setState(() { counter2 += 200; animatedCounter2 = IntTween( begin: animatedCounter2.value, end: counter2, ).animate(animationController2); }); animationController2.forward(from: 0); } @override Widget build(BuildContext context) { return Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ AnimatedBuilder( animation: animatedCounter, builder: (context, _) { return CounterVisual( animatedCounter.value, onPressed: _increment, ); }), AnimatedBuilder( animation: animatedCounter2, builder: (context, _) { return CounterVisual( animatedCounter2.value, onPressed: _increment2, ); }), AnimatedBuilder( animation: animatedCounter, builder: (context, _) => AnimatedBuilder( animation: animatedCounter2, builder: (context, _) { return Text( 'Total: ${animatedCounter.value + animatedCounter2.value}'); }), ), ], ); } }
demo_21-01-2019/lib/counter.dart/0
{'file_path': 'demo_21-01-2019/lib/counter.dart', 'repo_id': 'demo_21-01-2019', 'token_count': 1135}
import 'package:deposit/deposit.dart'; class MovieEntity extends Entity { MovieEntity({ this.id, required this.title, }); factory MovieEntity.fromJSON(Map<String, dynamic> data) { return MovieEntity( id: data['id'] as int?, title: data['title'] as String? ?? 'No title', ); } int? id; String title; @override Map<String, dynamic> toJSON() { return <String, dynamic>{ 'id': id, 'title': title, }; } @override String toString() => '$id: $title'; } class MovieDeposit extends Deposit<MovieEntity, int> { MovieDeposit() : super('movies', MovieEntity.fromJSON); } Future<void> main() async { Deposit.defaultAdapter = MemoryDepositAdapter(); final movieDeposit = MovieDeposit(); await movieDeposit.add(MovieEntity(title: 'The Godfather')); await movieDeposit.add(MovieEntity(title: 'Avatar')); final movie = await movieDeposit.getById(1); print('Movie id: ${movie.id}'); print(await movieDeposit.page(orderBy: OrderBy('title', ascending: true))); }
deposit/packages/deposit/example/main.dart/0
{'file_path': 'deposit/packages/deposit/example/main.dart', 'repo_id': 'deposit', 'token_count': 368}
name: devtools description: A suite of web-based performance tooling for Dart and Flutter. # Note: this version should only be updated by running tools/update_version.dart # that updates all versions of packages from packages/devtools. # # All the real functionality has moved to the devtools_app package with this # package remaining purely as a container for the compiled copy of the devtools # app. That ensures that version constraints for the devtools_app do not impact # this package. version: 2.3.3-dev.1 homepage: https://github.com/flutter/devtools environment: sdk: '>=2.3.0 <3.0.0' dependencies: devtools_server: 2.3.3-dev.1 devtools_shared: 2.3.3-dev.1 http: ^0.13.0 dependency_overrides: # The "#OVERRIDE_FOR_DEVELOPMENT" lines are stripped out when we publish. # All overriden dependencies are published together so there is no harm # in treating them like they are part of a mono-repo while developing. devtools_shared: #OVERRIDE_FOR_DEVELOPMENT path: ../devtools_shared #OVERRIDE_FOR_DEVELOPMENT devtools_server: #OVERRIDE_FOR_DEVELOPMENT path: ../devtools_server #OVERRIDE_FOR_DEVELOPMENT executables: devtools:
devtools/packages/devtools/pubspec.yaml/0
{'file_path': 'devtools/packages/devtools/pubspec.yaml', 'repo_id': 'devtools', 'token_count': 377}
// 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:async'; import '../config_specific/server/server.dart' as server; import 'analytics.dart' as analytics; import 'provider.dart'; class _RemoteAnalyticsProvider implements AnalyticsProvider { _RemoteAnalyticsProvider( this._isEnabled, this._isFirstRun, this._isGtagsEnabled, ); bool _isConfigured = false; @override bool get isEnabled => _isEnabled; final bool _isEnabled; @override bool get shouldPrompt => _isFirstRun && !_isConfigured; final bool _isFirstRun; @override bool get isGtagsEnabled => _isGtagsEnabled; final bool _isGtagsEnabled; @override void setAllowAnalytics() { _isConfigured = true; analytics.setAllowAnalytics(); } @override void setDontAllowAnalytics() { _isConfigured = true; analytics.setDontAllowAnalytics(); } @override void setUpAnalytics() { if (!_isGtagsEnabled) return; analytics.initializeGA(); analytics.jsHookupListenerForGA(); } } Future<AnalyticsProvider> get analyticsProvider async { if (_providerCompleter != null) return _providerCompleter.future; _providerCompleter = Completer<AnalyticsProvider>(); var isEnabled = false; var isFirstRun = false; var isGtagsEnabled = false; try { analytics.exposeGaDevToolsEnabledToJs(); if (analytics.isGtagsReset()) { await server.resetDevToolsFile(); } if (await analytics.isAnalyticsEnabled()) { isEnabled = true; } if (await server.isFirstRun()) { isFirstRun = true; } isGtagsEnabled = analytics.isGtagsEnabled(); } catch (_) { // Ignore issues if analytics could not be initialized. } _providerCompleter.complete( _RemoteAnalyticsProvider(isEnabled, isFirstRun, isGtagsEnabled)); return _providerCompleter.future; } Completer<AnalyticsProvider> _providerCompleter;
devtools/packages/devtools_app/lib/src/analytics/remote_provider.dart/0
{'file_path': 'devtools/packages/devtools_app/lib/src/analytics/remote_provider.dart', 'repo_id': 'devtools', 'token_count': 681}
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:math' as math; import 'dart:ui'; import 'package:collection/collection.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import '../auto_dispose_mixin.dart'; import '../common_widgets.dart'; import '../dialogs.dart'; import '../extent_delegate_list.dart'; import '../flutter_widgets/linked_scroll_controller.dart'; import '../theme.dart'; import '../trees.dart'; import '../ui/colors.dart'; import '../ui/search.dart'; import '../utils.dart'; const double rowPadding = 2.0; const double rowHeight = 25.0; const double rowHeightWithPadding = rowHeight + rowPadding; const double sectionSpacing = 16.0; const double sideInset = 70.0; const double sideInsetSmall = 60.0; // TODO(kenz): add some indication that we are scrolled out of the relevant area // so that users don't get lost in the extra pixels at the end of the chart. // TODO(kenz): consider cleaning up by changing to a flame chart code to use a // composition pattern instead of a class extension pattern. abstract class FlameChart<T, V> extends StatefulWidget { const FlameChart( this.data, { @required this.time, @required this.containerWidth, @required this.containerHeight, @required this.selectionNotifier, @required this.onDataSelected, this.searchMatchesNotifier, this.activeSearchMatchNotifier, this.startInset = sideInset, this.endInset = sideInset, }); static const minZoomLevel = 1.0; static const zoomMultiplier = 0.01; static const minScrollOffset = 0.0; static const rowOffsetForBottomPadding = 1; static const rowOffsetForSectionSpacer = 1; /// Maximum scroll delta allowed for scroll wheel based zooming. /// /// This isn't really needed but is a reasonable for safety in case we /// aren't handling some mouse based scroll wheel behavior well, etc. static const double maxScrollWheelDelta = 20.0; final T data; final TimeRange time; final double containerWidth; final double containerHeight; final double startInset; final double endInset; final ValueListenable<V> selectionNotifier; final ValueListenable<List<V>> searchMatchesNotifier; final ValueListenable<V> activeSearchMatchNotifier; final void Function(V data) onDataSelected; double get startingContentWidth => containerWidth - startInset - endInset; } // TODO(kenz): cap number of nodes we can show per row at once - need this for // performance improvements. Optionally we could also do something clever with // grouping nodes that are close together until they are zoomed in (quad tree // like implementation). abstract class FlameChartState<T extends FlameChart, V extends FlameChartDataMixin<V>> extends State<T> with AutoDisposeMixin, FlameChartColorMixin, TickerProviderStateMixin { int get rowOffsetForTopPadding => 2; // The "top" positional value for each flame chart node will be 0.0 because // each node is positioned inside its own list. final flameChartNodeTop = 0.0; final List<FlameChartRow<V>> rows = []; final List<FlameChartSection> sections = []; final focusNode = FocusNode(); bool _altKeyPressed = false; double mouseHoverX; FixedExtentDelegate verticalExtentDelegate; LinkedScrollControllerGroup verticalControllerGroup; LinkedScrollControllerGroup horizontalControllerGroup; ScrollController _flameChartScrollController; /// Animation controller for animating flame chart zoom changes. @visibleForTesting AnimationController zoomController; double currentZoom = FlameChart.minZoomLevel; double horizontalScrollOffset = FlameChart.minScrollOffset; double verticalScrollOffset = FlameChart.minScrollOffset; // Scrolling via WASD controls will pan the left/right 25% of the view. double get keyboardScrollUnit => widget.containerWidth * 0.25; // Zooming in via WASD controls will zoom the view in by 50% on each zoom. For // example, if the zoom level is 2.0, zooming by one unit would increase the // level to 3.0 (e.g. 2 + (2 * 0.5) = 3). double get keyboardZoomInUnit => currentZoom * 0.5; // Zooming out via WASD controls will zoom the view out to the previous zoom // level. For example, if the zoom level is 3.0, zooming out by one unit would // decrease the level to 2.0 (e.g. 3 - 3 * 1/3 = 2). See [wasdZoomInUnit] // for an explanation of how we previously zoomed from level 2.0 to level 3.0. double get keyboardZoomOutUnit => currentZoom * 1 / 3; double get contentWidthWithZoom => widget.startingContentWidth * currentZoom; double get widthWithZoom => contentWidthWithZoom + widget.startInset + widget.endInset; TimeRange get visibleTimeRange { final horizontalScrollOffset = horizontalControllerGroup.offset; final startMicros = horizontalScrollOffset < widget.startInset ? startTimeOffset : startTimeOffset + (horizontalScrollOffset - widget.startInset) / currentZoom / startingPxPerMicro; final endMicros = startTimeOffset + (horizontalScrollOffset - widget.startInset + widget.containerWidth) / currentZoom / startingPxPerMicro; return TimeRange() ..start = Duration(microseconds: startMicros.round()) ..end = Duration(microseconds: endMicros.round()); } /// Starting pixels per microsecond in order to fit all the data in view at /// start. double get startingPxPerMicro => widget.startingContentWidth / widget.time.duration.inMicroseconds; int get startTimeOffset => widget.time.start.inMicroseconds; double get maxZoomLevel { // The max zoom level is hit when 1 microsecond is the width of each grid // interval (this may bottom out at 2 micros per interval due to rounding). return TimelineGridPainter.baseGridIntervalPx * widget.time.duration.inMicroseconds / widget.startingContentWidth; } /// Provides widgets to be layered on top of the flame chart, if overridden. /// /// The widgets will be layered in a [Stack] in the order that they are /// returned. List<Widget> buildChartOverlays( BoxConstraints constraints, BuildContext buildContext, ) { return const []; } @override void initState() { super.initState(); initFlameChartElements(); horizontalControllerGroup = LinkedScrollControllerGroup(); verticalControllerGroup = LinkedScrollControllerGroup(); addAutoDisposeListener(horizontalControllerGroup.offsetNotifier, () { setState(() { horizontalScrollOffset = horizontalControllerGroup.offset; }); }); addAutoDisposeListener(verticalControllerGroup.offsetNotifier, () { setState(() { verticalScrollOffset = verticalControllerGroup.offset; }); }); _flameChartScrollController = verticalControllerGroup.addAndGet(); zoomController = AnimationController( value: FlameChart.minZoomLevel, lowerBound: FlameChart.minZoomLevel, upperBound: maxZoomLevel, vsync: this, )..addListener(_handleZoomControllerValueUpdate); verticalExtentDelegate = FixedExtentDelegate( computeExtent: (index) => rows[index].nodes.isEmpty ? sectionSpacing : rowHeightWithPadding, computeLength: () => rows.length, ); if (widget.activeSearchMatchNotifier != null) { addAutoDisposeListener(widget.activeSearchMatchNotifier, () async { final activeSearch = widget.activeSearchMatchNotifier.value; if (activeSearch == null) return; // Ensure the [activeSearch] is vertically in view. if (!isDataVerticallyInView(activeSearch)) { await scrollVerticallyToData(activeSearch); } // TODO(kenz): zoom if the event is less than some min width. // Ensure the [activeSearch] is horizontally in view. if (!isDataHorizontallyInView(activeSearch)) { await scrollHorizontallyToData(activeSearch); } }); } } @override void didUpdateWidget(T oldWidget) { if (widget.data != oldWidget.data) { initFlameChartElements(); horizontalControllerGroup.resetScroll(); verticalControllerGroup.resetScroll(); zoomController.reset(); verticalExtentDelegate.recompute(); } FocusScope.of(context).requestFocus(focusNode); super.didUpdateWidget(oldWidget); } @override void dispose() { zoomController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { // TODO(kenz): handle tooltips hover here instead of wrapping each row in a // MouseRegion widget. return MouseRegion( onHover: _handleMouseHover, child: RawKeyboardListener( autofocus: true, focusNode: focusNode, onKey: (event) => _handleKeyEvent(event), // Scrollbar needs to wrap [LayoutBuilder] so that the scroll bar is // rendered on top of the custom painters defined in [buildCustomPaints] child: Scrollbar( controller: _flameChartScrollController, isAlwaysShown: true, child: LayoutBuilder( builder: (context, constraints) { final chartOverlays = buildChartOverlays(constraints, context); final flameChart = _buildFlameChart(constraints); return chartOverlays.isNotEmpty ? Stack( children: [ flameChart, ...chartOverlays, ], ) : flameChart; }, ), ), ), ); } Widget _buildFlameChart(BoxConstraints constraints) { return ExtentDelegateListView( physics: const ClampingScrollPhysics(), controller: _flameChartScrollController, extentDelegate: verticalExtentDelegate, customPointerSignalHandler: _handlePointerSignal, childrenDelegate: SliverChildBuilderDelegate( (context, index) { final nodes = rows[index].nodes; var rowBackgroundColor = Colors.transparent; if (index >= rowOffsetForTopPadding && nodes.isEmpty) { // If this is a spacer row, we should use the background color of // the previous row with nodes. for (int i = index; i >= rowOffsetForTopPadding; i--) { // Look back until we find the first non-empty row. if (rows[i].nodes.isNotEmpty) { rowBackgroundColor = alternatingColorForIndex( rows[i].nodes.first.sectionIndex, Theme.of(context).colorScheme, ); break; } } } else if (nodes.isNotEmpty) { rowBackgroundColor = alternatingColorForIndex( nodes.first.sectionIndex, Theme.of(context).colorScheme, ); } return ScrollingFlameChartRow<V>( linkedScrollControllerGroup: horizontalControllerGroup, nodes: nodes, width: math.max(constraints.maxWidth, widthWithZoom), startInset: widget.startInset, selectionNotifier: widget.selectionNotifier, searchMatchesNotifier: widget.searchMatchesNotifier, activeSearchMatchNotifier: widget.activeSearchMatchNotifier, onTapUp: focusNode.requestFocus, backgroundColor: rowBackgroundColor, zoom: currentZoom, ); }, childCount: rows.length, addAutomaticKeepAlives: false, ), ); } // This method must be overridden by all subclasses. @mustCallSuper void initFlameChartElements() { rows.clear(); sections.clear(); } void expandRows(int newRowLength) { final currentLength = rows.length; for (int i = currentLength; i < newRowLength; i++) { rows.add(FlameChartRow<V>(i)); } } void _handleMouseHover(PointerHoverEvent event) { mouseHoverX = event.localPosition.dx; } void _handleKeyEvent(RawKeyEvent event) { if (event.isAltPressed) { _altKeyPressed = true; } else { _altKeyPressed = false; } // Only handle down events so logic is not duplicated on key up. if (event is RawKeyDownEvent) { // Handle zooming / navigation from W-A-S-D keys. final keyLabel = event.data.keyLabel; // TODO(kenz): zoom in/out faster if key is held. It actually zooms slower // if the key is held currently. if (keyLabel == 'w') { zoomTo(math.min( maxZoomLevel, currentZoom + keyboardZoomInUnit, )); } else if (keyLabel == 's') { zoomTo(math.max( FlameChart.minZoomLevel, currentZoom - keyboardZoomOutUnit, )); } else if (keyLabel == 'a') { scrollToX(horizontalControllerGroup.offset - keyboardScrollUnit); } else if (keyLabel == 'd') { scrollToX(horizontalControllerGroup.offset + keyboardScrollUnit); } } } void _handlePointerSignal(PointerSignalEvent event) async { if (event is PointerScrollEvent) { final deltaX = event.scrollDelta.dx; double deltaY = event.scrollDelta.dy; if (deltaY.abs() >= deltaX.abs()) { if (_altKeyPressed) { verticalControllerGroup.jumpTo(math.max( math.min( verticalControllerGroup.offset + deltaY, verticalControllerGroup.position.maxScrollExtent, ), 0.0, )); } else { deltaY = deltaY.clamp( -FlameChart.maxScrollWheelDelta, FlameChart.maxScrollWheelDelta, ); // TODO(kenz): if https://github.com/flutter/flutter/issues/52762 is, // resolved, consider adjusting the multiplier based on the scroll device // kind (mouse or track pad). final multiplier = FlameChart.zoomMultiplier * currentZoom; final newZoomLevel = (currentZoom + deltaY * multiplier).clamp( FlameChart.minZoomLevel, maxZoomLevel, ); await zoomTo(newZoomLevel, jump: true); if (newZoomLevel == FlameChart.minZoomLevel && horizontalControllerGroup.offset != 0.0) { // We do not need to call this in a post frame callback because // `FlameChart.minScrollOffset` (0.0) is guaranteed to be less than // the scroll controllers max scroll extent. await scrollToX(FlameChart.minScrollOffset); } } } } } void _handleZoomControllerValueUpdate() { final previousZoom = currentZoom; final newZoom = zoomController.value; if (previousZoom == newZoom) return; // Store current scroll values for re-calculating scroll location on zoom. final lastScrollOffset = horizontalControllerGroup.offset; final safeMouseHoverX = mouseHoverX ?? widget.containerWidth / 2; // Position in the zoomable coordinate space that we want to keep fixed. final fixedX = safeMouseHoverX + lastScrollOffset - widget.startInset; // Calculate the new horizontal scroll position. final newScrollOffset = fixedX >= 0 ? fixedX * newZoom / previousZoom + widget.startInset - safeMouseHoverX // We are in the fixed portion of the window - no need to transform. : lastScrollOffset; setState(() { currentZoom = zoomController.value; // TODO(kenz): consult with Flutter team to see if there is a better place // to call this that guarantees the scroll controller offsets will be // updated for the new zoom level and layout size // https://github.com/flutter/devtools/issues/2012. scrollToX(newScrollOffset, jump: true); }); } Future<void> zoomTo( double zoom, { double forceMouseX, bool jump = false, }) async { if (forceMouseX != null) { mouseHoverX = forceMouseX; } await zoomController.animateTo( zoom.clamp(FlameChart.minZoomLevel, maxZoomLevel), duration: jump ? Duration.zero : shortDuration, ); } /// Scroll the flame chart horizontally to [offset] scroll position. /// /// If this is being called immediately after a zoom call, without a chance /// for the UI to build between the zoom call and the call to /// this method, the call to this method should be placed inside of a /// postFrameCallback: /// `WidgetsBinding.instance.addPostFrameCallback((_) { ... });`. FutureOr<void> scrollToX( double offset, { bool jump = false, }) async { final target = offset.clamp( FlameChart.minScrollOffset, horizontalControllerGroup.position.maxScrollExtent, ); if (jump) { horizontalControllerGroup.jumpTo(target); } else { await horizontalControllerGroup.animateTo( target, curve: defaultCurve, duration: shortDuration, ); } } Future<void> scrollVerticallyToData(V data) async { await verticalControllerGroup.animateTo( // Subtract [2 * rowHeightWithPadding] to give the target scroll event top padding. (topYForData(data) - 2 * rowHeightWithPadding).clamp( FlameChart.minScrollOffset, verticalControllerGroup.position.maxScrollExtent, ), duration: shortDuration, curve: defaultCurve, ); } /// Scroll the flame chart horizontally to put [data] in view. /// /// If this is being called immediately after a zoom call, the call to /// this method should be placed inside of a postFrameCallback: /// `WidgetsBinding.instance.addPostFrameCallback((_) { ... });`. Future<void> scrollHorizontallyToData(V data) async { final offset = startXForData(data) + widget.startInset - widget.containerWidth * 0.1; await scrollToX(offset); } Future<void> zoomAndScrollToData({ @required int startMicros, @required int durationMicros, @required V data, bool scrollVertically = true, bool jumpZoom = false, }) async { await zoomToTimeRange( startMicros: startMicros, durationMicros: durationMicros, jump: jumpZoom, ); // Call these in a post frame callback so that the scroll controllers have // had time to update their scroll extents. Otherwise, we can hit a race // where are trying to scroll to an offset that is beyond what the scroll // controller thinks its max scroll extent is. WidgetsBinding.instance.addPostFrameCallback((_) async { await Future.wait([ scrollHorizontallyToData(data), if (scrollVertically) scrollVerticallyToData(data), ]); }); } Future<void> zoomToTimeRange({ @required int startMicros, @required int durationMicros, double targetWidth, bool jump = false, }) async { targetWidth ??= widget.containerWidth * 0.8; final startingWidth = durationMicros * startingPxPerMicro; final zoom = targetWidth / startingWidth; final mouseXForZoom = (startMicros - startTimeOffset + durationMicros / 2) * startingPxPerMicro + widget.startInset; await zoomTo(zoom, forceMouseX: mouseXForZoom, jump: jump); } bool isDataVerticallyInView(V data); bool isDataHorizontallyInView(V data); double topYForData(V data); double startXForData(V data); } class ScrollingFlameChartRow<V extends FlameChartDataMixin<V>> extends StatefulWidget { const ScrollingFlameChartRow({ @required this.linkedScrollControllerGroup, @required this.nodes, @required this.width, @required this.startInset, @required this.selectionNotifier, @required this.searchMatchesNotifier, @required this.activeSearchMatchNotifier, @required this.onTapUp, @required this.backgroundColor, @required this.zoom, }); final LinkedScrollControllerGroup linkedScrollControllerGroup; final List<FlameChartNode<V>> nodes; final double width; final double startInset; final ValueListenable<V> selectionNotifier; final ValueListenable<List<V>> searchMatchesNotifier; final ValueListenable<V> activeSearchMatchNotifier; final VoidCallback onTapUp; final Color backgroundColor; final double zoom; @override ScrollingFlameChartRowState<V> createState() => ScrollingFlameChartRowState<V>(); } class ScrollingFlameChartRowState<V extends FlameChartDataMixin<V>> extends State<ScrollingFlameChartRow> with AutoDisposeMixin { ScrollController scrollController; _ScrollingFlameChartRowExtentDelegate extentDelegate; /// Convenience getter for widget.nodes. List<FlameChartNode<V>> get nodes => widget.nodes; List<V> _nodeData; V selected; V hovered; @override void initState() { super.initState(); scrollController = widget.linkedScrollControllerGroup.addAndGet(); extentDelegate = _ScrollingFlameChartRowExtentDelegate( nodeIntervals: nodes.toPaddedZoomedIntervals( zoom: widget.zoom, chartStartInset: widget.startInset, chartWidth: widget.width, ), zoom: widget.zoom, chartStartInset: widget.startInset, chartWidth: widget.width, ); _initNodeDataList(); selected = widget.selectionNotifier.value; addAutoDisposeListener(widget.selectionNotifier, () { final containsPreviousSelected = _nodeData.contains(selected); final containsNewSelected = _nodeData.contains(widget.selectionNotifier.value); selected = widget.selectionNotifier.value; // We only want to rebuild the row if it contains the previous or new // selected node. if (containsPreviousSelected || containsNewSelected) { setState(() {}); } }); if (widget.searchMatchesNotifier != null) { addAutoDisposeListener(widget.searchMatchesNotifier); } if (widget.activeSearchMatchNotifier != null) { addAutoDisposeListener(widget.activeSearchMatchNotifier); } } @override void didUpdateWidget(ScrollingFlameChartRow oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.nodes != widget.nodes) { _initNodeDataList(); } if (oldWidget.nodes != widget.nodes || oldWidget.zoom != widget.zoom || oldWidget.width != widget.width || oldWidget.startInset != widget.startInset) { extentDelegate.recomputeWith( nodeIntervals: nodes.toPaddedZoomedIntervals( zoom: widget.zoom, chartStartInset: widget.startInset, chartWidth: widget.width, ), zoom: widget.zoom, chartStartInset: widget.startInset, chartWidth: widget.width, ); } _resetHovered(); } @override void dispose() { super.dispose(); scrollController.dispose(); _resetHovered(); } void _initNodeDataList() { _nodeData = nodes.map((node) => node.data).toList(); } @override Widget build(BuildContext context) { if (nodes.isEmpty) { return EmptyFlameChartRow( height: sectionSpacing, width: widget.width, backgroundColor: widget.backgroundColor, ); } // Having each row handle gestures and mouse events instead of each node // handling its own improves performance. return MouseRegion( onHover: _handleMouseHover, child: GestureDetector( behavior: HitTestBehavior.opaque, onTapUp: _handleTapUp, child: Container( height: rowHeightWithPadding, width: widget.width, color: widget.backgroundColor, // TODO(kenz): investigate if `addAutomaticKeepAlives: false` and // `addRepaintBoundaries: false` are needed here for perf improvement. child: ExtentDelegateListView( controller: scrollController, scrollDirection: Axis.horizontal, extentDelegate: extentDelegate, childrenDelegate: SliverChildBuilderDelegate( (context, index) => _buildFlameChartNode(index), childCount: nodes.length, addRepaintBoundaries: false, addAutomaticKeepAlives: false, ), ), ), ), ); } Widget _buildFlameChartNode(int index) { final node = nodes[index]; return Padding( padding: EdgeInsets.only( left: FlameChartUtils.leftPaddingForNode( index, nodes, chartZoom: widget.zoom, chartStartInset: widget.startInset, ), right: FlameChartUtils.rightPaddingForNode( index, nodes, chartZoom: widget.zoom, chartStartInset: widget.startInset, chartWidth: widget.width, ), bottom: rowPadding, ), child: node.buildWidget( selected: node.data == selected, hovered: node.data == hovered, searchMatch: node.data.isSearchMatch, activeSearchMatch: node.data.isActiveSearchMatch, zoom: FlameChartUtils.zoomForNode(node, widget.zoom), ), ); } void _handleMouseHover(PointerHoverEvent event) { final hoverNodeData = binarySearchForNode(event.localPosition.dx + scrollController.offset) ?.data; if (hoverNodeData != hovered) { setState(() { hovered = hoverNodeData; }); } } void _handleTapUp(TapUpDetails details) { final RenderBox referenceBox = context.findRenderObject(); final tapPosition = referenceBox.globalToLocal(details.globalPosition); final nodeToSelect = binarySearchForNode(tapPosition.dx + scrollController.offset); if (nodeToSelect != null) { nodeToSelect.onSelected(nodeToSelect.data); } widget.onTapUp(); } @visibleForTesting FlameChartNode<V> binarySearchForNode(double x) { int min = 0; int max = nodes.length; while (min < max) { final mid = min + ((max - min) >> 1); final node = nodes[mid]; final zoomedNodeRect = node.zoomedRect(widget.zoom, widget.startInset); if (x >= zoomedNodeRect.left && x <= zoomedNodeRect.right) { return node; } if (x < zoomedNodeRect.left) { max = mid; } if (x > zoomedNodeRect.right) { min = mid + 1; } } return null; } void _resetHovered() { hovered = null; } } extension NodeListExtension on List<FlameChartNode> { List<Range> toPaddedZoomedIntervals({ @required double zoom, @required double chartStartInset, @required double chartWidth, }) { return List<Range>.generate( length, (index) => FlameChartUtils.paddedZoomedInterval( index, this, chartZoom: zoom, chartStartInset: chartStartInset, chartWidth: chartWidth, ), ); } } class FlameChartUtils { static double leftPaddingForNode( int index, List<FlameChartNode> nodes, { @required double chartZoom, @required double chartStartInset, }) { final node = nodes[index]; double padding; if (index != 0) { padding = 0.0; } else if (!node.selectable) { padding = node.rect.left; } else { padding = (node.rect.left - chartStartInset) * zoomForNode(node, chartZoom) + chartStartInset; } // Floating point rounding error can result in slightly negative padding. return math.max(0.0, padding); } static double rightPaddingForNode( int index, List<FlameChartNode> nodes, { @required double chartZoom, @required double chartStartInset, @required double chartWidth, }) { // TODO(kenz): workaround for https://github.com/flutter/devtools/issues/2012. // This is a ridiculous amount of padding but it ensures that we don't hit // the issue described in the bug where the scroll extent is smaller than // where we want to `jumpTo`. Smaller values were experimented with but the // issue still persisted, so we are using a very large number. if (index == nodes.length - 1) return 1000000000000.0; final node = nodes[index]; final nextNode = index == nodes.length - 1 ? null : nodes[index + 1]; final nodeZoom = zoomForNode(node, chartZoom); final nextNodeZoom = zoomForNode(nextNode, chartZoom); // Node right with zoom and insets taken into consideration. final nodeRight = (node.rect.right - chartStartInset) * nodeZoom + chartStartInset; final padding = nextNode == null ? chartWidth - nodeRight : ((nextNode.rect.left - chartStartInset) * nextNodeZoom + chartStartInset) - nodeRight; // Floating point rounding error can result in slightly negative padding. return math.max(0.0, padding); } static double zoomForNode(FlameChartNode node, double chartZoom) { return node != null && node.selectable ? chartZoom : FlameChart.minZoomLevel; } static Range paddedZoomedInterval( int index, List<FlameChartNode> nodes, { @required double chartZoom, @required double chartStartInset, @required double chartWidth, }) { final node = nodes[index]; final zoomedRect = node.zoomedRect(chartZoom, chartStartInset); final leftPadding = leftPaddingForNode( index, nodes, chartZoom: chartZoom, chartStartInset: chartStartInset, ); final rightPadding = rightPaddingForNode( index, nodes, chartZoom: chartZoom, chartStartInset: chartStartInset, chartWidth: chartWidth, ); final left = zoomedRect.left - leftPadding; final width = leftPadding + zoomedRect.width + rightPadding; return Range(left, left + width); } } class FlameChartSection { FlameChartSection( this.index, { @required this.startRow, @required this.endRow, }); final int index; /// Start row (inclusive) for this section. final int startRow; /// End row (exclusive) for this section. final int endRow; } class FlameChartRow<T extends FlameChartDataMixin<T>> { FlameChartRow(this.index); final List<FlameChartNode<T>> nodes = []; final int index; /// Adds a node to [nodes] and assigns [this] to the nodes [row] property. /// /// If [index] is specified and in range of the list, [node] will be added at /// [index]. Otherwise, [node] will be added to the end of [nodes] void addNode(FlameChartNode<T> node, {int index}) { if (index != null && index >= 0 && index < nodes.length) { nodes.insert(index, node); } else { nodes.add(node); } node.row = this; } } mixin FlameChartDataMixin<T extends TreeNode<T>> on TreeDataSearchStateMixin<T> { String get tooltip; } // TODO(kenz): consider de-coupling this API from the dual background color // scheme. class FlameChartNode<T extends FlameChartDataMixin<T>> { FlameChartNode({ this.key, @required this.text, @required this.rect, @required this.backgroundColor, @required this.textColor, @required this.data, @required this.onSelected, this.selectable = true, this.sectionIndex, }); static const _darkTextColor = Colors.black; // We would like this value to be smaller, but zoom performance does not allow // for that. We should decrease this value if we can improve flame chart zoom // performance. static const _minWidthForText = 30.0; final Key key; final Rect rect; final String text; final Color backgroundColor; final Color textColor; final T data; final void Function(T) onSelected; final bool selectable; FlameChartRow row; int sectionIndex; Widget buildWidget({ @required bool selected, @required bool hovered, @required bool searchMatch, @required bool activeSearchMatch, @required double zoom, }) { // This math.max call prevents using a rect with negative width for // small events that have padding. // // See https://github.com/flutter/devtools/issues/1503 for details. final zoomedWidth = math.max(0.0, rect.width * zoom); // TODO(kenz): this is intended to improve performance but can probably be // improved. Perhaps we should still show a solid line and fade it out? if (zoomedWidth < 0.5) { return SizedBox(width: zoomedWidth); } selected = selectable ? selected : false; hovered = selectable ? hovered : false; final node = Container( key: hovered ? null : key, width: zoomedWidth, height: rect.height, padding: const EdgeInsets.symmetric(horizontal: 6.0), alignment: Alignment.centerLeft, color: _backgroundColor( selected: selected, searchMatch: searchMatch, activeSearchMatch: activeSearchMatch, ), child: zoomedWidth >= _minWidthForText ? Text( text, textAlign: TextAlign.left, overflow: TextOverflow.ellipsis, style: TextStyle( color: _textColor( selected: selected, searchMatch: searchMatch, activeSearchMatch: activeSearchMatch, ), ), ) : const SizedBox(), ); if (hovered || !selectable) { return Tooltip( key: key, message: data.tooltip, preferBelow: false, waitDuration: tooltipWait, child: node, ); } else { return node; } } Color _backgroundColor({ @required bool selected, @required bool searchMatch, @required bool activeSearchMatch, }) { if (selected) return defaultSelectionColor; if (activeSearchMatch) return activeSearchMatchColor; if (searchMatch) return searchMatchColor; return backgroundColor; } Color _textColor({ @required bool selected, @required bool searchMatch, @required bool activeSearchMatch, }) { if (selected || searchMatch || activeSearchMatch) return _darkTextColor; return textColor; } Rect zoomedRect(double zoom, double chartStartInset) { // If a node is not selectable (e.g. section labels "UI", "Raster", etc.), it // will not be zoomed, so return the original rect. if (!selectable) return rect; // These math.max calls prevent using a rect with negative width for // small events that have padding. // // See https://github.com/flutter/devtools/issues/1503 for details. final zoomedLeft = math.max(0.0, (rect.left - chartStartInset) * zoom + chartStartInset); final zoomedWidth = math.max(0.0, rect.width * zoom); return Rect.fromLTWH(zoomedLeft, rect.top, zoomedWidth, rect.height); } } mixin FlameChartColorMixin { Color nextUiColor(int row) { return uiColorPalette[row % uiColorPalette.length]; } Color nextRasterColor(int row) { return rasterColorPalette[row % rasterColorPalette.length]; } Color nextAsyncColor(int row) { return asyncColorPalette[row % asyncColorPalette.length]; } Color nextUnknownColor(int row) { return unknownColorPalette[row % unknownColorPalette.length]; } } /// [ExtentDelegate] implementation for the case where size and position is /// known for each list item. class _ScrollingFlameChartRowExtentDelegate extends ExtentDelegate { _ScrollingFlameChartRowExtentDelegate({ @required this.nodeIntervals, @required this.zoom, @required this.chartStartInset, @required this.chartWidth, }) { recompute(); } List<Range> nodeIntervals = []; double zoom; double chartStartInset; double chartWidth; void recomputeWith({ @required List<Range> nodeIntervals, @required double zoom, @required double chartStartInset, @required double chartWidth, }) { this.nodeIntervals = nodeIntervals; this.zoom = zoom; this.chartStartInset = chartStartInset; this.chartWidth = chartWidth; recompute(); } @override double itemExtent(int index) { if (index >= length) return 0; return nodeIntervals[index].size; } @override double layoutOffset(int index) { if (index <= 0) return 0.0; if (index >= length) return nodeIntervals.last.end; return nodeIntervals[index].begin; } @override int get length => nodeIntervals.length; @override int minChildIndexForScrollOffset(double scrollOffset) { final boundInterval = Range(scrollOffset, scrollOffset + 1); int index = lowerBound( nodeIntervals, boundInterval, compare: (Range a, Range b) => a.begin.compareTo(b.begin), ); if (index == 0) return 0; if (index >= nodeIntervals.length || (nodeIntervals[index].begin - scrollOffset).abs() > precisionErrorTolerance) { index--; } assert( nodeIntervals[index].begin <= scrollOffset + precisionErrorTolerance); return index; } @override int maxChildIndexForScrollOffset(double endScrollOffset) { final boundInterval = Range(endScrollOffset, endScrollOffset + 1); int index = lowerBound( nodeIntervals, boundInterval, compare: (Range a, Range b) => a.begin.compareTo(b.begin), ); if (index == 0) return 0; index--; assert(nodeIntervals[index].begin < endScrollOffset); return index; } } abstract class FlameChartPainter extends CustomPainter { FlameChartPainter({ @required this.zoom, @required this.constraints, @required this.verticalScrollOffset, @required this.horizontalScrollOffset, @required this.chartStartInset, @required this.colorScheme, }) : assert(colorScheme != null); final double zoom; final BoxConstraints constraints; final double verticalScrollOffset; final double horizontalScrollOffset; final double chartStartInset; /// The absolute coordinates of the flame chart's visible section. Rect get visibleRect { return Rect.fromLTWH( horizontalScrollOffset, verticalScrollOffset, constraints.maxWidth, constraints.maxHeight, ); } final ColorScheme colorScheme; @override bool shouldRepaint(CustomPainter oldDelegate) { if (oldDelegate is FlameChartPainter) { return verticalScrollOffset != oldDelegate.verticalScrollOffset || horizontalScrollOffset != oldDelegate.horizontalScrollOffset || constraints != oldDelegate.constraints || zoom != oldDelegate.zoom || chartStartInset != oldDelegate.chartStartInset || oldDelegate.colorScheme != colorScheme; } return true; } } class TimelineGridPainter extends FlameChartPainter { TimelineGridPainter({ @required double zoom, @required BoxConstraints constraints, @required double verticalScrollOffset, @required double horizontalScrollOffset, @required double chartStartInset, @required this.chartEndInset, @required this.flameChartWidth, @required this.duration, @required ColorScheme colorScheme, }) : super( zoom: zoom, constraints: constraints, verticalScrollOffset: verticalScrollOffset, horizontalScrollOffset: horizontalScrollOffset, chartStartInset: chartStartInset, colorScheme: colorScheme, ); static const baseGridIntervalPx = 150.0; static const timestampOffset = 6.0; final double chartEndInset; final double flameChartWidth; final Duration duration; @override void paint(Canvas canvas, Size size) { // Paint background for the section that will contain the timestamps. This // section will appear sticky to the top of the viewport. final visible = visibleRect; canvas.drawRect( Rect.fromLTWH( 0.0, 0.0, constraints.maxWidth, math.min(constraints.maxHeight, rowHeight), ), Paint()..color = colorScheme.defaultBackgroundColor, ); // Paint the timeline grid lines and corresponding timestamps in the flame // chart. final intervalWidth = _intervalWidth(); final microsPerInterval = _microsPerInterval(intervalWidth); int timestampMicros = _startingTimestamp(intervalWidth, microsPerInterval); double lineX; if (visible.left <= chartStartInset) { lineX = chartStartInset - visible.left; } else { lineX = intervalWidth - ((visible.left - chartStartInset) % intervalWidth); } while (lineX < constraints.maxWidth) { _paintTimestamp(canvas, timestampMicros, intervalWidth, lineX); _paintGridLine(canvas, lineX); lineX += intervalWidth; timestampMicros += microsPerInterval; } } void _paintTimestamp( Canvas canvas, int timestampMicros, double intervalWidth, double lineX, ) { final timestampText = msText( Duration(microseconds: timestampMicros), fractionDigits: timestampMicros == 0 ? 1 : 3, ); final textPainter = TextPainter( text: TextSpan( text: timestampText, style: TextStyle(color: colorScheme.chartTextColor), ), textAlign: TextAlign.right, textDirection: TextDirection.ltr, )..layout(maxWidth: intervalWidth); // TODO(kenz): figure out a way for the timestamps to scroll out of view // smoothly instead of dropping off. Consider using a horizontal list view // of text widgets for the timestamps instead of painting them. final xOffset = lineX - textPainter.width - timestampOffset; if (xOffset > 0) { textPainter.paint(canvas, Offset(xOffset, 5.0)); } } void _paintGridLine(Canvas canvas, double lineX) { canvas.drawLine( Offset(lineX, 0.0), Offset(lineX, constraints.maxHeight), Paint()..color = colorScheme.chartAccentColor, ); } double _intervalWidth() { final log2ZoomLevel = log2(zoom); final gridZoomFactor = math.pow(2, log2ZoomLevel); final gridIntervalPx = baseGridIntervalPx / gridZoomFactor; /// The physical pixel width of the grid interval at [zoom]. return gridIntervalPx * zoom; } int _microsPerInterval(double intervalWidth) { final contentWidth = flameChartWidth - chartStartInset - chartEndInset; final numCompleteIntervals = contentWidth ~/ intervalWidth; final remainderContentWidth = contentWidth - (numCompleteIntervals * intervalWidth); final remainderMicros = remainderContentWidth * duration.inMicroseconds / contentWidth; return ((duration.inMicroseconds - remainderMicros) / numCompleteIntervals) .round(); } int _startingTimestamp(double intervalWidth, int microsPerInterval) { final startingIntervalIndex = horizontalScrollOffset < chartStartInset ? 0 : (horizontalScrollOffset - chartStartInset) ~/ intervalWidth + 1; return startingIntervalIndex * microsPerInterval; } @override bool shouldRepaint(CustomPainter oldDelegate) => this != oldDelegate; @override bool operator ==(other) { return zoom == other.zoom && constraints == other.constraints && flameChartWidth == other.flameChartWidth && horizontalScrollOffset == other.horizontalScrollOffset && duration == other.duration && colorScheme == other.colorScheme; } @override int get hashCode => hashValues( zoom, constraints, flameChartWidth, horizontalScrollOffset, duration, colorScheme, ); } class FlameChartHelpButton extends StatelessWidget { @override Widget build(BuildContext context) { return HelpButton( onPressed: () => showDialog( context: context, builder: (context) => _FlameChartHelpDialog(), ), ); } } class _FlameChartHelpDialog extends StatelessWidget { /// A fixed width for the first column in the help dialog to ensure that the /// subsections are aligned. static const firstColumnWidth = 190.0; @override Widget build(BuildContext context) { final theme = Theme.of(context); return DevToolsDialog( title: dialogTitleText(theme, 'Flame Chart Help'), includeDivider: false, content: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ ...dialogSubHeader(theme, 'Navigation'), _buildNavigationInstructions(theme), const SizedBox(height: denseSpacing), ...dialogSubHeader(theme, 'Zoom'), _buildZoomInstructions(theme), ], ), actions: [ DialogCloseButton(), ], ); } Widget _buildNavigationInstructions(ThemeData theme) { return Row( children: [ SizedBox( width: firstColumnWidth, child: Column( crossAxisAlignment: CrossAxisAlignment.end, children: [ Text( 'click + drag • ', style: theme.fixedFontStyle, ), Text( 'click + fling • ', style: theme.fixedFontStyle, ), Text( 'alt/option + scroll • ', style: theme.fixedFontStyle, ), Text( 'scroll left / right • ', style: theme.fixedFontStyle, ), Text( 'a / d • ', style: theme.fixedFontStyle, ), ], ), ), Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'Pan chart up / down / left / right', style: theme.subtleTextStyle, ), Text( 'Fling chart up / down / left / right', style: theme.subtleTextStyle, ), Text( 'Pan chart up / down', style: theme.subtleTextStyle, ), Text( 'Pan chart left / right', style: theme.subtleTextStyle, ), Text( 'Pan chart left / right', style: theme.subtleTextStyle, ), ], ), ], ); } Widget _buildZoomInstructions(ThemeData theme) { return Row( children: [ SizedBox( width: firstColumnWidth, child: Column( crossAxisAlignment: CrossAxisAlignment.end, children: [ Text( 'scroll up / down • ', style: theme.fixedFontStyle, ), Text( 'w / s • ', style: theme.fixedFontStyle, ), ], ), ), Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'zoom in / out', style: theme.subtleTextStyle, ), Text( 'zoom in / out', style: theme.subtleTextStyle, ), ], ), ], ); } } class EmptyFlameChartRow extends StatelessWidget { const EmptyFlameChartRow({ @required this.height, @required this.width, @required this.backgroundColor, }); final double height; final double width; final Color backgroundColor; @override Widget build(BuildContext context) { return Container( height: height, width: width, color: backgroundColor, ); } }
devtools/packages/devtools_app/lib/src/charts/flame_chart.dart/0
{'file_path': 'devtools/packages/devtools_app/lib/src/charts/flame_chart.dart', 'repo_id': 'devtools', 'token_count': 18164}
// 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. /// Return the url the application is launched from. Future<String> initializePlatform() { throw UnimplementedError( 'Attempting to initialize framework for unrecognized platform'); }
devtools/packages/devtools_app/lib/src/config_specific/framework_initialize/_framework_initialize_stub.dart/0
{'file_path': 'devtools/packages/devtools_app/lib/src/config_specific/framework_initialize/_framework_initialize_stub.dart', 'repo_id': 'devtools', 'token_count': 90}
// 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 'logger.dart'; /// Catch and print errors from the given future. These errors are part of /// normal operation for an app, and don't need to be reported to analytics /// (i.e., they're not DevTools crashes). Future<T> allowedError<T>(Future<T> future, {bool logError = true}) { return future.catchError((Object error) { if (logError) { final errorLines = error.toString().split('\n'); log('[${error.runtimeType}] ${errorLines.first}', LogLevel.error); log(errorLines.skip(1).join('\n'), LogLevel.error); log(''); } }); }
devtools/packages/devtools_app/lib/src/config_specific/logger/allowed_error_default.dart/0
{'file_path': 'devtools/packages/devtools_app/lib/src/config_specific/logger/allowed_error_default.dart', 'repo_id': 'devtools', 'token_count': 241}
// 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'; import '../../utils.dart'; Map<String, String> loadQueryParams() { return devToolsQueryParams(window.location.toString()); }
devtools/packages/devtools_app/lib/src/config_specific/url/_url_web.dart/0
{'file_path': 'devtools/packages/devtools_app/lib/src/config_specific/url/_url_web.dart', 'repo_id': 'devtools', 'token_count': 93}
// 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:math'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:vm_service/vm_service.dart'; import '../auto_dispose_mixin.dart'; import '../notifications.dart'; import '../theme.dart'; import '../ui/search.dart'; import '../utils.dart'; import 'debugger_controller.dart'; class ExpressionEvalField extends StatefulWidget { const ExpressionEvalField({ this.controller, }); final DebuggerController controller; @override _ExpressionEvalFieldState createState() => _ExpressionEvalFieldState(); } class _ExpressionEvalFieldState extends State<ExpressionEvalField> with SearchFieldMixin, AutoDisposeMixin { AutoCompleteController _autoCompleteController; int historyPosition = -1; final evalTextFieldKey = GlobalKey(debugLabel: 'evalTextFieldKey'); @override void initState() { super.initState(); _autoCompleteController = AutoCompleteController(); addAutoDisposeListener(_autoCompleteController.searchNotifier, () { _autoCompleteController.handleAutoCompleteOverlay( context: context, searchFieldKey: evalTextFieldKey, onTap: _onSelection, bottom: false, maxWidth: false, ); }); addAutoDisposeListener( _autoCompleteController.selectTheSearchNotifier, _handleSearch); addAutoDisposeListener( _autoCompleteController.searchNotifier, _handleSearch); } void _handleSearch() async { final searchingValue = _autoCompleteController.search; final isField = searchingValue.endsWith('.'); if (searchingValue.isNotEmpty) { if (_autoCompleteController.selectTheSearch) { _autoCompleteController.resetSearch(); return; } // We avoid clearing the list of possible matches here even though the // current matches may be out of date as clearing results in flicker // as Flutter will render a frame before the new matches are available. // Find word in TextField to try and match (word breaks). final textFieldEditingValue = searchTextFieldController.value; final selection = textFieldEditingValue.selection; final parts = AutoCompleteSearchControllerMixin.activeEdtingParts( searchingValue, selection, handleFields: isField, ); // Only show pop-up if there's a real variable name or field. if (parts.activeWord.isEmpty && !parts.isField) { _autoCompleteController.clearSearchAutoComplete(); return; } final matches = await autoCompleteResultsFor(parts, widget.controller); if (matches.length == 1 && matches.first == parts.activeWord) { // It is not useful to show a single autocomplete that is exactly what // the already typed. _autoCompleteController.clearSearchAutoComplete(); } else { _autoCompleteController.searchAutoComplete.value = matches.sublist( 0, min(defaultTopMatchesLimit, matches.length), ); _autoCompleteController.currentDefaultIndex = 0; } } else { _autoCompleteController.closeAutoCompleteOverlay(); } } @override Widget build(BuildContext context) { final theme = Theme.of(context); return Container( decoration: BoxDecoration( border: Border( top: BorderSide(color: theme.focusColor), ), ), padding: const EdgeInsets.all(8.0), child: Row( children: [ const Text('>'), const SizedBox(width: 8.0), Expanded( child: Focus( onKey: (_, RawKeyEvent event) { if (event.isKeyPressed(LogicalKeyboardKey.arrowUp)) { _historyNavUp(); return KeyEventResult.handled; } else if (event.isKeyPressed(LogicalKeyboardKey.arrowDown)) { _historyNavDown(); return KeyEventResult.handled; } else if (event.isKeyPressed(LogicalKeyboardKey.enter)) { _handleExpressionEval(); return KeyEventResult.handled; } return KeyEventResult.ignored; }, child: buildAutoCompleteSearchField( controller: _autoCompleteController, searchFieldKey: evalTextFieldKey, searchFieldEnabled: true, shouldRequestFocus: false, supportClearField: true, onSelection: _onSelection, tracking: true, decoration: const InputDecoration( contentPadding: EdgeInsets.all(denseSpacing), border: OutlineInputBorder(), focusedBorder: OutlineInputBorder(borderSide: BorderSide.none), enabledBorder: OutlineInputBorder(borderSide: BorderSide.none), labelText: 'Eval', ), ), ), ), ], ), ); } void _onSelection(String word) { setState(() { _replaceActiveWord(word); _autoCompleteController.selectTheSearch = false; _autoCompleteController.closeAutoCompleteOverlay(); }); } /// Replace the current activeWord (partial name) with the selected item from /// the auto-complete list. void _replaceActiveWord(String word) { final textFieldEditingValue = searchTextFieldController.value; final editingValue = textFieldEditingValue.text; final selection = textFieldEditingValue.selection; final parts = AutoCompleteSearchControllerMixin.activeEdtingParts( editingValue, selection, handleFields: _autoCompleteController.search.endsWith('.'), ); // Add the newly selected auto-complete value. final newValue = '${parts.leftSide}$word${parts.rightSide}'; // Update the value and caret position of the auto-completed word. searchTextFieldController.value = TextEditingValue( text: newValue, selection: TextSelection.fromPosition( // Update the caret position to just beyond the newly picked // auto-complete item. TextPosition(offset: parts.leftSide.length + word.length), ), ); } void _handleExpressionEval() async { final expressionText = searchTextFieldController.value.text.trim(); updateSearchField(_autoCompleteController, '', 0); clearSearchField(_autoCompleteController, force: true); if (expressionText.isEmpty) return; // Don't try to eval if we're not paused. if (!widget.controller.isPaused.value) { Notifications.of(context) .push('Application must be paused to support expression evaluation.'); return; } widget.controller.appendStdio('> $expressionText\n'); setState(() { historyPosition = -1; widget.controller.evalHistory.pushEvalHistory(expressionText); }); try { // Response is either a ErrorRef, InstanceRef, or Sentinel. final response = await widget.controller.evalAtCurrentFrame(expressionText); // Display the response to the user. if (response is InstanceRef) { _emitRefToConsole(response); } else { var value = response.toString(); if (response is ErrorRef) { value = response.message; } else if (response is Sentinel) { value = response.valueAsString; } _emitToConsole(value); } } catch (e) { // Display the error to the user. _emitToConsole('$e'); } } void _emitToConsole(String text) { widget.controller.appendStdio(' ${text.replaceAll('\n', '\n ')}\n'); } void _emitRefToConsole(InstanceRef ref) { widget.controller.appendInstanceRef(ref); } @override void dispose() { _autoCompleteController.dispose(); super.dispose(); } void _historyNavUp() { final evalHistory = widget.controller.evalHistory; if (!evalHistory.canNavigateUp) { return; } setState(() { evalHistory.navigateUp(); final text = evalHistory.currentText; searchTextFieldController.value = TextEditingValue( text: text, selection: TextSelection.collapsed(offset: text.length), ); }); } void _historyNavDown() { final evalHistory = widget.controller.evalHistory; if (!evalHistory.canNavigateDown) { return; } setState(() { evalHistory.navigateDown(); final text = evalHistory.currentText ?? ''; searchTextFieldController.value = TextEditingValue( text: text, selection: TextSelection.collapsed(offset: text.length), ); }); } } Future<List<String>> autoCompleteResultsFor( EditingParts parts, DebuggerController controller, ) async { final result = <String>{}; if (!parts.isField) { final variables = controller.variables.value; result.addAll(variables.map((variable) => variable.boundVar.name)); final thisVariable = variables.firstWhere( (variable) => variable.boundVar.name == 'this', orElse: () => null, ); if (thisVariable != null) { // If a variable named `this` is in scope, we should provide autocompletes // for all static and instance members of that class as they are in scope // in Dart. For example, if you evaluate `foo()` that will be equivalent // to `this.foo()` if foo is an instance member and `ThisClass.foo() if // foo is a static member. final thisValue = thisVariable.boundVar.value; if (thisValue is InstanceRef) { await _addAllInstanceMembersToAutocompleteList( result, thisValue, controller, ); result.addAll(await _autoCompleteMembersFor( thisValue.classRef, controller, staticContext: true, )); } } final frame = controller.frameForEval; if (frame != null) { final function = frame.function; if (function != null) { final libraryRef = await controller.findOwnerLibrary(function); if (libraryRef != null) { result.addAll(await libraryMemberAndImportsAutocompletes( libraryRef, controller)); } } } } else { var left = parts.leftSide.split(' ').last; // Removing trailing `.`. left = left.substring(0, left.length - 1); try { final response = await controller.evalAtCurrentFrame(left); if (response is InstanceRef) { if (response.typeClass != null) { // Assume we want static members for a type class not members of the // Type object. This is reasonable as Type objects are rarely useful // in Dart and we will end up with accidental Type objects if the user // writes `SomeClass.` in the evaluate window. result.addAll(await _autoCompleteMembersFor( response.typeClass, controller, staticContext: true, )); } else { await _addAllInstanceMembersToAutocompleteList( result, response, controller, ); } } } catch (_) {} } return result.where((name) => name.startsWith(parts.activeWord)).toList(); } // Due to https://github.com/dart-lang/sdk/issues/46221 // we cannot tell what the show clause for an export was so it is unsafe to // surface exports as if they were library members as there tend to be // significant false positives for libraries such as Flutter where all of // dart:ui shows up as in scope from flutter:foundation when it should not be. bool debugIncludeExports = true; Future<Set<String>> libraryMemberAndImportsAutocompletes( LibraryRef libraryRef, DebuggerController controller, ) { return controller.libraryMemberAndImportsAutocompleteCache.putIfAbsent( libraryRef, () => _libraryMemberAndImportsAutocompletes(libraryRef, controller), ); } Future<Set<String>> _libraryMemberAndImportsAutocompletes( LibraryRef libraryRef, DebuggerController controller, ) async { final result = <String>{}; try { final futures = <Future<Set<String>>>[]; futures.add(libraryMemberAutocompletes( controller, libraryRef, includePrivates: true, )); final Library library = await controller.getObject(libraryRef); for (var dependency in library.dependencies) { if (dependency.prefix?.isNotEmpty ?? false) { // We won't give a list of autocompletes once you enter a prefix // but at least we do include the prefix in the autocompletes list. result.add(dependency.prefix); } else { futures.add(libraryMemberAutocompletes( controller, dependency.target, includePrivates: false, )); } } (await Future.wait(futures)).forEach(result.addAll); } catch (_) { // Silently skip library completions if there is a failure. } return result; } Future<Set<String>> libraryMemberAutocompletes( DebuggerController controller, LibraryRef libraryRef, { @required bool includePrivates, }) async { var result = await controller.libraryMemberAutocompleteCache.putIfAbsent( libraryRef, () => _libraryMemberAutocompletes(controller, libraryRef), ); if (!includePrivates) { result = result.where((name) => !isPrivate(name)).toSet(); } return result; } Future<Set<String>> _libraryMemberAutocompletes( DebuggerController controller, LibraryRef libraryRef, ) async { final result = <String>{}; final Library library = await controller.getObject(libraryRef); result.addAll(library.variables.map((field) => field.name)); result.addAll(library.functions // The VM shows setters as `<member>=`. .map((funcRef) => funcRef.name.replaceAll('=', ''))); // Autocomplete class names as well result.addAll(library.classes.map((clazz) => clazz.name)); if (debugIncludeExports) { final futures = <Future<Set<String>>>[]; for (var dependency in library.dependencies) { if (!dependency.isImport) { if (dependency.prefix?.isNotEmpty ?? false) { result.add(dependency.prefix); } else { futures.add(libraryMemberAutocompletes( controller, dependency.target, includePrivates: false, )); } } } if (futures.isNotEmpty) { (await Future.wait(futures)).forEach(result.addAll); } } return result; } Future<void> _addAllInstanceMembersToAutocompleteList( Set<String> result, InstanceRef response, DebuggerController controller, ) async { final Instance instance = await controller.getObject(response); result.addAll( await _autoCompleteMembersFor( instance.classRef, controller, staticContext: false, ), ); // TODO(grouma) - This shouldn't be necessary but package:dwds does // not properly provide superclass information. final clazz = await controller.classFor(instance.classRef); result.addAll(instance.fields .where((field) => !field.decl.isStatic) .map((field) => field.decl.name) .where((member) => _isAccessible(member, clazz, controller))); } Future<Set<String>> _autoCompleteMembersFor( ClassRef classRef, DebuggerController controller, { @required bool staticContext, }) async { if (classRef == null) { return {}; } // TODO(jacobr): consider using controller.autocompleteCache to cache the list // of autocomplete candidates for each class. The main challenge with caching // is _isAccessible depends on the current source location so makes caching // difficult. final result = <String>{}; final clazz = await controller.classFor(classRef); if (clazz != null) { result.addAll(clazz.fields .where((f) => f.isStatic == staticContext) .map((field) => field.name)); for (var funcRef in clazz.functions) { if (_validFunction(funcRef, clazz, staticContext)) { final isConstructor = _isConstructor(funcRef, clazz); // The VM shows setters as `<member>=`. var name = funcRef.name.replaceAll('=', ''); if (isConstructor) { assert(name.startsWith(clazz.name)); if (name.length <= clazz.name.length + 1) continue; name = name.substring(clazz.name.length + 1); } result.add(name); } } if (!staticContext) { result.addAll(await _autoCompleteMembersFor( clazz.superClass, controller, staticContext: staticContext, )); } result.removeWhere((member) => !_isAccessible(member, clazz, controller)); } return result; } bool _validFunction(FuncRef funcRef, Class clazz, bool staticContext) { // TODO(jacobr): we should include named constructors in static contexts. return ((_isConstructor(funcRef, clazz) || funcRef.isStatic) == staticContext) && !_isOperator(funcRef); } bool _isOperator(FuncRef funcRef) => const { '==', '+', '-', '*', '/', '&', '~', '|', '>', '<', '>=', '<=', '>>', '<<', '>>>', '^', '%', '~/', 'unary-', }.contains(funcRef.name); bool _isConstructor(FuncRef funcRef, Class clazz) => funcRef.name == clazz.name || funcRef.name.startsWith('${clazz.name}.'); bool _isAccessible(String member, Class clazz, DebuggerController controller) { final frame = controller.frameForEval; final currentScript = frame.location.script; return !isPrivate(member) || currentScript.id == clazz?.location?.script?.id; }
devtools/packages/devtools_app/lib/src/debugger/evaluate.dart/0
{'file_path': 'devtools/packages/devtools_app/lib/src/debugger/evaluate.dart', 'repo_id': 'devtools', 'token_count': 6865}
// 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 'split.dart'; class FlexSplitColumn extends StatelessWidget { FlexSplitColumn({ Key key, @required this.totalHeight, @required this.headers, @required List<Widget> children, @required List<double> initialFractions, List<double> minSizes, }) : assert(children != null && children.length >= 2), assert(initialFractions != null && initialFractions.length >= 2), assert(children.length == initialFractions.length), _children = buildChildrenWithFirstHeader(children, headers), _initialFractions = modifyInitialFractionsToIncludeFirstHeader( initialFractions, headers, totalHeight, ), _minSizes = modifyMinSizesToIncludeFirstHeader(minSizes, headers), super(key: key) { if (minSizes != null) { assert(minSizes.length == children.length); } } /// The headers that will be laid out above each corresponding child in /// [children]. /// /// All headers but the first will be passed into [Split.splitters] when /// creating the [Split] widget in `build`. Instead of being passed into /// [Split.splitters], it will be combined with the first child in [children] /// to create the first child we will pass into [Split.children]. /// /// We do this because the first header will not actually be a splitter as /// there is not any content above it for it to split. /// /// We modify other values [_children], [_initialFractions], and [_minSizes] /// from [children], [initialFractions], and [minSizes], respectively, to /// account for the first header. We do this adjustment here so that the /// creators of [FlexSplitColumn] can be unaware of the under-the-hood /// calculations necessary to achieve the UI requirements specified by /// [initialFractions] and [minSizes]. final List<PreferredSizeWidget> headers; /// The children that will be laid out below each corresponding header in /// [headers]. /// /// All [children] except the first will be passed into [Split.children] /// unmodified. We need to modify the first child from [children] to account /// for the first header (see above). final List<Widget> _children; /// The fraction of the layout to allocate to each child in [children]. /// /// We need to modify the values given by [initialFractions] to account for /// the first header (see above). final List<double> _initialFractions; /// The minimum size each child is allowed to be. /// /// We need to modify the values given by [minSizes] to account for the first /// header (see above). final List<double> _minSizes; /// The total height of the column, including all [headers] and [children]. final double totalHeight; @visibleForTesting static List<Widget> buildChildrenWithFirstHeader( List<Widget> children, List<PreferredSizeWidget> headers, ) { return [ Column( children: [ headers[0], Expanded(child: children[0]), ], ), ...children.sublist(1), ]; } @visibleForTesting static List<double> modifyInitialFractionsToIncludeFirstHeader( List<double> initialFractions, List<PreferredSizeWidget> headers, double totalHeight, ) { var totalHeaderHeight = 0.0; for (var header in headers) { totalHeaderHeight += header.preferredSize.height; } final intendedContentHeight = totalHeight - totalHeaderHeight; final intendedChildHeights = List<double>.generate(initialFractions.length, (i) => intendedContentHeight * initialFractions[i]); final trueContentHeight = intendedContentHeight + headers[0].preferredSize.height; return List<double>.generate(initialFractions.length, (i) { if (i == 0) { return (intendedChildHeights[i] + headers[0].preferredSize.height) / trueContentHeight; } return intendedChildHeights[i] / trueContentHeight; }); } @visibleForTesting static List<double> modifyMinSizesToIncludeFirstHeader( List<double> minSizes, List<PreferredSizeWidget> headers, ) { return [ minSizes[0] + headers[0].preferredSize.height, ...minSizes.sublist(1), ]; } @override Widget build(BuildContext context) { return Split( axis: Axis.vertical, children: _children, initialFractions: _initialFractions, minSizes: _minSizes, splitters: headers.sublist(1), ); } }
devtools/packages/devtools_app/lib/src/flex_split_column.dart/0
{'file_path': 'devtools/packages/devtools_app/lib/src/flex_split_column.dart', 'repo_id': 'devtools', 'token_count': 1533}
// 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:flutter/material.dart'; import '../ui/icons.dart'; import '../utils.dart'; import 'diagnostics_node.dart'; import 'inspector_controller.dart'; import 'inspector_text_styles.dart' as inspector_text_styles; import 'inspector_tree.dart'; final ColorIconMaker _colorIconMaker = ColorIconMaker(); final CustomIconMaker _customIconMaker = CustomIconMaker(); final CustomIcon defaultIcon = _customIconMaker.fromInfo('Default'); const bool _showRenderObjectPropertiesAsLinks = false; /// Presents the content of a single [RemoteDiagnosticsNode]. /// /// Use this class any time you want to display a single [RemoteDiagnosticsNode] /// in debugging UI whether you are displaying the node in the [InspectorTree] /// in console output, or a debugger. /// See also: /// * [InspectorTree], which uses this class to display each node in the in /// inspector tree. class DiagnosticsNodeDescription extends StatelessWidget { const DiagnosticsNodeDescription( this.diagnostic, { this.isSelected, this.errorText, }); final RemoteDiagnosticsNode diagnostic; final bool isSelected; final String errorText; Widget _paddedIcon(Widget icon) { return Padding( padding: const EdgeInsets.only(right: iconPadding), child: icon, ); } Iterable<TextSpan> _buildDescriptionTextSpans( String description, TextStyle textStyle, ColorScheme colorScheme, ) sync* { if (diagnostic.isDiagnosticableValue) { final match = treeNodePrimaryDescriptionPattern.firstMatch(description); if (match != null) { yield TextSpan(text: match.group(1), style: textStyle); if (match.group(2).isNotEmpty) { yield TextSpan( text: match.group(2), style: inspector_text_styles.unimportant(colorScheme), ); } return; } } else if (diagnostic.type == 'ErrorDescription') { final match = assertionThrownBuildingError.firstMatch(description); if (match != null) { yield TextSpan(text: match.group(1), style: textStyle); yield TextSpan(text: match.group(3), style: textStyle); return; } } if (description?.isNotEmpty == true) { yield TextSpan(text: description, style: textStyle); } } Widget buildDescription( String description, TextStyle textStyle, ColorScheme colorScheme, { bool isProperty, }) { return RichText( overflow: TextOverflow.ellipsis, text: TextSpan( children: _buildDescriptionTextSpans( description, textStyle, colorScheme, ).toList(), ), ); } @override Widget build(BuildContext context) { if (diagnostic == null) { return const SizedBox(); } final colorScheme = Theme.of(context).colorScheme; final icon = diagnostic.icon; final children = <Widget>[]; if (icon != null) { children.add(_paddedIcon(icon)); } final String name = diagnostic.name; TextStyle textStyle = DefaultTextStyle.of(context) .style .merge(textStyleForLevel(diagnostic.level, colorScheme)); if (diagnostic.isProperty) { // Display of inline properties. final String propertyType = diagnostic.propertyType; final Map<String, Object> properties = diagnostic.valuePropertiesJson; if (name?.isNotEmpty == true && diagnostic.showName) { children.add(Text('$name${diagnostic.separator} ', style: textStyle)); } if (diagnostic.isCreatedByLocalProject) { textStyle = textStyle.merge(inspector_text_styles.regularBold(colorScheme)); } String description = diagnostic.description; if (propertyType != null && properties != null) { switch (propertyType) { case 'Color': { final int alpha = JsonUtils.getIntMember(properties, 'alpha'); final int red = JsonUtils.getIntMember(properties, 'red'); final int green = JsonUtils.getIntMember(properties, 'green'); final int blue = JsonUtils.getIntMember(properties, 'blue'); String radix(int chan) => chan.toRadixString(16).padLeft(2, '0'); if (alpha == 255) { description = '#${radix(red)}${radix(green)}${radix(blue)}'; } else { description = '#${radix(alpha)}${radix(red)}${radix(green)}${radix(blue)}'; } final Color color = Color.fromARGB(alpha, red, green, blue); children.add(_paddedIcon(_colorIconMaker.getCustomIcon(color))); break; } case 'IconData': { final int codePoint = JsonUtils.getIntMember(properties, 'codePoint'); if (codePoint > 0) { final icon = FlutterMaterialIcons.getIconForCodePoint( codePoint, colorScheme, ); if (icon != null) { children.add(_paddedIcon(icon)); } } break; } } } if (_showRenderObjectPropertiesAsLinks && propertyType == 'RenderObject') { textStyle = textStyle..merge(inspector_text_styles.link(colorScheme)); } // TODO(jacobr): custom display for units, iterables, and padding. children.add(Flexible( child: buildDescription( description, textStyle, colorScheme, isProperty: true, ), )); if (diagnostic.level == DiagnosticLevel.fine && diagnostic.hasDefaultValue) { children.add(const Text(' ')); children.add(_paddedIcon(defaultIcon)); } } else { // Non property, regular node case. if (name?.isNotEmpty == true && diagnostic.showName && name != 'child') { if (name.startsWith('child ')) { children.add(Text( name, style: inspector_text_styles.unimportant(colorScheme), )); } else { children.add(Text(name, style: textStyle)); } if (diagnostic.showSeparator) { children.add(Text( diagnostic.separator, style: inspector_text_styles.unimportant(colorScheme), )); if (diagnostic.separator != ' ' && diagnostic.description.isNotEmpty) { children.add(Text( ' ', style: inspector_text_styles.unimportant(colorScheme), )); } } } if (!diagnostic.isSummaryTree && diagnostic.isCreatedByLocalProject) { textStyle = textStyle.merge(inspector_text_styles.regularBold(colorScheme)); } var diagnosticDescription = buildDescription( diagnostic.description, textStyle, colorScheme, isProperty: false, ); if (errorText != null) { // TODO(dantup): Find if there's a way to achieve this without // the nested row. diagnosticDescription = Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ diagnosticDescription, _buildErrorText(colorScheme), ], ); } children.add(Expanded(child: diagnosticDescription)); } return Row(mainAxisSize: MainAxisSize.min, children: children); } Flexible _buildErrorText(ColorScheme colorScheme) { return Flexible( child: RichText( textAlign: TextAlign.right, overflow: TextOverflow.ellipsis, text: TextSpan( text: errorText, // When the node is selected, the background will be an error // color so don't render the text the same color. style: isSelected ? inspector_text_styles.regular : inspector_text_styles.error(colorScheme), ), ), ); } }
devtools/packages/devtools_app/lib/src/inspector/diagnostics.dart/0
{'file_path': 'devtools/packages/devtools_app/lib/src/inspector/diagnostics.dart', 'repo_id': 'devtools', 'token_count': 3497}
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:math'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import '../../../theme.dart'; const defaultArrowColor = Colors.white; const defaultArrowStrokeWidth = 2.0; const defaultDistanceToArrow = 4.0; enum ArrowType { up, left, right, down, } Axis axis(ArrowType type) => (type == ArrowType.up || type == ArrowType.down) ? Axis.vertical : Axis.horizontal; /// Widget that draws a bidirectional arrow around another widget. /// /// This widget is typically used to help draw diagrams. @immutable class ArrowWrapper extends StatelessWidget { ArrowWrapper.unidirectional({ Key key, this.child, @required ArrowType type, this.arrowColor = defaultArrowColor, this.arrowHeadSize = defaultIconSize, this.arrowStrokeWidth = defaultArrowStrokeWidth, this.childMarginFromArrow = defaultDistanceToArrow, }) : assert(type != null), assert(arrowColor != null), assert(arrowHeadSize != null && arrowHeadSize > 0.0), assert(arrowStrokeWidth != null && arrowHeadSize > 0.0), assert(childMarginFromArrow != null && childMarginFromArrow > 0.0), direction = axis(type), isBidirectional = false, startArrowType = type, endArrowType = type, super(key: key); const ArrowWrapper.bidirectional({ Key key, this.child, @required this.direction, this.arrowColor = defaultArrowColor, this.arrowHeadSize = defaultIconSize, this.arrowStrokeWidth = defaultArrowStrokeWidth, this.childMarginFromArrow = defaultDistanceToArrow, }) : assert(direction != null), assert(arrowColor != null), assert(arrowHeadSize != null && arrowHeadSize >= 0.0), assert(arrowStrokeWidth != null && arrowHeadSize >= 0.0), assert(childMarginFromArrow != null && childMarginFromArrow >= 0.0), isBidirectional = true, startArrowType = direction == Axis.horizontal ? ArrowType.left : ArrowType.up, endArrowType = direction == Axis.horizontal ? ArrowType.right : ArrowType.down, super(key: key); final Color arrowColor; final double arrowHeadSize; final double arrowStrokeWidth; final Widget child; final Axis direction; final double childMarginFromArrow; final bool isBidirectional; final ArrowType startArrowType; final ArrowType endArrowType; double get verticalMarginFromArrow { if (child == null || direction == Axis.horizontal) return 0.0; return childMarginFromArrow; } double get horizontalMarginFromArrow { if (child == null || direction == Axis.vertical) return 0.0; return childMarginFromArrow; } @override Widget build(BuildContext context) { return Flex( direction: direction, children: <Widget>[ Expanded( child: Container( margin: EdgeInsets.only( bottom: verticalMarginFromArrow, right: horizontalMarginFromArrow, ), child: ArrowWidget( color: arrowColor, headSize: arrowHeadSize, strokeWidth: arrowStrokeWidth, type: startArrowType, shouldDrawHead: isBidirectional ? true : (startArrowType == ArrowType.left || startArrowType == ArrowType.up), ), ), ), if (child != null) child, Expanded( child: Container( margin: EdgeInsets.only( top: verticalMarginFromArrow, left: horizontalMarginFromArrow, ), child: ArrowWidget( color: arrowColor, headSize: arrowHeadSize, strokeWidth: arrowStrokeWidth, type: endArrowType, shouldDrawHead: isBidirectional ? true : (endArrowType == ArrowType.right || endArrowType == ArrowType.down), ), ), ), ], ); } } /// Widget that draws a fully sized, centered, unidirectional arrow according to its constraints @immutable class ArrowWidget extends StatelessWidget { ArrowWidget({ this.color = defaultArrowColor, this.headSize = defaultIconSize, Key key, this.shouldDrawHead = true, this.strokeWidth = defaultArrowStrokeWidth, @required this.type, }) : assert(color != null), assert(headSize != null && headSize > 0.0), assert(strokeWidth != null && strokeWidth > 0.0), assert(shouldDrawHead != null), assert(type != null), _painter = _ArrowPainter( headSize: headSize, color: color, strokeWidth: strokeWidth, type: type, shouldDrawHead: shouldDrawHead, ), super(key: key); final Color color; /// The arrow head is a Equilateral triangle final double headSize; final double strokeWidth; final ArrowType type; final CustomPainter _painter; final bool shouldDrawHead; @override Widget build(BuildContext context) { return CustomPaint( painter: _painter, child: Container(), ); } } class _ArrowPainter extends CustomPainter { _ArrowPainter({ this.headSize = defaultIconSize, this.strokeWidth = defaultArrowStrokeWidth, this.color = defaultArrowColor, this.shouldDrawHead = true, @required this.type, }) : assert(headSize != null), assert(color != null), assert(strokeWidth != null), assert(type != null), assert(shouldDrawHead != null), // the height of an equilateral triangle headHeight = 0.5 * sqrt(3) * headSize; final Color color; final double headSize; final bool shouldDrawHead; final double strokeWidth; final ArrowType type; final double headHeight; bool headIsGreaterThanConstraint(Size size) { if (type == ArrowType.left || type == ArrowType.right) { return headHeight >= (size.width); } return headHeight >= (size.height); } @override bool shouldRepaint(CustomPainter oldDelegate) => !(oldDelegate is _ArrowPainter && headSize == oldDelegate.headSize && strokeWidth == oldDelegate.strokeWidth && color == oldDelegate.color && type == oldDelegate.type); @override void paint(Canvas canvas, Size size) { final paint = Paint() ..color = color ..strokeWidth = strokeWidth; final originX = size.width / 2, originY = size.height / 2; Offset lineStartingPoint = Offset.zero; Offset lineEndingPoint = Offset.zero; if (!headIsGreaterThanConstraint(size) && shouldDrawHead) { Offset p1, p2, p3; final headSizeDividedBy2 = headSize / 2; switch (type) { case ArrowType.up: p1 = Offset(originX, 0); p2 = Offset(originX - headSizeDividedBy2, headHeight); p3 = Offset(originX + headSizeDividedBy2, headHeight); break; case ArrowType.left: p1 = Offset(0, originY); p2 = Offset(headHeight, originY - headSizeDividedBy2); p3 = Offset(headHeight, originY + headSizeDividedBy2); break; case ArrowType.right: final startingX = size.width - headHeight; p1 = Offset(size.width, originY); p2 = Offset(startingX, originY - headSizeDividedBy2); p3 = Offset(startingX, originY + headSizeDividedBy2); break; case ArrowType.down: final startingY = size.height - headHeight; p1 = Offset(originX, size.height); p2 = Offset(originX - headSizeDividedBy2, startingY); p3 = Offset(originX + headSizeDividedBy2, startingY); break; } final path = Path() ..moveTo(p1.dx, p1.dy) ..lineTo(p2.dx, p2.dy) ..lineTo(p3.dx, p3.dy) ..close(); canvas.drawPath(path, paint); switch (type) { case ArrowType.up: lineStartingPoint = Offset(originX, headHeight); lineEndingPoint = Offset(originX, size.height); break; case ArrowType.left: lineStartingPoint = Offset(headHeight, originY); lineEndingPoint = Offset(size.width, originY); break; case ArrowType.right: final arrowHeadStartingX = size.width - headHeight; lineStartingPoint = Offset(0, originY); lineEndingPoint = Offset(arrowHeadStartingX, originY); break; case ArrowType.down: final headStartingY = size.height - headHeight; lineStartingPoint = Offset(originX, 0); lineEndingPoint = Offset(originX, headStartingY); break; } } else { // draw full line switch (type) { case ArrowType.up: case ArrowType.down: lineStartingPoint = Offset(originX, 0); lineEndingPoint = Offset(originX, size.height); break; case ArrowType.left: case ArrowType.right: lineStartingPoint = Offset(0, originY); lineEndingPoint = Offset(size.width, originY); break; } } canvas.drawLine( lineStartingPoint, lineEndingPoint, paint, ); } }
devtools/packages/devtools_app/lib/src/inspector/layout_explorer/ui/arrow.dart/0
{'file_path': 'devtools/packages/devtools_app/lib/src/inspector/layout_explorer/ui/arrow.dart', 'repo_id': 'devtools', 'token_count': 4027}
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:collection'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:vm_service/vm_service.dart'; import '../auto_dispose_mixin.dart'; import '../table.dart'; import '../table_data.dart'; import '../utils.dart'; import 'memory_controller.dart'; import 'memory_graph_model.dart'; import 'memory_heap_tree_view.dart'; import 'memory_snapshot_models.dart'; bool _classMatcher(HeapGraphClassLive liveClass) { final regExp = RegExp(knownClassesRegExs); return regExp.allMatches(liveClass.name).isNotEmpty; } /// Returns a map of all datapoints collected: /// /// key: 'externals' value: List<ExternalReference> /// key: 'filters' value: List<ClassReference> /// key: 'libraries' value: List<ClassReference> /// Map<String, List<Reference>> collect( MemoryController controller, Snapshot snapshot) { final Map<String, List<Reference>> result = {}; // Analyze the snapshot's heap memory information final root = snapshot.libraryRoot; final heapGraph = controller.heapGraph; for (final library in root.children) { if (library.isExternals) { final externalsToAnalyze = <ExternalReference>[]; final ExternalReferences externals = library; for (final ExternalReference external in externals.children) { assert(external.isExternal); final liveExternal = external.liveExternal; final size = liveExternal.externalProperty.externalSize; final liveElement = liveExternal.live; final HeapGraphClassLive liveClass = liveElement.theClass; if (_classMatcher(liveClass)) { final instances = liveClass.getInstances(heapGraph); externalsToAnalyze.add(external); debugLogger('Regex external found ${liveClass.name} ' 'instances=${instances.length} ' 'allocated bytes=$size'); } } result['externals'] = externalsToAnalyze; } else if (library.isFiltered) { final filtersToAnalyze = <ClassReference>[]; for (final LibraryReference libraryRef in library.children) { for (final ClassReference classRef in libraryRef.children) { final HeapGraphClassLive liveClass = classRef.actualClass; if (_classMatcher(liveClass)) { filtersToAnalyze.add(classRef); final instances = liveClass.getInstances(heapGraph); debugLogger('Regex filtered found ${classRef.name} ' 'instances=${instances.length}'); } } result['filters'] = filtersToAnalyze; } } else if (library.isLibrary) { final librariesToAnalyze = <ClassReference>[]; for (final ClassReference classRef in library.children) { final HeapGraphClassLive liveClass = classRef.actualClass; if (_classMatcher(liveClass)) { librariesToAnalyze.add(classRef); final instances = liveClass.getInstances(heapGraph); debugLogger('Regex library found ${classRef.name} ' 'instances=${instances.length}'); } } result['libraries'] = librariesToAnalyze; } else if (library.isAnalysis) { // Nothing to do on anay analyses. } } return result; } const bucket10K = '1..10K'; const bucket50K = '10K..50K'; const bucket100K = '50K..100K'; const bucket500K = '100K..500K'; const bucket1M = '500K..1M'; const bucket10M = '1M..10M'; const bucket50M = '10M..50M'; const bucketBigM = '50M+'; class Bucket { Bucket(this.totalCount, this.totalBytes); int totalCount; int totalBytes; } void imageAnalysis( MemoryController controller, AnalysisSnapshotReference analysisSnapshot, Map<String, List<Reference>> collectedData, ) { // TODO(terry): Look at heap rate of growth (used, external, RSS). // TODO(terry): Any items with <empty> Reference.isEmpty need to be computed e.g., onExpand, collectedData.forEach((key, value) { switch (key) { case 'externals': final externalsNode = AnalysisReference('Externals'); analysisSnapshot.addChild(externalsNode); for (final ExternalReference ref in value) { final HeapGraphExternalLive liveExternal = ref.liveExternal; final HeapGraphElementLive liveElement = liveExternal.live; /// TODO(terry): Eliminate or show sentinels for total instances? final objectNode = AnalysisReference( '${ref.name}', countNote: liveElement.theClass.instancesCount, ); externalsNode.addChild(objectNode); var childExternalSizes = 0; final bucketSizes = SplayTreeMap<String, Bucket>(); for (final ExternalObjectReference child in ref.children) { if (child.externalSize < 10000) { bucketSizes.putIfAbsent(bucket10K, () => Bucket(0, 0)); bucketSizes[bucket10K].totalCount += 1; bucketSizes[bucket10K].totalBytes += child.externalSize; } else if (child.externalSize < 50000) { bucketSizes.putIfAbsent(bucket50K, () => Bucket(0, 0)); bucketSizes[bucket50K].totalCount += 1; bucketSizes[bucket50K].totalBytes += child.externalSize; } else if (child.externalSize < 100000) { bucketSizes.putIfAbsent(bucket100K, () => Bucket(0, 0)); bucketSizes[bucket100K].totalCount += 1; bucketSizes[bucket100K].totalBytes += child.externalSize; } else if (child.externalSize < 500000) { bucketSizes.putIfAbsent(bucket500K, () => Bucket(0, 0)); bucketSizes[bucket500K].totalCount += 1; bucketSizes[bucket500K].totalBytes += child.externalSize; } else if (child.externalSize < 1000000) { bucketSizes.putIfAbsent(bucket1M, () => Bucket(0, 0)); bucketSizes[bucket1M].totalCount += 1; bucketSizes[bucket1M].totalBytes += child.externalSize; } else if (child.externalSize < 10000000) { bucketSizes.putIfAbsent(bucket10M, () => Bucket(0, 0)); bucketSizes[bucket10M].totalCount += 1; bucketSizes[bucket10M].totalBytes += child.externalSize; } else if (child.externalSize < 50000000) { bucketSizes.putIfAbsent(bucket50M, () => Bucket(0, 0)); bucketSizes[bucket50M].totalCount += 1; bucketSizes[bucket50M].totalBytes += child.externalSize; } else { bucketSizes.putIfAbsent(bucketBigM, () => Bucket(0, 0)); bucketSizes[bucketBigM].totalCount += 1; bucketSizes[bucketBigM].totalBytes += child.externalSize; } childExternalSizes += child.externalSize; } final bucketNode = AnalysisReference( 'Buckets', sizeNote: childExternalSizes, ); bucketSizes.forEach((key, value) { bucketNode.addChild(AnalysisReference( '$key', countNote: value.totalCount, sizeNote: value.totalBytes, )); }); objectNode.addChild(bucketNode); } break; case 'filters': case 'libraries': final librariesNode = AnalysisReference('Library $key'); final matches = drillIn(controller, librariesNode, value); final imageCacheNode = processMatches(controller, matches); if (imageCacheNode != null) { librariesNode.addChild(imageCacheNode); } analysisSnapshot.addChild(librariesNode); } }); } AnalysisReference processMatches( MemoryController controller, Map<String, List<String>> matches, ) { // Root __FIELDS__ is a container for children, the children // are added, later, to a treenode - if the treenode should // be created. final AnalysisField pending = AnalysisField( '__FIELDS__', null, ); final AnalysisField cache = AnalysisField( '__FIELDS__', null, ); final AnalysisField live = AnalysisField( '__FIELDS__', null, ); var countPending = 0; var countCache = 0; var countLive = 0; bool imageCacheFound = false; matches.forEach((key, values) { final fields = key.split('.'); imageCacheFound = fields[0] == imageCache; for (final value in values) { switch (fields[1]) { case '_pendingImages': countPending++; pending.addChild(AnalysisField('url', value)); break; case '_cache': countCache++; cache.addChild(AnalysisField('url', value)); break; case '_liveImages': countLive++; live.addChild(AnalysisField('url', value)); break; } } }); if (imageCacheFound) { final imageCacheNode = AnalysisReference( imageCache, countNote: countPending + countCache + countLive, ); final pendingNode = AnalysisReference( 'Pending', countNote: countPending, ); final cacheNode = AnalysisReference( 'Cache', countNote: countCache, ); final liveNode = AnalysisReference( 'Live', countNote: countLive, ); final pendingInstance = AnalysisInstance( controller, 'Images', pending, ); final cacheInstance = AnalysisInstance( controller, 'Images', cache, ); final liveInstance = AnalysisInstance( controller, 'Images', live, ); pendingNode.addChild(pendingInstance); imageCacheNode.addChild(pendingNode); cacheNode.addChild(cacheInstance); imageCacheNode.addChild(cacheNode); liveNode.addChild(liveInstance); imageCacheNode.addChild(liveNode); return imageCacheNode; } return null; } // TODO(terry): Add a test, insure debugMonitor output never seen before checkin. /// Enable monitoring. bool _debugMonitorEnabled = false; // Name of classes to monitor then all field/object are followed with debug // information during drill in, e.g., final _debugMonitorClasses = ['ImageCache']; /// Class being monitored if its name is in the debugMonitorClasses. String _debugMonitorClass; void _debugMonitor(String msg) { if (!_debugMonitorEnabled || _debugMonitorClass == null) return; print('--> $_debugMonitorClass:$msg'); } ClassFields fieldsStack = ClassFields(); Map<String, List<String>> drillIn( MemoryController controller, AnalysisReference librariesNode, List<Reference> references, { createTreeNodes = false, }) { final Map<String, List<String>> result = {}; final matcher = ObjectMatcher((className, fields, value) { final key = '$className.${fields.join(".")}'; result.putIfAbsent(key, () => []); result[key].add(value); }); for (final ClassReference classRef in references) { if (!matcher.isClassMatched(classRef.name)) continue; // Insure instances are realized (not Reference.empty). computeInstanceForClassReference(controller, classRef); final HeapGraphClassLive liveClass = classRef.actualClass; AnalysisReference objectNode; if (createTreeNodes) { objectNode = AnalysisReference( '${classRef.name}', countNote: liveClass.instancesCount, ); librariesNode.addChild(objectNode); } if (_debugMonitorEnabled) { _debugMonitorClass = _debugMonitorClasses.contains(classRef.name) ? '${classRef.name}' : ''; } fieldsStack.push(classRef.name); var instanceIndex = 0; _debugMonitor('Class ${classRef.name} Instance=$instanceIndex'); for (final ObjectReference objRef in classRef.children) { final fields = objRef.instance.getFields(); // Root __FIELDS__ is a container for children, the children // are added, later, to a treenode - if the treenode should // be created. final AnalysisField fieldsRoot = AnalysisField( '__FIELDS__', null, ); for (final field in fields) { if (field.value.isSentinel) continue; final HeapGraphElementLive live = field.value; if (live.references.isNotEmpty) { _debugMonitor('${field.key} OBJECT Start'); final fieldObjectNode = AnalysisField(field.key, ''); fieldsStack.push(field.key); displayObject( matcher, fieldObjectNode, live, createTreeNodes: createTreeNodes, ); fieldsStack.pop(); if (createTreeNodes) { fieldsRoot.addChild(fieldObjectNode); } _debugMonitor('${field.key} OBJECT End'); } else { final value = displayData(live); if (value != null) { fieldsStack.push(field.key); matcher.findFieldMatch(fieldsStack, value); fieldsStack.pop(); _debugMonitor('${field.key} = $value'); if (createTreeNodes) { final fieldNode = AnalysisField(field.key, value); fieldsRoot.addChild(fieldNode); } } else { _debugMonitor('${field.key} Skipped null'); } } } if (createTreeNodes) { final instanceNode = AnalysisInstance( controller, 'Instance $instanceIndex', fieldsRoot, ); objectNode.addChild(instanceNode); } instanceIndex++; } fieldsStack.pop(); // Pop class name. } return result; } bool displayObject( ObjectMatcher matcher, AnalysisField objectField, HeapGraphElementLive live, { depth = 0, maxDepth = 4, createTreeNodes = false, }) { if (depth >= maxDepth) return null; if (live.references.isEmpty) return true; final fields = live.getFields(); for (final field in fields) { if (field.value.isSentinel) continue; final HeapGraphElementLive liveField = field.value; for (final ref in liveField.references) { if (ref.isSentinel) continue; final HeapGraphElementLive liveRef = ref; final objectFields = liveRef.getFields(); if (objectFields.isEmpty) continue; final newObject = AnalysisField(field.key, ''); _debugMonitor('${field.key} OBJECT start [depth=$depth]'); depth++; fieldsStack.push(field.key); final continueResult = displayObject( matcher, newObject, liveRef, depth: depth, createTreeNodes: createTreeNodes, ); fieldsStack.pop(); depth--; // Drilled in enough, stop. if (continueResult == null) continue; if (createTreeNodes) { objectField.addChild(newObject); } _debugMonitor('${field.key} OBJECT end [depth=$depth]'); } final value = displayData(liveField); if (value != null) { fieldsStack.push(field.key); matcher.findFieldMatch(fieldsStack, value); fieldsStack.pop(); _debugMonitor('${field.key}=$value'); if (createTreeNodes) { final node = AnalysisField(field.key, value); objectField.addChild(node); } } } return true; } String displayData(instance) { String result; switch (instance.origin.data.runtimeType) { case HeapSnapshotObjectNullData: case HeapSnapshotObjectNoData: case Null: case TypeArguments: break; default: result = '${instance.origin.data}'; } return result; } class AnalysisInstanceViewTable extends StatefulWidget { @override AnalysisInstanceViewState createState() => AnalysisInstanceViewState(); } /// Table of the fields of an instance (type, name and value). class AnalysisInstanceViewState extends State<AnalysisInstanceViewTable> with AutoDisposeMixin { MemoryController controller; final TreeColumnData<AnalysisField> treeColumn = _AnalysisFieldNameColumn(); final List<ColumnData<AnalysisField>> columns = []; @override void initState() { super.initState(); // Setup the table columns. columns.addAll([ treeColumn, _AnalysisFieldValueColumn(), ]); } @override void didChangeDependencies() { super.didChangeDependencies(); final newController = Provider.of<MemoryController>(context); if (newController == controller) return; controller = newController; cancel(); // Update the chart when the memorySource changes. addAutoDisposeListener(controller.selectedSnapshotNotifier, () { setState(() { controller.computeAllLibraries(rebuild: true); }); }); } @override Widget build(BuildContext context) { controller.analysisFieldsTreeTable = TreeTable<AnalysisField>( dataRoots: controller.analysisInstanceRoot, columns: columns, treeColumn: treeColumn, keyFactory: (typeRef) => PageStorageKey<String>(typeRef.name), sortColumn: columns[0], sortDirection: SortDirection.ascending, ); return controller.analysisFieldsTreeTable; } } class _AnalysisFieldNameColumn extends TreeColumnData<AnalysisField> { _AnalysisFieldNameColumn() : super('Name'); @override dynamic getValue(AnalysisField dataObject) => dataObject.name; @override String getDisplayValue(AnalysisField dataObject) => '${getValue(dataObject)}'; @override bool get supportsSorting => true; @override int compare(AnalysisField a, AnalysisField b) { final Comparable valueA = getValue(a); final Comparable valueB = getValue(b); return valueA.compareTo(valueB); } @override double get fixedWidthPx => 250.0; } class _AnalysisFieldValueColumn extends ColumnData<AnalysisField> { _AnalysisFieldValueColumn() : super( 'Value', fixedWidthPx: 350.0, ); @override dynamic getValue(AnalysisField dataObject) => dataObject.value; @override String getDisplayValue(AnalysisField dataObject) { var value = getValue(dataObject); if (value is String && value.length > 30) { value = '${value.substring(0, 13)}…${value.substring(value.length - 17)}'; } return '$value'; } @override bool get supportsSorting => true; @override int compare(AnalysisField a, AnalysisField b) { final Comparable valueA = getValue(a); final Comparable valueB = getValue(b); return valueA.compareTo(valueB); } } class ClassFields { final List<String> _fields = []; void clear() { _fields.clear(); } int get length => _fields.length; void push(String name) { _fields.add(name); } String pop() => _fields.removeLast(); String elementAt(int index) => _fields.elementAt(index); } const imageCache = 'ImageCache'; /// Callback function when an ObjectReference's class name and fields all match. /// Parameters: /// className that matched /// fields that all matched /// value of the matched objectReference /// typedef CompletedFunction = void Function( String className, List<String> fields, dynamic value); class ObjectMatcher { ObjectMatcher(this._matchCompleted); static const Map<String, List<List<String>>> matcherDrillIn = { '$imageCache': [ ['_pendingImages', 'data_', 'completer', 'context_', 'url'], ['_cache', 'data_', 'completer', 'context_', 'url'], ['_liveImages', 'data_', 'completer', 'context_', 'url'], ] }; final CompletedFunction _matchCompleted; bool isClassMatched(String className) => matcherDrillIn.containsKey(className); List<List<String>> _findClassMatch(String className) => matcherDrillIn[className]; // TODO(terry): Change to be less strict. Look for subclass or parentage // relationships. If a new field or subclass is added we can // still find what we're looking for. Maybe even consider the // the type we're looking for - best to be loosey goosey so // we're not brittle as the Framework or any code changes. /// First field name match. bool findFieldMatch(ClassFields classFields, dynamic value) { bool matched = false; final className = classFields._fields.elementAt(0); final listOfFieldsToMatch = _findClassMatch(className); if (listOfFieldsToMatch != null) { for (final fieldsToMatch in listOfFieldsToMatch) { final fieldsSize = fieldsToMatch.length; if (fieldsSize == classFields._fields.length - 1) { for (var index = 0; index < fieldsSize; index++) { if (fieldsToMatch[index] == classFields._fields.elementAt(index + 1)) { matched = true; } else { matched = false; break; } } } if (matched) { _matchCompleted(className, fieldsToMatch, value); break; } } } return matched; } }
devtools/packages/devtools_app/lib/src/memory/memory_analyzer.dart/0
{'file_path': 'devtools/packages/devtools_app/lib/src/memory/memory_analyzer.dart', 'repo_id': 'devtools', 'token_count': 8180}
// 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 VMChartController extends ChartController { VMChartController(this._memoryController) : super( displayTopLine: false, name: 'VM Memory', ); 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() { 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 externalValue = sample.external.toDouble(); addDataToTrace( TraceName.external.index, trace.Data(timestamp, externalValue), ); final usedValue = sample.used.toDouble(); addDataToTrace(TraceName.used.index, trace.Data(timestamp, usedValue)); final capacityValue = sample.capacity.toDouble(); addDataToTrace( TraceName.capacity.index, trace.Data(timestamp, capacityValue), ); final rssValue = sample.rss?.toDouble(); addDataToTrace(TraceName.rSS.index, trace.Data(timestamp, rssValue)); final rasterLayerValue = sample.rasterCache.layerBytes.toDouble(); addDataToTrace( TraceName.rasterLayer.index, trace.Data(timestamp, rasterLayerValue), ); final rasterPictureValue = sample.rasterCache.pictureBytes.toDouble(); addDataToTrace( TraceName.rasterPicture.index, trace.Data(timestamp, rasterPictureValue), ); } void addDataToTrace(int traceIndex, trace.Data data) { this.trace(traceIndex).addDatum(data); } } class MemoryVMChart extends StatefulWidget { const MemoryVMChart(this.chartController, {Key key}) : super(key: key); final VMChartController chartController; @override MemoryVMChartState createState() => MemoryVMChartState(); } /// Name of each trace being charted, index order is the trace index /// too (order of trace creation top-down order). enum TraceName { external, used, capacity, rSS, rasterLayer, rasterPicture, } class MemoryVMChartState extends State<MemoryVMChart> with AutoDisposeMixin { /// Controller attached to the chart. VMChartController get _chartController => widget.chartController; /// Controller for managing memory collection. MemoryController _memoryController; MemoryTimeline get _memoryTimeline => _memoryController.memoryTimeline; ColorScheme colorScheme; @override void initState() { super.initState(); setupTraces(); } @override void didChangeDependencies() { super.didChangeDependencies(); _memoryController = Provider.of<MemoryController>(context); colorScheme = Theme.of(context).colorScheme; cancel(); setupTraces(); _chartController.setupData(); addAutoDisposeListener(_memoryTimeline.sampleAddedNotifier, () { setState(() { _processHeapSample(_memoryTimeline.sampleAddedNotifier.value); }); }); } @override Widget build(BuildContext context) { if (_chartController != null) { if (_chartController.timestamps.isNotEmpty) { return Container( height: defaultChartHeight, child: Chart(_chartController), ); } } return const SizedBox(width: denseSpacing); } // TODO(terry): Move colors to theme? static final capacityColor = Colors.grey[400]; static const usedColor = Color(0xff33b5e5); static const externalColor = Color(0xff4ddeff); // TODO(terry): UX review of raster colors see https://github.com/flutter/devtools/issues/2616 final rasterLayerColor = Colors.greenAccent.shade400; static const rasterPictureColor = Color(0xffff4444); final rssColor = Colors.orange.shade700; void setupTraces() { if (_chartController.traces.isNotEmpty) { assert(_chartController.traces.length == TraceName.values.length); final externalIndex = TraceName.external.index; assert(_chartController.trace(externalIndex).name == TraceName.values[externalIndex].toString()); final usedIndex = TraceName.used.index; assert(_chartController.trace(usedIndex).name == TraceName.values[usedIndex].toString()); final capacityIndex = TraceName.capacity.index; assert(_chartController.trace(capacityIndex).name == TraceName.values[capacityIndex].toString()); final rSSIndex = TraceName.rSS.index; assert(_chartController.trace(rSSIndex).name == TraceName.values[rSSIndex].toString()); final rasterLayerIndex = TraceName.rasterLayer.index; assert(_chartController.trace(rasterLayerIndex).name == TraceName.values[rasterLayerIndex].toString()); final rasterPictureIndex = TraceName.rasterPicture.index; assert(_chartController.trace(rasterPictureIndex).name == TraceName.values[rasterPictureIndex].toString()); return; } final externalIndex = _chartController.createTrace( trace.ChartType.line, trace.PaintCharacteristics( color: externalColor, symbol: trace.ChartSymbol.disc, diameter: 1.5, ), stacked: true, name: TraceName.external.toString(), ); assert(externalIndex == TraceName.external.index); assert(_chartController.trace(externalIndex).name == TraceName.values[externalIndex].toString()); // Used Heap final usedIndex = _chartController.createTrace( trace.ChartType.line, trace.PaintCharacteristics( color: usedColor, symbol: trace.ChartSymbol.disc, diameter: 1.5, ), stacked: true, name: TraceName.used.toString(), ); assert(usedIndex == TraceName.used.index); assert(_chartController.trace(usedIndex).name == TraceName.values[usedIndex].toString()); // Heap Capacity final capacityIndex = _chartController.createTrace( trace.ChartType.line, trace.PaintCharacteristics( color: capacityColor, diameter: 0.0, symbol: trace.ChartSymbol.dashedLine, ), name: TraceName.capacity.toString(), ); assert(capacityIndex == TraceName.capacity.index); assert(_chartController.trace(capacityIndex).name == TraceName.values[capacityIndex].toString()); // RSS final rSSIndex = _chartController.createTrace( trace.ChartType.line, trace.PaintCharacteristics( color: rssColor, symbol: trace.ChartSymbol.dashedLine, strokeWidth: 2, ), name: TraceName.rSS.toString(), ); assert(rSSIndex == TraceName.rSS.index); assert(_chartController.trace(rSSIndex).name == TraceName.values[rSSIndex].toString()); final rasterLayerIndex = _chartController.createTrace( trace.ChartType.line, trace.PaintCharacteristics( color: rasterLayerColor, symbol: trace.ChartSymbol.dashedLine, strokeWidth: 2, ), name: TraceName.rasterLayer.toString(), ); assert(rasterLayerIndex == TraceName.rasterLayer.index); assert(_chartController.trace(rasterLayerIndex).name == TraceName.values[rasterLayerIndex].toString()); final rasterPictureIndex = _chartController.createTrace( trace.ChartType.line, trace.PaintCharacteristics( color: rasterPictureColor, symbol: trace.ChartSymbol.dashedLine, strokeWidth: 2, ), name: TraceName.rasterPicture.toString(), ); assert(rasterPictureIndex == TraceName.rasterPicture.index); assert(_chartController.trace(rasterPictureIndex).name == TraceName.values[rasterPictureIndex].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_vm_chart.dart/0
{'file_path': 'devtools/packages/devtools_app/lib/src/memory/memory_vm_chart.dart', 'repo_id': 'devtools', 'token_count': 3182}
// 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. // TODO(kenz): delete this legacy implementation after // https://github.com/flutter/flutter/commit/78a96b09d64dc2a520e5b269d5cea1b9dde27d3f // hits flutter stable. import 'dart:async'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import '../../analytics/analytics_stub.dart' if (dart.library.html) '../../analytics/analytics.dart' as ga; import '../../auto_dispose_mixin.dart'; import '../../banner_messages.dart'; import '../../common_widgets.dart'; import '../../config_specific/import_export/import_export.dart'; import '../../connected_app.dart'; import '../../dialogs.dart'; import '../../globals.dart'; import '../../notifications.dart'; import '../../screen.dart'; import '../../service_extensions.dart'; import '../../split.dart'; import '../../theme.dart'; import '../../ui/icons.dart'; import '../../ui/service_extension_widgets.dart'; import '../../ui/utils.dart'; import '../../ui/vm_flag_widgets.dart'; import '../../version.dart'; import 'event_details.dart'; import 'flutter_frames_chart.dart'; import 'performance_controller.dart'; import 'performance_model.dart'; import 'timeline_flame_chart.dart'; // TODO(kenz): handle small screen widths better by using Wrap instead of Row // where applicable. class LegacyPerformanceScreen extends Screen { const LegacyPerformanceScreen() : super.conditional( id: id, // Only show this screen for flutter apps, where we can conditionally // show this screen or [PerformanceScreen] based on the current // flutter version. requiresLibrary: flutterLibraryUri, requiresDartVm: true, worksOffline: true, shouldShowForFlutterVersion: _shouldShowForFlutterVersion, title: 'Performance', icon: Octicons.pulse, ); static const id = 'legacy-performance'; static bool _shouldShowForFlutterVersion(FlutterVersion currentVersion) { return currentVersion != null && currentVersion < SemanticVersion( major: 2, minor: 3, // Specifying patch makes the version number more readable. // ignore: avoid_redundant_argument_values patch: 0, preReleaseMajor: 16, preReleaseMinor: 0, ); } @override String get docPageId => 'performance'; @override Widget build(BuildContext context) => const LegacyPerformanceScreenBody(); } class LegacyPerformanceScreenBody extends StatefulWidget { const LegacyPerformanceScreenBody(); @override LegacyPerformanceScreenBodyState createState() => LegacyPerformanceScreenBodyState(); } class LegacyPerformanceScreenBodyState extends State<LegacyPerformanceScreenBody> with AutoDisposeMixin, OfflineScreenMixin<LegacyPerformanceScreenBody, LegacyOfflinePerformanceData> { static const _primaryControlsMinIncludeTextWidth = 725.0; static const _secondaryControlsMinIncludeTextWidth = 1100.0; LegacyPerformanceController controller; bool processing = false; double processingProgress = 0.0; @override void initState() { super.initState(); ga.screen(LegacyPerformanceScreen.id); } @override void didChangeDependencies() { super.didChangeDependencies(); maybePushDebugModePerformanceMessage(context, LegacyPerformanceScreen.id); final newController = Provider.of<LegacyPerformanceController>(context); if (newController == controller) return; controller = newController; cancel(); processing = controller.processing.value; addAutoDisposeListener(controller.processing, () { setState(() { processing = controller.processing.value; }); }); processingProgress = controller.processor.progressNotifier.value; addAutoDisposeListener(controller.processor.progressNotifier, () { setState(() { processingProgress = controller.processor.progressNotifier.value; }); }); addAutoDisposeListener(controller.selectedFrame); // Refresh data on page load if data is null. On subsequent tab changes, // this should not be called. if (controller.data == null && !offlineMode) { controller.refreshData(); } // Load offline timeline data if available. if (shouldLoadOfflineData()) { // This is a workaround to guarantee that DevTools exports are compatible // with other trace viewers (catapult, perfetto, chrome://tracing), which // require a top level field named "traceEvents". See how timeline data is // encoded in [ExportController.encode]. final timelineJson = Map<String, dynamic>.from(offlineDataJson[LegacyPerformanceScreen.id]) ..addAll({ LegacyPerformanceData.traceEventsKey: offlineDataJson[LegacyPerformanceData.traceEventsKey] }); final offlinePerformanceData = LegacyOfflinePerformanceData.parse(timelineJson); if (!offlinePerformanceData.isEmpty) { loadOfflineData(offlinePerformanceData); } } } @override Widget build(BuildContext context) { final isOfflineFlutterApp = offlineMode && controller.offlinePerformanceData != null && controller.offlinePerformanceData.frames.isNotEmpty; final performanceScreen = Column( children: [ if (!offlineMode) _buildPerformanceControls(), const SizedBox(height: denseRowSpacing), if (isOfflineFlutterApp || (!offlineMode && serviceManager.connectedApp.isFlutterAppNow)) ValueListenableBuilder( valueListenable: controller.flutterFrames, builder: (context, frames, _) => ValueListenableBuilder( valueListenable: controller.displayRefreshRate, builder: (context, displayRefreshRate, _) { return LegacyFlutterFramesChart( frames, displayRefreshRate, ); }, ), ), Expanded( child: Split( axis: Axis.vertical, initialFractions: const [0.6, 0.4], children: [ LegacyTimelineFlameChartContainer( processing: processing, processingProgress: processingProgress, ), ValueListenableBuilder( valueListenable: controller.selectedTimelineEvent, builder: (context, selectedEvent, _) { return EventDetails(selectedEvent); }, ), ], ), ), ], ); // We put these two items in a stack because the screen's UI needs to be // built before offline data is processed in order to initialize listeners // that respond to data processing events. The spinner hides the screen's // empty UI while data is being processed. return Stack( children: [ performanceScreen, if (loadingOfflineData) Container( color: Theme.of(context).scaffoldBackgroundColor, child: const CenteredCircularProgressIndicator(), ), ], ); } Widget _buildPerformanceControls() { return Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ _buildPrimaryStateControls(), _buildSecondaryControls(), ], ); } Widget _buildPrimaryStateControls() { return ValueListenableBuilder( valueListenable: controller.refreshing, builder: (context, refreshing, _) { return Row( children: [ RefreshButton( includeTextWidth: _primaryControlsMinIncludeTextWidth, onPressed: (refreshing || processing) ? null : _refreshPerformanceData, ), const SizedBox(width: defaultSpacing), ClearButton( includeTextWidth: _primaryControlsMinIncludeTextWidth, onPressed: (refreshing || processing) ? null : _clearPerformanceData, ), ], ); }, ); } Widget _buildSecondaryControls() { return Row( mainAxisAlignment: MainAxisAlignment.end, children: [ ProfileGranularityDropdown( screenId: LegacyPerformanceScreen.id, profileGranularityFlagNotifier: controller.cpuProfilerController.profileGranularityFlagNotifier, ), const SizedBox(width: defaultSpacing), if (!serviceManager.connectedApp.isDartCliAppNow) ServiceExtensionButtonGroup( minIncludeTextWidth: _secondaryControlsMinIncludeTextWidth, extensions: [performanceOverlay, profileWidgetBuilds], ), // TODO(kenz): hide or disable button if http timeline logging is not // available. const SizedBox(width: defaultSpacing), ExportButton( onPressed: _exportPerformanceData, includeTextWidth: _secondaryControlsMinIncludeTextWidth, ), const SizedBox(width: defaultSpacing), SettingsOutlinedButton( onPressed: _openSettingsDialog, label: 'Performance Settings', ), ], ); } void _openSettingsDialog() { showDialog( context: context, builder: (context) => LegacyPerformanceSettingsDialog(controller), ); } Future<void> _refreshPerformanceData() async { await controller.refreshData(); } Future<void> _clearPerformanceData() async { await controller.clearData(); setState(() {}); } void _exportPerformanceData() { final exportedFile = controller.exportData(); // TODO(kenz): investigate if we need to do any error handling here. Is the // download always successful? // TODO(peterdjlee): find a way to push the notification logic into the // export controller. Notifications.of(context).push(successfulExportMessage(exportedFile)); } @override FutureOr<void> processOfflineData( LegacyOfflinePerformanceData offlineData) async { await controller.processOfflineData(offlineData); } @override bool shouldLoadOfflineData() { return offlineMode && offlineDataJson.isNotEmpty && offlineDataJson[LegacyPerformanceScreen.id] != null && offlineDataJson[LegacyPerformanceData.traceEventsKey] != null; } } class LegacyPerformanceSettingsDialog extends StatelessWidget { const LegacyPerformanceSettingsDialog(this.controller); final LegacyPerformanceController controller; @override Widget build(BuildContext context) { final theme = Theme.of(context); return DevToolsDialog( title: dialogTitleText(theme, 'Performance Settings'), includeDivider: false, content: Container( width: defaultDialogWidth, child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ ...dialogSubHeader(theme, 'Recorded Timeline Streams'), ..._defaultRecordedStreams(theme), ..._advancedStreams(theme), if (serviceManager.connectedApp.isFlutterAppNow) ...[ const SizedBox(height: denseSpacing), ..._additionalFlutterSettings(theme), ], ], ), ), actions: [ DialogCloseButton(), ], ); } List<Widget> _defaultRecordedStreams(ThemeData theme) { return [ RichText( text: TextSpan( text: 'Default', style: theme.subtleTextStyle, ), ), ..._timelineStreams(theme, advanced: false), // Special case "Network Traffic" because it is not implemented as a // Timeline recorded stream in the VM. The user does not need to be aware of // the distinction, however. _buildStream( name: 'Network', description: ' • Http traffic', listenable: controller.httpTimelineLoggingEnabled, onChanged: controller.toggleHttpRequestLogging, theme: theme, ), ]; } List<Widget> _advancedStreams(ThemeData theme) { return [ RichText( text: TextSpan( text: 'Advanced', style: theme.subtleTextStyle, ), ), ..._timelineStreams(theme, advanced: true), ]; } List<Widget> _timelineStreams( ThemeData theme, { @required bool advanced, }) { final settings = <Widget>[]; final streams = controller.recordedStreams .where((s) => s.advanced == advanced) .toList(); for (final stream in streams) { settings.add(_buildStream( name: stream.name, description: ' • ${stream.description}', listenable: stream.enabled, onChanged: (_) => controller.toggleTimelineStream(stream), theme: theme, )); } return settings; } Widget _buildStream({ @required String name, @required String description, @required ValueListenable listenable, @required void Function(bool) onChanged, @required ThemeData theme, }) { return Row( mainAxisSize: MainAxisSize.min, children: [ // TODO(kenz): refactor so that we can use NotifierCheckbox here. ValueListenableBuilder( valueListenable: listenable, builder: (context, value, _) { return Checkbox( value: value, onChanged: onChanged, ); }, ), Flexible( child: RichText( overflow: TextOverflow.visible, text: TextSpan( text: name, style: theme.regularTextStyle, children: [ TextSpan( text: description, style: theme.subtleTextStyle, ), ], ), ), ), ], ); } List<Widget> _additionalFlutterSettings(ThemeData theme) { return [ ...dialogSubHeader(theme, 'Additional Settings'), _LegacyBadgeJankyFramesSetting(controller), ]; } } class _LegacyBadgeJankyFramesSetting extends StatelessWidget { const _LegacyBadgeJankyFramesSetting(this.controller); final LegacyPerformanceController controller; @override Widget build(BuildContext context) { return Row( children: [ NotifierCheckbox(notifier: controller.badgeTabForJankyFrames), RichText( overflow: TextOverflow.visible, text: TextSpan( text: 'Badge Performance tab when Flutter UI jank is detected', style: Theme.of(context).regularTextStyle, ), ), ], ); } }
devtools/packages/devtools_app/lib/src/performance/legacy/performance_screen.dart/0
{'file_path': 'devtools/packages/devtools_app/lib/src/performance/legacy/performance_screen.dart', 'repo_id': 'devtools', 'token_count': 5964}
import '../table_data.dart'; import '../url_utils.dart'; import '../utils.dart'; import 'cpu_profile_model.dart'; const _timeColumnWidthPx = 180.0; class SelfTimeColumn extends ColumnData<CpuStackFrame> { SelfTimeColumn({String titleTooltip}) : super( 'Self Time', titleTooltip: titleTooltip, fixedWidthPx: _timeColumnWidthPx, ); @override bool get numeric => true; @override int compare(CpuStackFrame a, CpuStackFrame b) { final int result = super.compare(a, b); if (result == 0) { return a.name.compareTo(b.name); } return result; } @override dynamic getValue(CpuStackFrame dataObject) => dataObject.selfTime.inMicroseconds; @override String getDisplayValue(CpuStackFrame dataObject) { return '${msText(dataObject.selfTime, fractionDigits: 2)} ' '(${percent2(dataObject.selfTimeRatio)})'; } } class TotalTimeColumn extends ColumnData<CpuStackFrame> { TotalTimeColumn({String titleTooltip}) : super( 'Total Time', titleTooltip: titleTooltip, fixedWidthPx: _timeColumnWidthPx, ); @override bool get numeric => true; @override int compare(CpuStackFrame a, CpuStackFrame b) { final int result = super.compare(a, b); if (result == 0) { return a.name.compareTo(b.name); } return result; } @override dynamic getValue(CpuStackFrame dataObject) => dataObject.totalTime.inMicroseconds; @override String getDisplayValue(CpuStackFrame dataObject) { return '${msText(dataObject.totalTime, fractionDigits: 2)} ' '(${percent2(dataObject.totalTimeRatio)})'; } } class MethodNameColumn extends TreeColumnData<CpuStackFrame> { MethodNameColumn() : super('Method'); static const maxMethodNameLength = 75; @override dynamic getValue(CpuStackFrame dataObject) => dataObject.name; @override String getDisplayValue(CpuStackFrame dataObject) { if (dataObject.name.length > maxMethodNameLength) { return dataObject.name.substring(0, maxMethodNameLength) + '...'; } return dataObject.name; } @override bool get supportsSorting => true; @override String getTooltip(CpuStackFrame dataObject) => dataObject.name; } // TODO(kenz): make these urls clickable once we can jump to source. class SourceColumn extends ColumnData<CpuStackFrame> { SourceColumn() : super.wide('Source', alignment: ColumnAlignment.right); @override dynamic getValue(CpuStackFrame dataObject) => dataObject.url; @override String getDisplayValue(CpuStackFrame dataObject) { return getSimplePackageUrl(dataObject.url); } @override String getTooltip(CpuStackFrame dataObject) => dataObject.url; @override bool get supportsSorting => true; }
devtools/packages/devtools_app/lib/src/profiler/cpu_profile_columns.dart/0
{'file_path': 'devtools/packages/devtools_app/lib/src/profiler/cpu_profile_columns.dart', 'repo_id': 'devtools', 'token_count': 1013}
// 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:collection/collection.dart'; import 'package:meta/meta.dart'; import 'package:vm_service/vm_service.dart' hide SentinelException; import '../../eval_on_dart_library.dart'; import 'fake_freezed_annotation.dart'; // This part is generated using package:freezed, but without the devtool depending // on the package. // To update the generated files, temporarily add freezed/freezed_annotation/build_runner // as dependencies; replace the `fake_freezed_annotation.dart` import with the // real annotation package, then execute `pub run build_runner build`. part 'result.freezed.dart'; @freezed abstract class Result<T> with _$Result<T> { Result._(); factory Result.data(@nullable T value) = _ResultData<T>; factory Result.error(Object error, [StackTrace stackTrace]) = _ResultError<T>; factory Result.guard(T Function() cb) { try { return Result.data(cb()); } catch (err, stack) { return Result.error(err, stack); } } static Future<Result<T>> guardFuture<T>(Future<T> Function() cb) async { try { return Result.data(await cb()); } catch (err, stack) { return Result.error(err, stack); } } Result<Res> chain<Res>(Res Function(T value) cb) { return when( data: (value) { try { return Result.data(cb(value)); } catch (err, stack) { return Result.error(err, stack); } }, error: (err, stack) => Result.error(err, stack), ); } T get dataOrThrow { return when( data: (value) => value, error: (err, stack) { // ignore: only_throw_errors throw err; }, ); } } Result<T> parseSentinel<T>(Object value) { // TODO(rrousselGit) remove condition after migrating to NNBD if (value == null) return Result.data(null); if (value is T) return Result.data(value); if (value is Sentinel) { return Result.error( SentinelException(value), StackTrace.current, ); } return Result.error(value, StackTrace.current); }
devtools/packages/devtools_app/lib/src/provider/instance_viewer/result.dart/0
{'file_path': 'devtools/packages/devtools_app/lib/src/provider/instance_viewer/result.dart', 'repo_id': 'devtools', 'token_count': 806}
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'common_widgets.dart'; import 'globals.dart'; import 'routing.dart'; import 'screen.dart'; import 'theme.dart'; /// The screen in the app responsible for connecting to the Dart VM. /// /// We need to use this screen to get a guarantee that the app has a Dart VM /// available. class SnapshotScreenBody extends StatefulWidget { const SnapshotScreenBody(this.args, this.possibleScreens); final SnapshotArguments args; /// All possible screens, both visible and hidden, that DevTools was started /// with. /// /// This will include screens that are only available when connected to an app /// as well as screens that are only available based on the presence of a /// conditional library. /// /// These screens are stored here so that we can import files for all screens, /// regardless of whether an app is connected to DevTools or whether a /// connected app contains the correct conditional library. final List<Screen> possibleScreens; @override _SnapshotScreenBodyState createState() => _SnapshotScreenBodyState(); } class _SnapshotScreenBodyState extends State<SnapshotScreenBody> { Screen _screen; @override void initState() { super.initState(); _initScreen(); } @override void didChangeDependencies() { super.didChangeDependencies(); } @override void didUpdateWidget(SnapshotScreenBody oldWidget) { super.didUpdateWidget(oldWidget); if (widget.args != oldWidget.args || widget.possibleScreens != oldWidget.possibleScreens) { _initScreen(); } } void _initScreen() { _screen = widget.possibleScreens.firstWhere( (s) => s.screenId == widget.args?.screenId, orElse: () => null, ); } @override Widget build(BuildContext context) { final routerDelegate = DevToolsRouterDelegate.of(context); return Column( children: [ Row( children: [ ExitOfflineButton(onPressed: () { offlineMode = false; reset(); // Use Router.neglect to replace the current history entry with // the homepage so that clicking Back will not return here. Router.neglect( context, () => routerDelegate.navigate( homePageId, {'screen': null}, ), ); }), ], ), const SizedBox(height: denseRowSpacing), Expanded( child: _screen != null ? _screen.build(context) : _buildSnapshotError(), ), ], ); } Widget _buildSnapshotError() { return CenteredMessage( 'Cannot load snapshot for screen \'${widget.args?.screenId}\''); } void reset() { setState(() { offlineDataJson.clear(); _screen = null; }); } } class SnapshotArguments { SnapshotArguments(this.screenId); SnapshotArguments.fromArgs(Map<String, String> args) : this(args['screen']); final String screenId; }
devtools/packages/devtools_app/lib/src/snapshot_screen.dart/0
{'file_path': 'devtools/packages/devtools_app/lib/src/snapshot_screen.dart', 'repo_id': 'devtools', 'token_count': 1188}
// 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. @JS() library gtags; // ignore_for_file: non_constant_identifier_names import 'package:js/js.dart'; import '../analytics/analytics.dart' as ga; /// For gtags API see https://developers.google.com/gtagjs/reference/api /// For debugging install the Chrome Plugin "Google Analytics Debugger". @JS('gtag') external void _gTagCommandName(String command, String name, [dynamic params]); /// Google Analytics ready to collect. @JS('isGaInitialized') external bool isGaInitialized(); class GTag { static const String _event = 'event'; static const String _exception = 'exception'; /// Collect the analytic's event and its parameters. static void event(String eventName, GtagEvent gaEvent) async { if (await ga.isAnalyticsEnabled()) { _gTagCommandName(_event, eventName, gaEvent); } } static void exception(GtagException gaException) async { if (await ga.isAnalyticsEnabled()) { _gTagCommandName(_event, _exception, gaException); } } } @JS() @anonymous class GtagEvent { external factory GtagEvent({ String event_category, String event_label, // Event e.g., gaScreenViewEvent, gaSelectEvent, etc. String send_to, // UA ID of target GA property to receive event data. int value, bool non_interaction, dynamic custom_map, }); external String get event_category; external String get event_label; external String get send_to; external int get value; // Positive number. external bool get non_interaction; external dynamic get custom_map; // Custom metrics } @JS() @anonymous class GtagException { external factory GtagException({ String description, bool fatal, }); external String get description; // Description of the error. external bool get fatal; // Fatal error. }
devtools/packages/devtools_app/lib/src/ui/gtags.dart/0
{'file_path': 'devtools/packages/devtools_app/lib/src/ui/gtags.dart', 'repo_id': 'devtools', 'token_count': 590}
// 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:vm_service/vm_service.dart'; /// NOTE: this file contains extensions to classes provided by /// `package:vm_service` in order to expose VM internal fields in a controlled /// fashion. Objects and extensions in this class should not be used outside of /// the `vm_developer` directory. /// An extension on [VM] which allows for access to VM internal fields. extension VMPrivateViewExtension on VM { String get embedder => json['_embedder']; String get profilerMode => json['_profilerMode']; int get currentMemory => json['_currentMemory']; int get currentRSS => json['_currentRSS']; int get maxRSS => json['_maxRSS']; int get nativeZoneMemoryUsage => json['_nativeZoneMemoryUsage']; } /// An extension on [Isolate] which allows for access to VM internal fields. extension IsolatePrivateViewExtension on Isolate { Map<String, dynamic> get tagCounters => json['_tagCounters']; int get dartHeapSize => newSpaceUsage + oldSpaceUsage; int get dartHeapCapacity => newSpaceCapacity + oldSpaceCapacity; int get newSpaceUsage => json['_heaps']['new']['used']; int get oldSpaceUsage => json['_heaps']['old']['used']; int get newSpaceCapacity => json['_heaps']['new']['capacity']; int get oldSpaceCapacity => json['_heaps']['old']['capacity']; }
devtools/packages/devtools_app/lib/src/vm_developer/vm_service_private_extensions.dart/0
{'file_path': 'devtools/packages/devtools_app/lib/src/vm_developer/vm_service_private_extensions.dart', 'repo_id': 'devtools', 'token_count': 430}
name: devtools_app description: Web-based performance tooling for Dart and Flutter. # Note: this version should only be updated by running tools/update_version.dart # that updates all versions of packages from packages/devtools. # When publishing new versions of this package be sure to publish a new version # of package:devtools as well. package:devtools contains a compiled snapshot of # this package. version: 2.3.3-dev.1 homepage: https://github.com/flutter/devtools environment: sdk: '>=2.10.0 <3.0.0' # The flutter desktop support interacts with build scripts on the Flutter # side that are not yet stable, so it requires a very recent version of # Flutter. This version will increase regularly as the build scripts change. flutter: '>=1.10.0' dependencies: ansi_up: ^0.0.2 # path: ../../third_party/packages/ansi_up # Pin ansicolor to version before pre-NNBD version 1.1.0, should be ^1.0.5 # See https://github.com/flutter/devtools/issues/2530 ansicolor: 1.0.5 async: ^2.0.0 codicon: ^0.0.3 collection: ^1.15.0-nnbd dds: ^2.0.1 devtools_shared: 2.3.3-dev.1 file: ^6.0.0 file_selector: ^0.8.0 file_selector_linux: ^0.0.2 file_selector_macos: ^0.0.2 file_selector_web: ^0.8.1 file_selector_windows: ^0.0.2 flutter: sdk: flutter flutter_riverpod: ^0.14.0+3 flutter_web_plugins: sdk: flutter http: ^0.13.0 image: ^3.0.2 intl: '>=0.16.1 <0.18.0' js: ^0.6.1+1 meta: ^1.3.0 mime: ^1.0.0 path: ^1.8.0 pedantic: ^1.11.0 provider: ^5.0.0 sse: ^4.0.0 stack_trace: ^1.10.0 string_scanner: ^1.1.0 url_launcher: ^5.0.0 url_launcher_web: ^0.1.1+6 vm_service: ^7.1.0 vm_snapshot_analysis: ^0.6.0 web_socket_channel: ^2.1.0 dev_dependencies: build_runner: ^2.0.4 devtools: 2.3.3-dev.1 devtools_testing: 2.3.3-dev.1 flutter_test: sdk: flutter mockito: ^5.0.9 webkit_inspection_protocol: '>=0.5.0 <2.0.0' flutter: uses-material-design: true assets: - assets/ - assets/img/ - assets/img/layout_explorer/ - assets/img/layout_explorer/cross_axis_alignment/ - assets/img/layout_explorer/main_axis_alignment/ - assets/img/legend/ - assets/scripts/inspector_polyfill_script.dart - icons/ - icons/actions/ - icons/custom/ - icons/general/ - icons/gutter/ - icons/inspector/ - icons/memory/ - icons/perf/ fonts: - family: Roboto fonts: - asset: fonts/Roboto/Roboto-Thin.ttf weight: 100 - asset: fonts/Roboto/Roboto-Light.ttf weight: 300 - asset: fonts/Roboto/Roboto-Regular.ttf weight: 400 - asset: fonts/Roboto/Roboto-Medium.ttf weight: 500 - asset: fonts/Roboto/Roboto-Bold.ttf weight: 700 - asset: fonts/Roboto/Roboto-Black.ttf weight: 900 - family: RobotoMono fonts: - asset: fonts/Roboto_Mono/RobotoMono-Thin.ttf weight: 100 - asset: fonts/Roboto_Mono/RobotoMono-Light.ttf weight: 300 - asset: fonts/Roboto_Mono/RobotoMono-Regular.ttf weight: 400 - asset: fonts/Roboto_Mono/RobotoMono-Medium.ttf weight: 500 - asset: fonts/Roboto_Mono/RobotoMono-Bold.ttf weight: 700 - family: Octicons fonts: - asset: fonts/Octicons.ttf - family: Codicon fonts: - asset: packages/codicon/font/codicon.ttf dependency_overrides: # The '#OVERRIDE_FOR_DEVELOPMENT' lines are stripped out when we publish. # All overriden dependencies are published together so there is no harm # in treating them like they are part of a mono-repo while developing. devtools_server: #OVERRIDE_FOR_DEVELOPMENT path: ../devtools_server #OVERRIDE_FOR_DEVELOPMENT devtools_shared: #OVERRIDE_FOR_DEVELOPMENT path: ../devtools_shared #OVERRIDE_FOR_DEVELOPMENT devtools_testing: #OVERRIDE_FOR_DEVELOPMENT path: ../devtools_testing #OVERRIDE_FOR_DEVELOPMENT devtools: #OVERRIDE_FOR_DEVELOPMENT path: ../devtools #OVERRIDE_FOR_DEVELOPMENT
devtools/packages/devtools_app/pubspec.yaml/0
{'file_path': 'devtools/packages/devtools_app/pubspec.yaml', 'repo_id': 'devtools', 'token_count': 1785}
// 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/profiler/cpu_profile_controller.dart'; import 'package:devtools_app/src/profiler/cpu_profile_model.dart'; import 'package:devtools_app/src/service_manager.dart'; import 'package:devtools_testing/support/cpu_profile_test_data.dart'; import 'package:flutter_test/flutter_test.dart'; import 'support/mocks.dart'; import 'support/utils.dart'; void main() { group('CpuProfileController', () { CpuProfilerController controller; FakeServiceManager fakeServiceManager; setUp(() { fakeServiceManager = FakeServiceManager(); setGlobal(ServiceConnectionManager, fakeServiceManager); controller = CpuProfilerController(); }); Future<void> pullProfileAndSelectFrame() async { await controller.pullAndProcessProfile(startMicros: 0, extentMicros: 100); controller.selectCpuStackFrame(testStackFrame); expect( controller.dataNotifier.value, isNot(equals(CpuProfilerController.baseStateCpuProfileData)), ); expect( controller.selectedCpuStackFrameNotifier.value, equals(testStackFrame), ); } test('pullAndProcessProfile', () async { expect( controller.dataNotifier.value, equals(CpuProfilerController.baseStateCpuProfileData), ); expect(controller.processingNotifier.value, false); // [startMicros] and [extentMicros] are arbitrary for testing. await controller.pullAndProcessProfile(startMicros: 0, extentMicros: 100); expect( controller.dataNotifier.value, isNot(equals(CpuProfilerController.baseStateCpuProfileData)), ); expect(controller.processingNotifier.value, false); await controller.clear(); expect( controller.dataNotifier.value, equals(CpuProfilerController.baseStateCpuProfileData), ); }); test('selectCpuStackFrame', () async { expect( controller.dataNotifier.value.selectedStackFrame, isNull, ); expect(controller.selectedCpuStackFrameNotifier.value, isNull); controller.selectCpuStackFrame(testStackFrame); expect( controller.dataNotifier.value.selectedStackFrame, equals(testStackFrame), ); expect( controller.selectedCpuStackFrameNotifier.value, equals(testStackFrame), ); await controller.clear(); expect(controller.selectedCpuStackFrameNotifier.value, isNull); }); test('matchesForSearch', () async { // [startMicros] and [extentMicros] are arbitrary for testing. await controller.pullAndProcessProfile(startMicros: 0, extentMicros: 100); expect( controller.dataNotifier.value.stackFrames.values.length, equals(17)); // Match on name. expect(controller.matchesForSearch(null).length, equals(0)); expect(controller.matchesForSearch('').length, equals(0)); expect(controller.matchesForSearch('render').length, equals(9)); expect(controller.matchesForSearch('RenderObject').length, equals(3)); expect(controller.matchesForSearch('THREAD').length, equals(2)); expect(controller.matchesForSearch('paint').length, equals(7)); // Match on url. expect(controller.matchesForSearch('rendering/').length, equals(9)); expect(controller.matchesForSearch('proxy_box.dart').length, equals(2)); expect(controller.matchesForSearch('dartlang-sdk').length, equals(1)); // Match with RegExp. expect( controller.matchesForSearch('rendering/.*\.dart').length, equals(9)); expect(controller.matchesForSearch('RENDER.*\.paint').length, equals(6)); }); test('matchesForSearch sets isSearchMatch property', () async { // [startMicros] and [extentMicros] are arbitrary for testing. await controller.pullAndProcessProfile(startMicros: 0, extentMicros: 100); expect( controller.dataNotifier.value.stackFrames.values.length, equals(17)); var matches = controller.matchesForSearch('render'); verifyIsSearchMatch( controller.dataNotifier.value.stackFrames.values.toList(), matches, ); matches = controller.matchesForSearch('THREAD'); verifyIsSearchMatch( controller.dataNotifier.value.stackFrames.values.toList(), matches, ); }); test('processDataForTag', () async { final cpuProfileDataWithTags = CpuProfileData.parse(cpuProfileDataWithUserTagsJson); await controller.transformer.processData(cpuProfileDataWithTags); controller.loadProcessedData(cpuProfileDataWithTags); expect( controller.dataNotifier.value.cpuProfileRoot.profileMetaData.time .duration.inMicroseconds, equals(250)); expect( controller.dataNotifier.value.cpuProfileRoot.toStringDeep(), equals( ''' all - children: 1 - excl: 0 - incl: 5 Frame1 - children: 2 - excl: 0 - incl: 5 Frame2 - children: 2 - excl: 0 - incl: 2 Frame3 - children: 0 - excl: 1 - incl: 1 Frame4 - children: 0 - excl: 1 - incl: 1 Frame5 - children: 1 - excl: 2 - incl: 3 Frame6 - children: 0 - excl: 1 - incl: 1 ''', ), ); await controller.loadDataWithTag('userTagA'); expect( controller.dataNotifier.value.cpuProfileRoot.toStringDeep(), equals( ''' all - children: 1 - excl: 0 - incl: 2 Frame1 - children: 2 - excl: 0 - incl: 2 Frame2 - children: 1 - excl: 0 - incl: 1 Frame3 - children: 0 - excl: 1 - incl: 1 Frame5 - children: 0 - excl: 1 - incl: 1 ''', ), ); await controller.loadDataWithTag('userTagB'); expect( controller.dataNotifier.value.cpuProfileRoot.toStringDeep(), equals( ''' all - children: 1 - excl: 0 - incl: 1 Frame1 - children: 1 - excl: 0 - incl: 1 Frame2 - children: 1 - excl: 0 - incl: 1 Frame4 - children: 0 - excl: 1 - incl: 1 ''', ), ); await controller.loadDataWithTag('userTagC'); expect( controller.dataNotifier.value.cpuProfileRoot.toStringDeep(), equals( ''' all - children: 1 - excl: 0 - incl: 2 Frame1 - children: 1 - excl: 0 - incl: 2 Frame5 - children: 1 - excl: 1 - incl: 2 Frame6 - children: 0 - excl: 1 - incl: 1 ''', ), ); }); test('reset', () async { await pullProfileAndSelectFrame(); controller.reset(); expect( controller.dataNotifier.value, equals(CpuProfilerController.baseStateCpuProfileData), ); expect(controller.selectedCpuStackFrameNotifier.value, isNull); expect(controller.processingNotifier.value, isFalse); }); test('disposes', () { controller.dispose(); expect(() { controller.dataNotifier.addListener(() {}); }, throwsA(anything)); expect(() { controller.selectedCpuStackFrameNotifier.addListener(() {}); }, throwsA(anything)); expect(() { controller.processingNotifier.addListener(() {}); }, throwsA(anything)); }); }); }
devtools/packages/devtools_app/test/cpu_profiler_controller_test.dart/0
{'file_path': 'devtools/packages/devtools_app/test/cpu_profiler_controller_test.dart', 'repo_id': 'devtools', 'token_count': 2878}
// 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:devtools_app/src/debugger/hover.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; const _textSpan = TextSpan(children: [ TextSpan(text: 'hello', style: TextStyle(fontWeight: FontWeight.bold)), TextSpan(text: ' '), TextSpan(text: 'world'), TextSpan(text: ' '), TextSpan(text: 'foo', style: TextStyle(fontWeight: FontWeight.bold)), TextSpan(text: '.'), TextSpan(text: 'bar'), TextSpan(text: '.'), TextSpan(text: 'baz', style: TextStyle(fontWeight: FontWeight.w100)), TextSpan(text: ' '), TextSpan(text: 'blah'), ]); void main() { test('wordForHover returns the correct word given the provided x offset', () { expect(wordForHover(10, _textSpan), 'hello'); expect(wordForHover(100, _textSpan), 'world'); expect(wordForHover(5000, _textSpan), ''); }); test('wordForHover returns an empty string if there is no underlying word', () { expect(wordForHover(5000, _textSpan), ''); }); test('wordForHover merges words linked with `.`', () { expect(wordForHover(200, _textSpan), 'foo'); expect(wordForHover(250, _textSpan), 'foo.bar'); expect(wordForHover(300, _textSpan), 'foo.bar.baz'); }); }
devtools/packages/devtools_app/test/hover_test.dart/0
{'file_path': 'devtools/packages/devtools_app/test/hover_test.dart', 'repo_id': 'devtools', 'token_count': 509}
// 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:async'; import 'dart:convert'; import 'dart:io'; import 'package:devtools_shared/devtools_shared.dart'; import 'package:devtools_testing/support/file_utils.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:meta/meta.dart'; import 'package:vm_service/vm_service.dart'; import '../support/chrome.dart'; import '../support/cli_test_driver.dart'; import '../support/devtools_server_driver.dart'; import '../support/utils.dart'; import 'integration.dart'; CliAppFixture appFixture; DevToolsServerDriver server; final Map<String, Completer<Map<String, dynamic>>> completers = {}; final StreamController<Map<String, dynamic>> eventController = StreamController.broadcast(); /// A broadcast stream of events from the server. /// /// Listening for "server.started" events on this stream may be unreliable because /// it may have occurred before the test starts. Use `serverStartedEvent` instead. Stream<Map<String, dynamic>> get events => eventController.stream; Future<Map<String, dynamic>> serverStartedEvent; final Map<String, String> registeredServices = {}; // A list of PIDs for Chrome instances spawned by tests that should be // cleaned up. final List<int> browserPids = []; void main() { // ignore: unused_local_variable final bool testInReleaseMode = Platform.environment['WEBDEV_RELEASE'] == 'true'; setUpAll(() async { // Clear the existing build directory. if (Directory('build').existsSync()) { Directory('build').deleteSync(recursive: true); } // Build the app, as the server can't start without the build output. await WebBuildFixture.build(verbose: true); // The devtools package build directory needs to reflect the latest // devtools_app package contents. if (Directory('../devtools/build').existsSync()) { Directory('../devtools/build').deleteSync(recursive: true); } Directory('build/web').renameSync('../devtools/build'); }); setUp(() async { compensateForFlutterTestDirectoryBug(); // Start the command-line server. server = await DevToolsServerDriver.create(); // Fail tests on any stderr. server.stderr.listen((text) => throw 'STDERR: $text'); server.stdout.listen((map) { if (map.containsKey('id')) { if (map.containsKey('result')) { completers[map['id']].complete(map['result']); } else { completers[map['id']].completeError(map['error']); } } else if (map.containsKey('event')) { eventController.add(map); } }); serverStartedEvent = events.firstWhere((map) => map['event'] == 'server.started'); await _startApp(); }); tearDown(() async { browserPids ..forEach(Process.killPid) ..clear(); server?.kill(); await appFixture?.teardown(); }); test('registers service', () async { final serverResponse = await _send('vm.register', {'uri': appFixture.serviceUri.toString()}); expect(serverResponse['success'], isTrue); // Expect the VM service to see the launchDevTools service registered. expect(registeredServices, contains('launchDevTools')); }, timeout: const Timeout.factor(10)); test('can bind to next available port', () async { final server1 = await DevToolsServerDriver.create(port: 8855); try { // Wait for the first server to start up and ensure it got the // expected port. final event1 = await server1.stdout .firstWhere((map) => map['event'] == 'server.started'); expect(event1['params']['port'], equals(8855)); // Now spawn another requesting the same port and ensure it got the next // port number. final server2 = await DevToolsServerDriver.create(port: 8855, tryPorts: 2); try { final event2 = await server2.stdout .firstWhere((map) => map['event'] == 'server.started'); expect(event2['params']['port'], equals(8856)); } finally { server2.kill(); } } finally { server1.kill(); } }, timeout: const Timeout.factor(10)); test('does not allow embedding without flag', () async { final server = await DevToolsServerDriver.create(); final httpClient = HttpClient(); try { final startedEvent = await server.stdout .firstWhere((map) => map['event'] == 'server.started'); final host = startedEvent['params']['host']; final port = startedEvent['params']['port']; final req = await httpClient.get(host, port, '/'); final resp = await req.close(); expect(resp.headers.value('x-frame-options'), equals('SAMEORIGIN')); } finally { httpClient.close(); server.kill(); } }, timeout: const Timeout.factor(10)); test('allows embedding with flag', () async { final server = await DevToolsServerDriver.create( additionalArgs: ['--allow-embedding']); final httpClient = HttpClient(); try { final startedEvent = await server.stdout .firstWhere((map) => map['event'] == 'server.started'); final host = startedEvent['params']['host']; final port = startedEvent['params']['port']; final req = await httpClient.get(host, port, '/'); final resp = await req.close(); expect(resp.headers.value('x-frame-options'), isNull); } finally { httpClient.close(); server.kill(); } }, timeout: const Timeout.factor(10)); test('Analytics Survey', () async { var serverResponse = await _send('devTools.survey', { 'surveyRequest': 'copyAndCreateDevToolsFile', }); expect(serverResponse, isNotNull); expect(serverResponse['sucess'], isTrue); serverResponse = await _send('devTools.survey', { 'surveyRequest': apiSetActiveSurvey, 'value': 'Q3-2019', }); expect(serverResponse, isNotNull); expect(serverResponse['sucess'], isTrue); expect(serverResponse['activeSurvey'], 'Q3-2019'); serverResponse = await _send('devTools.survey', { 'surveyRequest': apiIncrementSurveyShownCount, }); expect(serverResponse, isNotNull); expect(serverResponse['activeSurvey'], 'Q3-2019'); expect(serverResponse['surveyShownCount'], equals(1)); serverResponse = await _send('devTools.survey', { 'surveyRequest': apiIncrementSurveyShownCount, }); expect(serverResponse, isNotNull); expect(serverResponse['activeSurvey'], 'Q3-2019'); expect(serverResponse['surveyShownCount'], equals(2)); serverResponse = await _send('devTools.survey', { 'surveyRequest': apiGetSurveyShownCount, }); expect(serverResponse, isNotNull); expect(serverResponse['activeSurvey'], 'Q3-2019'); expect(serverResponse['surveyShownCount'], equals(2)); serverResponse = await _send('devTools.survey', { 'surveyRequest': apiGetSurveyActionTaken, }); expect(serverResponse, isNotNull); expect(serverResponse['activeSurvey'], 'Q3-2019'); expect(serverResponse['surveyActionTaken'], isFalse); serverResponse = await _send('devTools.survey', { 'surveyRequest': apiSetSurveyActionTaken, 'value': json.encode(true), }); expect(serverResponse, isNotNull); expect(serverResponse['activeSurvey'], 'Q3-2019'); expect(serverResponse['surveyActionTaken'], isTrue); serverResponse = await _send('devTools.survey', { 'surveyRequest': 'restoreDevToolsFile', }); expect(serverResponse, isNotNull); expect(serverResponse['sucess'], isTrue); expect( serverResponse['content'], '{\n' ' \"Q3-2019\": {\n' ' \"surveyActionTaken\": true,\n' ' \"surveyShownCount\": 2\n' ' }\n' '}\n', ); }, timeout: const Timeout.factor(10)); for (final bool useVmService in [true, false]) { group('Server (${useVmService ? 'VM Service' : 'API'})', () { test( 'DevTools connects back to server API and registers that it is connected', () async { // Register the VM. await _send('vm.register', {'uri': appFixture.serviceUri.toString()}); // Send a request to launch DevTools in a browser. await _sendLaunchDevToolsRequest(useVmService: useVmService); final serverResponse = await _waitForClients(requiredConnectionState: true); expect(serverResponse, isNotNull); expect(serverResponse['clients'], hasLength(1)); expect(serverResponse['clients'][0]['hasConnection'], isTrue); expect(serverResponse['clients'][0]['vmServiceUri'], equals(appFixture.serviceUri.toString())); }, timeout: const Timeout.factor(10)); test('can launch on a specific page', () async { // Register the VM. await _send('vm.register', {'uri': appFixture.serviceUri.toString()}); // Send a request to launch at a certain page. await _sendLaunchDevToolsRequest( useVmService: useVmService, page: 'memory'); final serverResponse = await _waitForClients(requiredPage: 'memory'); expect(serverResponse, isNotNull); expect(serverResponse['clients'], hasLength(1)); expect(serverResponse['clients'][0]['hasConnection'], isTrue); expect(serverResponse['clients'][0]['vmServiceUri'], equals(appFixture.serviceUri.toString())); expect(serverResponse['clients'][0]['currentPage'], equals('memory')); }, timeout: const Timeout.factor(10)); test('can switch page', () async { await _send('vm.register', {'uri': appFixture.serviceUri.toString()}); // Launch on the memory page and wait for the connection. await _sendLaunchDevToolsRequest( useVmService: useVmService, page: 'memory'); await _waitForClients(requiredPage: 'memory'); // Re-launch, allowing reuse and with a different page. await _sendLaunchDevToolsRequest( useVmService: useVmService, reuseWindows: true, page: 'logging'); final serverResponse = await _waitForClients(requiredPage: 'logging'); expect(serverResponse, isNotNull); expect(serverResponse['clients'], hasLength(1)); expect(serverResponse['clients'][0]['hasConnection'], isTrue); expect(serverResponse['clients'][0]['vmServiceUri'], equals(appFixture.serviceUri.toString())); expect(serverResponse['clients'][0]['currentPage'], equals('logging')); }, timeout: const Timeout.factor(10)); test('DevTools reports disconnects from a VM', () async { // Register the VM. await _send('vm.register', {'uri': appFixture.serviceUri.toString()}); // Send a request to launch DevTools in a browser. await _sendLaunchDevToolsRequest(useVmService: useVmService); // Wait for the DevTools to inform server that it's connected. await _waitForClients(requiredConnectionState: true); // Terminate the VM. await appFixture.teardown(); // Ensure the client is marked as disconnected. final serverResponse = await _waitForClients(requiredConnectionState: false); expect(serverResponse['clients'], hasLength(1)); expect(serverResponse['clients'][0]['hasConnection'], isFalse); expect(serverResponse['clients'][0]['vmServiceUri'], isNull); }, timeout: const Timeout.factor(10)); test('server removes clients that disconnect from the API', () async { final event = await serverStartedEvent; // Spawn our own Chrome process so we can terminate it. final devToolsUri = 'http://${event['params']['host']}:${event['params']['port']}'; final chrome = await Chrome.locate().start(url: devToolsUri); // Wait for DevTools to inform server that it's connected. await _waitForClients(); // Close the browser, which will disconnect DevTools SSE connection // back to the server. chrome.kill(); // Ensure the client is completely removed from the list. await _waitForClients(expectNone: true); }, timeout: const Timeout.factor(10)); test('Server reuses DevTools instance if already connected to same VM', () async { // Register the VM. await _send('vm.register', {'uri': appFixture.serviceUri.toString()}); // Send a request to launch DevTools in a browser. await _sendLaunchDevToolsRequest(useVmService: useVmService); { final serverResponse = await _waitForClients(requiredConnectionState: true); expect(serverResponse['clients'], hasLength(1)); } // Request again, allowing reuse, and server emits an event saying the // window was reused. final launchResponse = await _sendLaunchDevToolsRequest( useVmService: useVmService, reuseWindows: true); expect(launchResponse['reused'], isTrue); // Ensure there's still only one connection (eg. we didn't spawn a new one // we reused the existing one). final serverResponse = await _waitForClients(requiredConnectionState: true); expect(serverResponse['clients'], hasLength(1)); }, timeout: const Timeout.factor(10)); test('Server does not reuses DevTools instance if embedded', () async { // Register the VM. await _send('vm.register', {'uri': appFixture.serviceUri.toString()}); // Spawn an embedded version of DevTools in a browser. final event = await serverStartedEvent; final devToolsUri = 'http://${event['params']['host']}:${event['params']['port']}'; final launchUrl = '$devToolsUri/?embed=true&page=logging' '&uri=${Uri.encodeQueryComponent(appFixture.serviceUri.toString())}'; final chrome = await Chrome.locate().start(url: launchUrl); try { { final serverResponse = await _waitForClients(requiredConnectionState: true); expect(serverResponse['clients'], hasLength(1)); } // Send a request to the server to launch and ensure it did // not reuse the existing connection. Launch it on a different page // so we can easily tell once this one has connected. final launchResponse = await _sendLaunchDevToolsRequest( useVmService: useVmService, reuseWindows: true, page: 'memory'); expect(launchResponse['reused'], isFalse); // Ensure there's now two connections. final serverResponse = await _waitForClients( requiredConnectionState: true, requiredPage: 'memory'); expect(serverResponse['clients'], hasLength(2)); } finally { chrome?.kill(); } }, timeout: const Timeout.factor(10)); test('Server reuses DevTools instance if not connected to a VM', () async { // Register the VM. await _send('vm.register', {'uri': appFixture.serviceUri.toString()}); // Send a request to launch DevTools in a browser. await _sendLaunchDevToolsRequest(useVmService: useVmService); // Wait for the DevTools to inform server that it's connected. await _waitForClients(requiredConnectionState: true); // Terminate the VM. await appFixture.teardown(); // Ensure the client is marked as disconnected. await _waitForClients(requiredConnectionState: false); // Start up a new app. await _startApp(); await _send('vm.register', {'uri': appFixture.serviceUri.toString()}); // Send a new request to launch. await _sendLaunchDevToolsRequest( useVmService: useVmService, reuseWindows: true); // Ensure we now have a single connected client. final serverResponse = await _waitForClients(requiredConnectionState: true); expect(serverResponse['clients'], hasLength(1)); expect(serverResponse['clients'][0]['hasConnection'], isTrue); expect(serverResponse['clients'][0]['vmServiceUri'], equals(appFixture.serviceUri.toString())); }, timeout: const Timeout.factor(10)); // The API only works in release mode. // TODO(kenz): enable integration tests. // See https://github.com/flutter/devtools/issues/2595. }, skip: true /*!testInReleaseMode*/); } } Future<Map<String, dynamic>> _sendLaunchDevToolsRequest({ @required bool useVmService, String page, bool reuseWindows = false, }) async { final launchEvent = events.where((e) => e['event'] == 'client.launch').first; if (useVmService) { await appFixture.serviceConnection.callMethod( registeredServices['launchDevTools'], args: { 'reuseWindows': reuseWindows, 'page': page, }, ); } else { await _send('devTools.launch', { 'vmServiceUri': appFixture.serviceUri.toString(), 'reuseWindows': reuseWindows, 'page': page, }); } final response = await launchEvent; final pid = response['params']['pid']; if (pid != null) { browserPids.add(pid); } return response['params']; } Future<void> _startApp() async { appFixture = await CliAppFixture.create('test/fixtures/empty_app.dart'); // TODO(dantup): When the stable versions of Dart + Flutter are >= v3.22 // of the VM Service (July 2019), the _Service option here can be removed. final serviceStreamName = await appFixture.serviceConnection.serviceStreamName; // Track services method names as they're registered. appFixture.serviceConnection .onEvent(serviceStreamName) .where((e) => e.kind == EventKind.kServiceRegistered) .listen((e) => registeredServices[e.service] = e.method); await appFixture.serviceConnection.streamListen(serviceStreamName); } int nextId = 0; Future<Map<String, dynamic>> _send(String method, [Map<String, dynamic> params]) { final id = (nextId++).toString(); completers[id] = Completer<Map<String, dynamic>>(); server.write({'id': id.toString(), 'method': method, 'params': params}); return completers[id].future; } // It may take time for the servers client list to be updated as the web app // connects, so this helper just polls waiting for the expected state and // then returns the client list. Future<Map<String, dynamic>> _waitForClients({ bool requiredConnectionState, String requiredPage, bool expectNone = false, }) async { Map<String, dynamic> serverResponse; String timeoutMessage = expectNone ? 'Server returned clients' : 'Server did not return any known clients'; if (requiredConnectionState != null) { timeoutMessage += requiredConnectionState ? ' that are connected' : ' that are not connected'; } if (requiredPage != null) { timeoutMessage += ' that are on page $requiredPage'; } final isOnPage = (client) => client['currentPage'] == requiredPage; final hasConnectionState = (client) => requiredConnectionState // If we require a connected client, also require a non-null page. This // avoids a race in tests where we may proceed to send messages to a client // that is not fully initialised. ? (client['hasConnection'] && client['currentPage'] != null) : !client['hasConnection']; await waitFor( () async { // Await a short delay to give the client time to connect. await delay(); serverResponse = await _send('client.list'); final clients = serverResponse['clients']; return clients is List && (clients.isEmpty == expectNone) && (requiredPage == null || clients.any(isOnPage)) && (requiredConnectionState == null || clients.any(hasConnectionState)); }, timeoutMessage: timeoutMessage, delay: const Duration(seconds: 1), ); return serverResponse; }
devtools/packages/devtools_app/test/integration_tests/server_test.dart/0
{'file_path': 'devtools/packages/devtools_app/test/integration_tests/server_test.dart', 'repo_id': 'devtools', 'token_count': 7319}
// 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 'package:flutter_test/flutter_test.dart'; /* import 'package:devtools_testing/logging_controller_test.dart'; import 'package:devtools_testing/support/flutter_test_driver.dart' show FlutterRunConfiguration; import 'package:devtools_testing/support/flutter_test_environment.dart'; */ void main() async { // TODO(#1987): rewrite this test for the flutter app. /* final FlutterTestEnvironment env = FlutterTestEnvironment( const FlutterRunConfiguration(withDebugger: true), testAppDirectory: 'fixtures/flutter_error_app', ); await runLoggingControllerTests(env); */ }
devtools/packages/devtools_app/test/logging_controller_fixture_test.dart/0
{'file_path': 'devtools/packages/devtools_app/test/logging_controller_fixture_test.dart', 'repo_id': 'devtools', 'token_count': 242}
// 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/performance/performance_utils.dart'; import 'package:devtools_testing/support/performance_test_data.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { group('PerformanceUtils', () { test('computeEventGroupKey for event with a set groupKey', () async { expect( PerformanceUtils.computeEventGroupKey(httpEvent, threadNamesById), equals('HTTP/client'), ); }); test('computeEventGroupKey for UI event', () async { expect( PerformanceUtils.computeEventGroupKey( goldenUiTimelineEvent, threadNamesById), equals('UI'), ); }); test('computeEventGroupKey for Raster event', () async { expect( PerformanceUtils.computeEventGroupKey( goldenRasterTimelineEvent, threadNamesById), equals('Raster'), ); }); test('computeEventGroupKey for Async event', () async { expect( PerformanceUtils.computeEventGroupKey( goldenAsyncTimelineEvent, threadNamesById), equals('A'), ); // A child async event should return the key of its root. expect( PerformanceUtils.computeEventGroupKey(asyncEventB, threadNamesById), equals('A')); }); test('computeEventGroupKey for event with named thread', () { expect( PerformanceUtils.computeEventGroupKey( eventForNamedThread, threadNamesById), equals('io.flutter.1.platform (775)'), ); }); test('computeEventGroupKey for unknown event', () async { expect( PerformanceUtils.computeEventGroupKey(unknownEvent, threadNamesById), equals('Unknown'), ); }); test('event bucket compare', () { expect(PerformanceUtils.eventGroupComparator('UI', 'Raster'), equals(-1)); expect(PerformanceUtils.eventGroupComparator('Raster', 'UI'), equals(1)); expect(PerformanceUtils.eventGroupComparator('UI', 'UI'), equals(0)); expect(PerformanceUtils.eventGroupComparator('UI', 'Async'), equals(-1)); expect(PerformanceUtils.eventGroupComparator('A', 'B'), equals(-1)); expect(PerformanceUtils.eventGroupComparator('Z', 'Unknown'), equals(1)); expect(PerformanceUtils.eventGroupComparator('Unknown', 'Unknown'), equals(0)); expect(PerformanceUtils.eventGroupComparator('Unknown', 'Unknown (1234)'), equals(-1)); expect( PerformanceUtils.eventGroupComparator( 'Unknown (2345)', 'Unknown (1234)'), equals(1)); expect(PerformanceUtils.eventGroupComparator('Unknown', 'Warm up shader'), equals(1)); expect(PerformanceUtils.eventGroupComparator('UI', 'SHADE'), equals(1)); expect( PerformanceUtils.eventGroupComparator('Raster', 'SHADE'), equals(1)); expect(PerformanceUtils.eventGroupComparator('SHADE', 'Warm up shader'), equals(-1)); expect(PerformanceUtils.eventGroupComparator('Warm up shader', 'A'), equals(-1)); }); }); }
devtools/packages/devtools_app/test/performance_utils_test.dart/0
{'file_path': 'devtools/packages/devtools_app/test/performance_utils_test.dart', 'repo_id': 'devtools', 'token_count': 1229}
// 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/performance/performance_controller.dart'; import 'package:devtools_app/src/performance/performance_model.dart'; import 'package:devtools_app/src/performance/timeline_event_processor.dart'; import 'package:devtools_app/src/trace_event.dart'; import 'package:devtools_app/src/utils.dart'; import 'package:devtools_testing/support/performance_test_data.dart'; import 'package:devtools_testing/support/test_utils.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/mockito.dart'; void main() { final originalGoldenUiEvent = goldenUiTimelineEvent.deepCopy(); final originalGoldenGpuEvent = goldenRasterTimelineEvent.deepCopy(); final originalGoldenUiTraceEvents = List.of(goldenUiTraceEvents); final originalGoldenGpuTraceEvents = List.of(goldenRasterTraceEvents); setUp(() { // If any of these expect statements fail, a golden was modified while the // tests were running. Do not modify the goldens. Instead, make a copy and // modify the copy. expect(originalGoldenUiEvent.toString(), equals(goldenUiString)); expect(originalGoldenGpuEvent.toString(), equals(goldenRasterString)); expect( collectionEquals(goldenUiTraceEvents, originalGoldenUiTraceEvents), isTrue, ); expect( collectionEquals(goldenRasterTraceEvents, originalGoldenGpuTraceEvents), isTrue, ); }); group('TimelineProcessor', () { TimelineEventProcessor processor; setUp(() { processor = TimelineEventProcessor(MockTimelineController()) ..primeThreadIds( uiThreadId: testUiThreadId, rasterThreadId: testRasterThreadId, ); }); test('creates one new frame per id', () async { await processor.processTimeline( [frameStartEvent, frameEndEvent], resetAfterProcessing: false, ); expect(processor.pendingFrames.length, equals(1)); expect(processor.pendingFrames.containsKey('PipelineItem-f1'), isTrue); }); test('duration trace events form timeline event tree', () async { await processor.processTimeline(goldenUiTraceEvents); final processedUiEvent = processor.timelineController.data.timelineEvents.first; expect(processedUiEvent.toString(), equals(goldenUiString)); }); test('frame events satisfy ui gpu order', () { const frameStartTime = 2000; const frameEndTime = 8000; FlutterFrame frame = FlutterFrame('frameId') ..pipelineItemTime.start = const Duration(microseconds: frameStartTime) ..pipelineItemTime.end = const Duration(microseconds: frameEndTime); // Satisfies UI / GPU order. final uiEvent = goldenUiTimelineEvent.deepCopy() ..time = (TimeRange() ..start = const Duration(microseconds: 5000) ..end = const Duration(microseconds: 6000)); final rasterEvent = goldenRasterTimelineEvent.deepCopy() ..time = (TimeRange() ..start = const Duration(microseconds: 4000) ..end = const Duration(microseconds: 8000)); expect(processor.satisfiesUiRasterOrder(uiEvent, frame), isTrue); expect(processor.satisfiesUiRasterOrder(rasterEvent, frame), isTrue); frame.setEventFlow(uiEvent, type: TimelineEventType.ui); expect(processor.satisfiesUiRasterOrder(rasterEvent, frame), isFalse); frame = FlutterFrame('frameId') ..pipelineItemTime.start = const Duration(microseconds: frameStartTime) ..pipelineItemTime.end = const Duration(microseconds: frameEndTime); frame ..setEventFlow(null, type: TimelineEventType.ui) ..setEventFlow(rasterEvent, type: TimelineEventType.raster); expect(processor.satisfiesUiRasterOrder(uiEvent, frame), isFalse); }); test( 'UI event flow sets end frame time if it completes after raster event flow', () { final uiEvent = goldenUiTimelineEvent.deepCopy() ..time = (TimeRange() ..start = const Duration(microseconds: 5000) ..end = const Duration(microseconds: 8000)); final rasterEvent = goldenRasterTimelineEvent.deepCopy() ..time = (TimeRange() ..start = const Duration(microseconds: 6000) ..end = const Duration(microseconds: 7000)); final frame = FlutterFrame('frameId'); frame.setEventFlow(rasterEvent, type: TimelineEventType.raster); expect(frame.time.start, isNull); expect(frame.time.end, isNull); frame.setEventFlow(uiEvent, type: TimelineEventType.ui); expect(frame.time.start, equals(const Duration(microseconds: 5000))); expect(frame.time.end, equals(const Duration(microseconds: 8000))); }); test('frame completed', () async { await processor.processTimeline([ frameStartEvent, ...goldenUiTraceEvents, ...goldenRasterTraceEvents, frameEndEvent, ]); expect(processor.pendingFrames.length, equals(0)); expect(processor.timelineController.data.frames.length, equals(1)); final frame = processor.timelineController.data.frames.first; expect(frame.uiEventFlow.toString(), equals(goldenUiString)); expect(frame.rasterEventFlow.toString(), equals(goldenRasterString)); expect(frame.isReadyForTimeline, isTrue); }); test('handles trace event duplicates', () async { // Duplicate duration begin event. // VSYNC // Animator::BeginFrame // Animator::BeginFrame // ... // Animator::BeginFrame // VSYNC var traceEvents = List.of(goldenUiTraceEvents); traceEvents.insert(1, goldenUiTraceEvents[1]); await processor.processTimeline(traceEvents); expect( processor.timelineController.data.timelineEvents.length, equals(1)); expect( processor.timelineController.data.timelineEvents.first.toString(), equals(goldenUiString), ); await processor.timelineController.clearData(); // Duplicate duration end event. // VSYNC // Animator::BeginFrame // ... // Animator::BeginFrame // Animator::BeginFrame // VSYNC traceEvents = List.of(goldenUiTraceEvents); traceEvents.insert(goldenUiTraceEvents.length - 2, goldenUiTraceEvents[goldenUiTraceEvents.length - 2]); await processor.processTimeline(traceEvents); expect( processor.timelineController.data.timelineEvents.length, equals(1)); expect( processor.timelineController.data.timelineEvents.first.toString(), equals(goldenUiString), ); await processor.timelineController.clearData(); // Unrecoverable state resets event tracking. // VSYNC // Animator::BeginFrame // VSYNC // Animator::BeginFrame // ... // Animator::BeginFrame // VSYNC final vsyncEvent = testTraceEventWrapper({ 'name': 'VSYNC', 'cat': 'Embedder', 'tid': testUiThreadId, 'pid': 94955, 'ts': 118039650802, 'ph': 'B', 'args': {} }); final animatorBeginFrameEvent = testTraceEventWrapper({ 'name': 'Animator::BeginFrame', 'cat': 'Embedder', 'tid': testUiThreadId, 'pid': 94955, 'ts': 118039650802, 'ph': 'B', 'args': {} }); traceEvents = [ vsyncEvent, animatorBeginFrameEvent, vsyncEvent, animatorBeginFrameEvent ]; traceEvents .addAll(goldenUiTraceEvents.getRange(2, goldenUiTraceEvents.length)); traceEvents.insert(2, goldenUiTraceEvents[0]); traceEvents.insert(3, goldenUiTraceEvents[1]); await processor.processTimeline(traceEvents); expect( processor.currentDurationEventNodes[TimelineEventType.ui.index], isNull, ); }); test('processes all events', () async { final traceEvents = [ ...asyncTraceEvents, ...goldenUiTraceEvents, ...goldenRasterTraceEvents, ]; expect( processor.timelineController.data.timelineEvents, isEmpty, ); await processor.processTimeline(traceEvents); expect( processor.timelineController.data.timelineEvents.length, equals(4), ); expect( processor.timelineController.data.timelineEvents[0].toString(), equals(goldenAsyncString), ); expect( processor.timelineController.data.timelineEvents[1].toString(), equals(' D [193937061035 μs - 193938741076 μs]\n'), ); expect( processor.timelineController.data.timelineEvents[2].toString(), equals(goldenUiString), ); expect( processor.timelineController.data.timelineEvents[3].toString(), equals(goldenRasterString), ); }); test('processes trace with duplicate events', () async { expect( processor.timelineController.data.timelineEvents, isEmpty, ); await processor.processTimeline(durationEventsWithDuplicateTraces); // If the processor is not handling duplicates properly, this value would // be 0. expect( processor.timelineController.data.timelineEvents.length, equals(1), ); }); test( 'processes trace with children with different ids does not throw assert', () async { // This test should complete without throwing an assert from // `AsyncTimelineEvent.endAsyncEvent`. await processor.processTimeline(asyncEventsWithChildrenWithDifferentIds); }); test('inferEventType', () { expect( processor.inferEventType(asyncStartATrace.event), equals(TimelineEventType.async), ); expect( processor.inferEventType(asyncEndATrace.event), equals(TimelineEventType.async), ); expect( processor.inferEventType(vsyncTrace.event), equals(TimelineEventType.ui), ); expect( processor.inferEventType(gpuRasterizerDrawTrace.event), equals(TimelineEventType.raster), ); expect( processor.inferEventType(unknownEventBeginTrace.event), equals(TimelineEventType.unknown), ); }); }); } class MockTimelineController extends Mock implements PerformanceController { @override final data = PerformanceData(); @override void addTimelineEvent(TimelineEvent event) { data.addTimelineEvent(event); } @override void addFrame(FlutterFrame frame) { data.frames.add(frame); } @override Future<void> clearData({bool clearVmTimeline = true}) async { data.clear(); } }
devtools/packages/devtools_app/test/timeline_processor_test.dart/0
{'file_path': 'devtools/packages/devtools_app/test/timeline_processor_test.dart', 'repo_id': 'devtools', 'token_count': 4270}
name: devtools_server description: A server that supports Dart DevTools. # 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: args: ^2.0.0 browser_launcher: ^1.0.0 devtools_shared: 2.3.3-dev.1 intl: '>=0.16.1 <0.18.0' path: ^1.8.0 sse: ^4.0.0 shelf: ^1.1.0 shelf_proxy: ^1.0.0 shelf_static: ^1.0.0 http_multi_server: ^3.0.0 vm_service: ^7.1.0 collection: ^1.15.0 dependency_overrides: # The "#OVERRIDE_FOR_DEVELOPMENT" lines are stripped out when we publish. # All overriden dependencies are published together so there is no harm # in treating them like they are part of a mono-repo while developing. devtools_shared: #OVERRIDE_FOR_DEVELOPMENT path: ../devtools_shared #OVERRIDE_FOR_DEVELOPMENT
devtools/packages/devtools_server/pubspec.yaml/0
{'file_path': 'devtools/packages/devtools_server/pubspec.yaml', 'repo_id': 'devtools', 'token_count': 368}
// 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:convert'; import 'dart:io'; import 'package:path/path.dart' as path; import 'package:usage/usage_io.dart'; import 'file_system.dart'; /// Access the file '~/.flutter'. class FlutterUsage { FlutterUsage({String settingsName = 'flutter'}) { _analytics = AnalyticsIO('', settingsName, ''); } late Analytics _analytics; /// Does the .flutter store exist? static bool get doesStoreExist { return LocalFileSystem.flutterStoreExists(); } bool get isFirstRun => _analytics.firstRun; bool get enabled => _analytics.enabled; set enabled(bool value) => _analytics.enabled = value; String get clientId => _analytics.clientId; } // Access the DevTools on disk store (~/.devtools/.devtools). class DevToolsUsage { DevToolsUsage() { LocalFileSystem.maybeMoveLegacyDevToolsStore(); properties = IOPersistentProperties( storeName, documentDirPath: LocalFileSystem.devToolsDir(), ); } static const storeName = '.devtools'; /// The activeSurvey is the property name of a top-level property /// existing or created in the file ~/.devtools /// If the property doesn't exist it is created with default survey values: /// /// properties[activeSurvey]['surveyActionTaken'] = false; /// properties[activeSurvey]['surveyShownCount'] = 0; /// /// It is a requirement that the API apiSetActiveSurvey must be called before /// calling any survey method on DevToolsUsage (addSurvey, rewriteActiveSurvey, /// surveyShownCount, incrementSurveyShownCount, or surveyActionTaken). String? _activeSurvey; late IOPersistentProperties properties; static const _surveyActionTaken = 'surveyActionTaken'; static const _surveyShownCount = 'surveyShownCount'; void reset() { properties.remove('firstRun'); properties['enabled'] = false; } bool get isFirstRun { properties['firstRun'] = properties['firstRun'] == null; return properties['firstRun']; } bool get enabled { if (properties['enabled'] == null) { properties['enabled'] = false; } return properties['enabled']; } set enabled(bool value) { properties['enabled'] = value; return properties['enabled']; } bool surveyNameExists(String surveyName) => properties[surveyName] != null; void _addSurvey(String surveyName) { assert(activeSurvey != null); assert(activeSurvey == surveyName); rewriteActiveSurvey(false, 0); } String? get activeSurvey => _activeSurvey; set activeSurvey(String? surveyName) { assert(surveyName != null); _activeSurvey = surveyName; if (!surveyNameExists(activeSurvey!)) { // Create the survey if property is non-existent in ~/.devtools _addSurvey(activeSurvey!); } } /// Need to rewrite the entire survey structure for property to be persisted. void rewriteActiveSurvey(bool actionTaken, int shownCount) { assert(activeSurvey != null); properties[activeSurvey!] = { _surveyActionTaken: actionTaken, _surveyShownCount: shownCount, }; } int get surveyShownCount { assert(activeSurvey != null); final prop = properties[activeSurvey!]; if (prop[_surveyShownCount] == null) { rewriteActiveSurvey(prop[_surveyActionTaken], 0); } return properties[activeSurvey!][_surveyShownCount]; } void incrementSurveyShownCount() { assert(activeSurvey != null); surveyShownCount; // Ensure surveyShownCount has been initialized. final prop = properties[activeSurvey!]; rewriteActiveSurvey(prop[_surveyActionTaken], prop[_surveyShownCount] + 1); } bool get surveyActionTaken { assert(activeSurvey != null); return properties[activeSurvey!][_surveyActionTaken] == true; } set surveyActionTaken(bool value) { assert(activeSurvey != null); final prop = properties[activeSurvey!]; rewriteActiveSurvey(value, prop[_surveyShownCount]); } } abstract class PersistentProperties { PersistentProperties(this.name); final String name; dynamic operator [](String key); void operator []=(String key, dynamic value); /// Re-read settings from the backing store. /// /// May be a no-op on some platforms. void syncSettings(); } const JsonEncoder _jsonEncoder = JsonEncoder.withIndent(' '); class IOPersistentProperties extends PersistentProperties { IOPersistentProperties( String name, { String? documentDirPath, }) : super(name) { final String fileName = name.replaceAll(' ', '_'); documentDirPath ??= LocalFileSystem.devToolsDir(); _file = File(path.join(documentDirPath, fileName)); if (!_file.existsSync()) { _file.createSync(recursive: true); } syncSettings(); } IOPersistentProperties.fromFile(File file) : super(path.basename(file.path)) { _file = file; if (!_file.existsSync()) { _file.createSync(recursive: true); } syncSettings(); } late File _file; late Map _map; @override dynamic operator [](String key) => _map[key]; @override void operator []=(String key, dynamic value) { if (value == null && !_map.containsKey(key)) return; if (_map[key] == value) return; if (value == null) { _map.remove(key); } else { _map[key] = value; } try { _file.writeAsStringSync(_jsonEncoder.convert(_map) + '\n'); } catch (_) {} } @override void syncSettings() { try { String contents = _file.readAsStringSync(); if (contents.isEmpty) contents = '{}'; _map = jsonDecode(contents); } catch (_) { _map = {}; } } void remove(String propertyName) { _map.remove(propertyName); } }
devtools/packages/devtools_shared/lib/src/server/usage.dart/0
{'file_path': 'devtools/packages/devtools_shared/lib/src/server/usage.dart', 'repo_id': 'devtools', 'token_count': 1971}
// 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. export 'autocomplete_export.dart'; // ignore: unused_element int _privateFieldInOtherLibrary = 2; int publicFieldInOtherLibrary = 3; // ignore: unused_element void _privateMethodOtherLibrary() {} void publicMethodOtherLibrary() {}
devtools/packages/devtools_testing/fixtures/flutter_app/lib/src/autocomplete_helper_library.dart/0
{'file_path': 'devtools/packages/devtools_testing/fixtures/flutter_app/lib/src/autocomplete_helper_library.dart', 'repo_id': 'devtools', 'token_count': 108}
mixin Mixin { // ignore: unused_field, prefer_final_fields, the property is used for testing int _privateMixinProperty = 0; }
devtools/packages/devtools_testing/fixtures/provider_app/lib/mixin.dart/0
{'file_path': 'devtools/packages/devtools_testing/fixtures/provider_app/lib/mixin.dart', 'repo_id': 'devtools', 'token_count': 40}
// 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 'package:devtools_app/src/profiler/cpu_profile_model.dart'; import 'package:devtools_app/src/utils.dart'; final Map<String, dynamic> goldenCpuProfileDataJson = { 'type': '_CpuProfileTimeline', 'samplePeriod': 50, 'sampleCount': 8, 'stackDepth': 128, 'timeOriginMicros': 47377796685, 'timeExtentMicros': 3000, 'stackFrames': goldenCpuProfileStackFrames, 'traceEvents': goldenCpuProfileTraceEvents, }; final Map<String, dynamic> emptyCpuProfileDataJson = { 'type': '_CpuProfileTimeline', 'samplePeriod': 50, 'sampleCount': 0, 'stackDepth': 128, 'timeOriginMicros': 47377796685, 'timeExtentMicros': 0, 'stackFrames': {}, 'traceEvents': [], }; final Map<String, dynamic> cpuProfileDataWithUserTagsJson = { 'type': '_CpuProfileTimeline', 'samplePeriod': 50, 'sampleCount': 5, 'stackDepth': 128, 'timeOriginMicros': 0, 'timeExtentMicros': 250, 'stackFrames': { '140357727781376-1': { 'category': 'Dart', 'name': 'Frame1', 'resolvedUrl': '', }, '140357727781376-2': { 'category': 'Dart', 'name': 'Frame2', 'parent': '140357727781376-1', 'resolvedUrl': '', }, '140357727781376-3': { 'category': 'Dart', 'name': 'Frame3', 'parent': '140357727781376-2', 'resolvedUrl': '', }, '140357727781376-4': { 'category': 'Dart', 'name': 'Frame4', 'parent': '140357727781376-2', 'resolvedUrl': '', }, '140357727781376-5': { 'category': 'Dart', 'name': 'Frame5', 'parent': '140357727781376-1', 'resolvedUrl': '', }, '140357727781376-6': { 'category': 'Dart', 'name': 'Frame6', 'parent': '140357727781376-5', 'resolvedUrl': '', }, }, 'traceEvents': [ { 'ph': 'P', 'name': '', 'pid': 77616, 'tid': 42247, 'ts': 50, 'cat': 'Dart', 'args': { 'mode': 'basic', 'userTag': 'userTagA', }, 'sf': '140357727781376-3' }, { 'ph': 'P', 'name': '', 'pid': 77616, 'tid': 42247, 'ts': 100, 'cat': 'Dart', 'args': { 'mode': 'basic', 'userTag': 'userTagB', }, 'sf': '140357727781376-4' }, { 'ph': 'P', 'name': '', 'pid': 77616, 'tid': 42247, 'ts': 150, 'cat': 'Dart', 'args': { 'mode': 'basic', 'userTag': 'userTagA', }, 'sf': '140357727781376-5' }, { 'ph': 'P', 'name': '', 'pid': 77616, 'tid': 42247, 'ts': 200, 'cat': 'Dart', 'args': { 'mode': 'basic', 'userTag': 'userTagC', }, 'sf': '140357727781376-5' }, { 'ph': 'P', 'name': '', 'pid': 77616, 'tid': 42247, 'ts': 250, 'cat': 'Dart', 'args': { 'mode': 'basic', 'userTag': 'userTagC', }, 'sf': '140357727781376-6' }, ], }; const goldenCpuProfileString = ''' all - children: 2 - excl: 0 - incl: 8 thread_start - children: 1 - excl: 0 - incl: 2 _pthread_start - children: 1 - excl: 0 - incl: 2 _drawFrame - children: 2 - excl: 0 - incl: 2 _WidgetsFlutterBinding.draw - children: 1 - excl: 0 - incl: 1 RendererBinding.drawFrame - children: 0 - excl: 1 - incl: 1 _RenderProxyBox.paint - children: 1 - excl: 0 - incl: 1 PaintingContext.paintChild - children: 1 - excl: 0 - incl: 1 _SyncBlock.finish - children: 0 - excl: 1 - incl: 1 [Truncated] - children: 2 - excl: 0 - incl: 6 RenderObject._getSemanticsForParent.<closure> - children: 1 - excl: 0 - incl: 1 RenderObject._getSemanticsForParent - children: 0 - excl: 1 - incl: 1 RenderPhysicalModel.paint - children: 1 - excl: 0 - incl: 5 RenderCustomMultiChildLayoutBox.paint - children: 1 - excl: 0 - incl: 5 _RenderCustomMultiChildLayoutBox.defaultPaint - children: 2 - excl: 3 - incl: 5 RenderObject._paintWithContext - children: 0 - excl: 1 - incl: 1 RenderStack.paintStack - children: 1 - excl: 0 - incl: 1 Gesture._invokeFrameCallback - children: 0 - excl: 1 - incl: 1 '''; final Map<String, dynamic> cpuProfileResponseJson = { 'type': '_CpuProfileTimeline', 'samplePeriod': 50, 'stackDepth': 128, 'sampleCount': 8, 'timeSpan': 0.003678, 'timeOriginMicros': 47377796685, 'timeExtentMicros': 3000, 'stackFrames': goldenCpuProfileStackFrames, 'traceEvents': goldenCpuProfileTraceEvents, }; final Map<String, dynamic> goldenCpuProfileStackFrames = Map.from(subProfileStackFrames) ..addAll({ '140357727781376-12': { 'category': 'Dart', 'name': 'RenderPhysicalModel.paint', 'parent': '140357727781376-9', 'resolvedUrl': 'path/to/flutter/packages/flutter/lib/src/rendering/proxy_box.dart', }, '140357727781376-13': { 'category': 'Dart', 'name': 'RenderCustomMultiChildLayoutBox.paint', 'parent': '140357727781376-12', 'resolvedUrl': 'path/to/flutter/packages/flutter/lib/src/rendering/custom_layout.dart', }, '140357727781376-14': { 'category': 'Dart', 'name': '_RenderCustomMultiChildLayoutBox.defaultPaint', 'parent': '140357727781376-13', 'resolvedUrl': 'path/to/flutter/packages/flutter/lib/src/rendering/box.dart', }, '140357727781376-15': { 'category': 'Dart', 'name': 'RenderObject._paintWithContext', 'parent': '140357727781376-14', 'resolvedUrl': 'path/to/flutter/packages/flutter/lib/src/rendering/object.dart', }, '140357727781376-16': { 'category': 'Dart', 'name': 'RenderStack.paintStack', 'parent': '140357727781376-14', 'resolvedUrl': 'path/to/flutter/packages/flutter/lib/src/rendering/stack.dart', }, '140357727781376-17': { 'category': '[Stub] OneArgCheckInlineCache', 'name': '_WidgetsFlutterBinding&BindingBase&Gesture._invokeFrameCallback', 'parent': '140357727781376-16', 'resolvedUrl': '', } }); final subProfileStackFrames = { '140357727781376-1': { 'category': 'Dart', 'name': 'thread_start', 'resolvedUrl': '', }, '140357727781376-2': { 'category': 'Dart', 'name': '_pthread_start', 'parent': '140357727781376-1', 'resolvedUrl': '', }, '140357727781376-3': { 'category': 'Dart', 'name': '_drawFrame', 'parent': '140357727781376-2', 'resolvedUrl': 'org-dartlang-sdk:///flutter/lib/ui/hooks.dart', }, '140357727781376-4': { 'category': 'Dart', 'name': '_WidgetsFlutterBinding.draw', 'parent': '140357727781376-3', 'resolvedUrl': 'file:///path/to/flutter/packages/flutter/lib/src/scheduler/binding.dart', }, '140357727781376-5': { 'category': 'Dart', 'name': 'RendererBinding.drawFrame', 'parent': '140357727781376-4', 'resolvedUrl': 'path/to/flutter/packages/flutter/lib/src/rendering/binding.dart', }, '140357727781376-6': { 'category': 'Dart', 'name': '_RenderProxyBox.paint', 'parent': '140357727781376-3', 'resolvedUrl': 'path/to/flutter/packages/flutter/lib/src/rendering/proxy_box.dart', }, '140357727781376-7': { 'category': 'Dart', 'name': 'PaintingContext.paintChild', 'parent': '140357727781376-6', 'resolvedUrl': 'path/to/flutter/packages/flutter/lib/src/painting/context.dart', }, '140357727781376-8': { 'category': 'Dart', 'name': '_SyncBlock.finish', 'parent': '140357727781376-7', 'resolvedUrl': '', }, '140357727781376-9': { 'category': 'Dart', 'name': '[Truncated]', 'resolvedUrl': '', }, '140357727781376-10': { 'category': 'Dart', 'name': 'RenderObject._getSemanticsForParent.<closure>', 'parent': '140357727781376-9', 'resolvedUrl': 'file:///path/to/flutter/packages/flutter/lib/src/rendering/object.dart', }, '140357727781376-11': { 'category': 'Dart', 'name': 'RenderObject._getSemanticsForParent', 'parent': '140357727781376-10', 'resolvedUrl': 'file:///path/to/flutter/packages/flutter/lib/src/rendering/object.dart', }, }; final List<Map<String, dynamic>> goldenCpuProfileTraceEvents = List.from(subProfileTraceEvents) ..addAll([ { 'ph': 'P', 'name': '', 'pid': 77616, 'tid': 42247, 'ts': 47377800363, 'cat': 'Dart', 'args': {'mode': 'basic'}, 'sf': '140357727781376-14' }, { 'ph': 'P', 'name': '', 'pid': 77616, 'tid': 42247, 'ts': 47377800463, 'cat': 'Dart', 'args': {'mode': 'basic'}, 'sf': '140357727781376-14' }, { 'ph': 'P', 'name': '', 'pid': 77616, 'tid': 42247, 'ts': 47377800563, 'cat': 'Dart', 'args': {'mode': 'basic'}, 'sf': '140357727781376-14' }, { 'ph': 'P', 'name': '', 'pid': 77616, 'tid': 42247, 'ts': 47377800663, 'cat': 'Dart', 'args': {'mode': 'basic'}, 'sf': '140357727781376-15' }, { 'ph': 'P', 'name': '', 'pid': 77616, 'tid': 42247, 'ts': 47377800763, 'cat': 'Dart', 'args': {'mode': 'basic'}, 'sf': '140357727781376-17' } ]); final subProfileTraceEvents = [ { 'ph': 'P', 'name': '', 'pid': 77616, 'tid': 42247, 'ts': 47377796685, 'cat': 'Dart', 'args': {'mode': 'basic'}, 'sf': '140357727781376-5' }, { 'ph': 'P', 'name': '', 'pid': 77616, 'tid': 42247, 'ts': 47377797975, 'cat': 'Dart', 'args': {'mode': 'basic'}, 'sf': '140357727781376-8' }, { 'ph': 'P', 'name': '', 'pid': 77616, 'tid': 42247, 'ts': 47377799063, 'cat': 'Dart', 'args': {'mode': 'basic'}, 'sf': '140357727781376-11' }, ]; final responseWithMissingLeafFrame = { 'type': '_CpuProfileTimeline', 'samplePeriod': 1000, 'stackDepth': 128, 'sampleCount': 3, 'timeSpan': 0.003678, 'timeOriginMicros': 47377796685, 'timeExtentMicros': 3678, 'stackFrames': { // Missing stack frame 140357727781376-0 '140357727781376-1': { 'category': 'Dart', 'name': 'thread_start', 'resolvedUrl': '', }, '140357727781376-2': { 'category': 'Dart', 'name': '_pthread_start', 'parent': '140357727781376-1', 'resolvedUrl': '', }, '140357727781376-3': { 'category': 'Dart', 'name': '_drawFrame', 'parent': '140357727781376-2', 'resolvedUrl': 'org-dartlang-sdk:///flutter/lib/ui/hooks.dart', }, '140357727781376-4': { 'category': 'Dart', 'name': '_WidgetsFlutterBinding&BindingBase', 'parent': '140357727781376-3', 'resolvedUrl': 'file:///path/to/flutter/packages/flutter/lib/src/scheduler/binding.dart', }, }, 'traceEvents': [ { 'ph': 'P', 'name': '', 'pid': 77616, 'tid': 42247, 'ts': 47377796685, 'cat': 'Dart', 'args': {'mode': 'basic'}, 'sf': '140357727781376-0' }, { 'ph': 'P', 'name': '', 'pid': 77616, 'tid': 42247, 'ts': 47377797975, 'cat': 'Dart', 'args': {'mode': 'basic'}, 'sf': '140357727781376-2' }, { 'ph': 'P', 'name': '', 'pid': 77616, 'tid': 42247, 'ts': 47377799063, 'cat': 'Dart', 'args': {'mode': 'basic'}, 'sf': '140357727781376-4' }, ] }; final CpuProfileMetaData profileMetaData = CpuProfileMetaData( sampleCount: 10, samplePeriod: 50, stackDepth: 128, time: TimeRange() ..start = const Duration() ..end = const Duration(microseconds: 100), ); final CpuStackFrame stackFrameA = CpuStackFrame( id: 'id_0', name: 'A', category: 'Dart', url: '', profileMetaData: profileMetaData, )..exclusiveSampleCount = 0; final CpuStackFrame stackFrameB = CpuStackFrame( id: 'id_1', name: 'B', category: 'Dart', url: 'org-dartlang-sdk:///third_party/dart/sdk/lib/async/zone.dart', profileMetaData: profileMetaData, )..exclusiveSampleCount = 0; final CpuStackFrame stackFrameC = CpuStackFrame( id: 'id_2', name: 'C', category: 'Dart', url: 'file:///path/to/flutter/packages/flutter/lib/src/widgets/binding.dart', profileMetaData: profileMetaData, )..exclusiveSampleCount = 2; final CpuStackFrame stackFrameD = CpuStackFrame( id: 'id_3', name: 'D', category: 'Dart', url: 'url', profileMetaData: profileMetaData, )..exclusiveSampleCount = 2; final CpuStackFrame stackFrameE = CpuStackFrame( id: 'id_4', name: 'E', category: 'Dart', url: 'url', profileMetaData: profileMetaData, )..exclusiveSampleCount = 1; final CpuStackFrame stackFrameF = CpuStackFrame( id: 'id_5', name: 'F', category: 'Dart', url: 'url', profileMetaData: profileMetaData, )..exclusiveSampleCount = 0; final CpuStackFrame stackFrameF2 = CpuStackFrame( id: 'id_6', name: 'F', category: 'Dart', url: 'url', profileMetaData: profileMetaData, )..exclusiveSampleCount = 3; final CpuStackFrame stackFrameC2 = CpuStackFrame( id: 'id_7', name: 'C', category: 'Dart', url: 'file:///path/to/flutter/packages/flutter/lib/src/widgets/binding.dart', profileMetaData: profileMetaData, )..exclusiveSampleCount = 1; final CpuStackFrame stackFrameC3 = CpuStackFrame( id: 'id_8', name: 'C', category: 'Dart', url: 'file:///path/to/flutter/packages/flutter/lib/src/widgets/binding.dart', profileMetaData: profileMetaData, )..exclusiveSampleCount = 1; final CpuStackFrame stackFrameG = CpuStackFrame( id: 'id_9', name: 'G', category: 'Dart', url: 'file:///path/to/flutter/packages/flutter/lib/src/widgets/binding.dart', profileMetaData: profileMetaData, )..exclusiveSampleCount = 1; final CpuStackFrame testStackFrame = stackFrameA ..addChild(stackFrameB ..addChild(stackFrameC) ..addChild(stackFrameD ..addChild(stackFrameE..addChild(stackFrameF..addChild(stackFrameC2))) ..addChild(stackFrameF2..addChild(stackFrameC3)))); const String testStackFrameStringGolden = ''' A - children: 1 - excl: 0 - incl: 10 B - children: 2 - excl: 0 - incl: 10 C - children: 0 - excl: 2 - incl: 2 D - children: 2 - excl: 2 - incl: 8 E - children: 1 - excl: 1 - incl: 2 F - children: 1 - excl: 0 - incl: 1 C - children: 0 - excl: 1 - incl: 1 F - children: 1 - excl: 3 - incl: 4 C - children: 0 - excl: 1 - incl: 1 '''; const String bottomUpPreMergeGolden = ''' C - children: 1 - excl: 2 - incl: 2 B - children: 1 - excl: 2 - incl: 2 A - children: 0 - excl: 2 - incl: 2 D - children: 1 - excl: 2 - incl: 2 B - children: 1 - excl: 2 - incl: 2 A - children: 0 - excl: 2 - incl: 2 E - children: 1 - excl: 1 - incl: 1 D - children: 1 - excl: 1 - incl: 1 B - children: 1 - excl: 1 - incl: 1 A - children: 0 - excl: 1 - incl: 1 C - children: 1 - excl: 1 - incl: 1 F - children: 1 - excl: 1 - incl: 1 E - children: 1 - excl: 1 - incl: 1 D - children: 1 - excl: 1 - incl: 1 B - children: 1 - excl: 1 - incl: 1 A - children: 0 - excl: 1 - incl: 1 F - children: 1 - excl: 3 - incl: 3 D - children: 1 - excl: 3 - incl: 3 B - children: 1 - excl: 3 - incl: 3 A - children: 0 - excl: 3 - incl: 3 C - children: 1 - excl: 1 - incl: 1 F - children: 1 - excl: 1 - incl: 1 D - children: 1 - excl: 1 - incl: 1 B - children: 1 - excl: 1 - incl: 1 A - children: 0 - excl: 1 - incl: 1 '''; const String bottomUpGolden = ''' C - children: 2 - excl: 4 - incl: 4 B - children: 1 - excl: 2 - incl: 2 A - children: 0 - excl: 2 - incl: 2 F - children: 2 - excl: 2 - incl: 2 E - children: 1 - excl: 1 - incl: 1 D - children: 1 - excl: 1 - incl: 1 B - children: 1 - excl: 1 - incl: 1 A - children: 0 - excl: 1 - incl: 1 D - children: 1 - excl: 1 - incl: 1 B - children: 1 - excl: 1 - incl: 1 A - children: 0 - excl: 1 - incl: 1 D - children: 1 - excl: 2 - incl: 2 B - children: 1 - excl: 2 - incl: 2 A - children: 0 - excl: 2 - incl: 2 E - children: 1 - excl: 1 - incl: 1 D - children: 1 - excl: 1 - incl: 1 B - children: 1 - excl: 1 - incl: 1 A - children: 0 - excl: 1 - incl: 1 F - children: 1 - excl: 3 - incl: 3 D - children: 1 - excl: 3 - incl: 3 B - children: 1 - excl: 3 - incl: 3 A - children: 0 - excl: 3 - incl: 3 '''; final CpuProfileMetaData zeroProfileMetaData = CpuProfileMetaData( sampleCount: 0, samplePeriod: 50, stackDepth: 128, time: TimeRange() ..start = const Duration() ..end = const Duration(microseconds: 100), ); final CpuStackFrame zeroStackFrame = CpuStackFrame( id: 'id_0', name: 'A', category: 'Dart', url: '', profileMetaData: zeroProfileMetaData, )..exclusiveSampleCount = 0;
devtools/packages/devtools_testing/lib/support/cpu_profile_test_data.dart/0
{'file_path': 'devtools/packages/devtools_testing/lib/support/cpu_profile_test_data.dart', 'repo_id': 'devtools', 'token_count': 8516}
// 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:async'; import 'dart:io'; import 'package:args/command_runner.dart'; import 'package:cli_util/cli_logging.dart'; import '../model.dart'; import '../utils.dart'; class AnalyzeCommand extends Command { @override String get name => 'analyze'; @override String get description => 'Analyze all DevTools packages.'; @override Future run() async { final sdk = FlutterSdk.getSdk(); if (sdk == null) { print('Unable to locate a Flutter sdk.'); return 1; } final log = Logger.standard(); final repo = DevToolsRepo.getInstance()!; final packages = repo.getPackages(); log.stdout('Running flutter analyze...'); int failureCount = 0; for (Package p in packages) { if (!p.hasAnyDartCode) { continue; } final progress = log.progress(' ${p.relativePath}'); final process = await Process.start( sdk.flutterToolPath, ['--no-color', 'analyze'], workingDirectory: p.packagePath, ); final Stream<List<int>> stdout = process.stdout; final Stream<List<int>> stderr = process.stderr; final int exitCode = await process.exitCode; if (exitCode == 0) { progress.finish(showTiming: true); } else { failureCount++; // Display stderr when there's an error. final List<List<int>> out = await stdout.toList(); final stdOutput = convertProcessOutputToString(out, ' '); final List<List<int>> err = await stderr.toList(); final errorOutput = convertProcessOutputToString(err, ' '); progress.finish(message: 'failed'); log.stderr(stdOutput); log.stderr(log.ansi.error(errorOutput)); } } return failureCount == 0 ? 0 : 1; } }
devtools/tool/lib/commands/analyze.dart/0
{'file_path': 'devtools/tool/lib/commands/analyze.dart', 'repo_id': 'devtools', 'token_count': 758}
import 'dart:convert'; import 'dart:io'; // This script must be executed from the top level devtools/ directory. // TODO(kenz): If changes are made to this script, first consider refactoring to // use https://github.com/dart-lang/pubspec_parse. void main(List<String> args) async { final pubspecs = [ 'packages/devtools/pubspec.yaml', 'packages/devtools_app/pubspec.yaml', 'packages/devtools_server/pubspec.yaml', 'packages/devtools_shared/pubspec.yaml', 'packages/devtools_testing/pubspec.yaml', ].map((path) => File(path)).toList(); final version = args.isNotEmpty ? args.first : incrementVersion(versionFromPubspecFile(pubspecs.first)!); if (version == null) { print('Something went wrong. Could not resolve version number.'); return; } print('Updating pubspecs to version $version...'); for (final pubspec in pubspecs) { writeVersionToPubspec(pubspec, version); } print('Updating devtools.dart to version $version...'); writeVersionToVersionFile( File('packages/devtools_app/lib/devtools.dart'), version, ); print('Updating CHANGELOG to version $version...'); writeVersionToChangelog(File('packages/devtools/CHANGELOG.md'), version); final process = await Process.start('./tool/pub_upgrade.sh', []); process.stdout.asBroadcastStream().listen((event) { print(utf8.decode(event)); }); } String? incrementVersion(String oldVersion) { final semVer = RegExp(r'[0-9]+\.[0-9]\.[0-9]+').firstMatch(oldVersion)![0]; const devTag = '-dev'; final isDevVersion = oldVersion.contains(devTag); if (isDevVersion) { return semVer; } final parts = semVer!.split('.'); // Versions should have the form 'x.y.z'. if (parts.length != 3) return null; final patch = int.parse(parts.last); final nextPatch = patch + 1; return [parts[0], parts[1], nextPatch].join('.'); } String? versionFromPubspecFile(File pubspec) { final lines = pubspec.readAsLinesSync(); for (final line in lines) { if (line.startsWith(pubspecVersionPrefix)) { return line.substring(pubspecVersionPrefix.length).trim(); } } return null; } void writeVersionToPubspec(File pubspec, String version) { final lines = pubspec.readAsLinesSync(); final revisedLines = <String>[]; String? currentSection = ''; final sectionRegExp = RegExp('([a-z]|_)+:'); for (var line in lines) { if (line.startsWith(sectionRegExp)) { // This is a top level section of the pubspec. currentSection = sectionRegExp.firstMatch(line)![0]; } if (editablePubspecSections.contains(currentSection)) { if (line.startsWith(pubspecVersionPrefix)) { line = [ line.substring( 0, line.indexOf(pubspecVersionPrefix) + pubspecVersionPrefix.length, ), ' $version', ].join(); } else { for (final prefix in devToolsDependencyPrefixes) { if (line.contains(prefix)) { line = [ line.substring(0, line.indexOf(prefix) + prefix.length), version, ].join(); break; } } } } revisedLines.add(line); } final content = revisedLines.joinWithNewLine(); pubspec.writeAsStringSync(content); } void writeVersionToVersionFile(File versionFile, String version) { const prefix = 'const String version = '; final lines = versionFile.readAsLinesSync(); final revisedLines = <String>[]; for (var line in lines) { if (line.startsWith(prefix)) { line = [prefix, '\'$version\';'].join(); } revisedLines.add(line); } versionFile.writeAsStringSync(revisedLines.joinWithNewLine()); } void writeVersionToChangelog(File changelog, String version) { final lines = changelog.readAsLinesSync(); final versionString = '## $version'; if (lines.first.endsWith(versionString)) { print('Changelog already has an entry for version $version'); return; } changelog.writeAsString([ versionString, 'TODO: update changelog\n', ...lines, ].joinWithNewLine()); } const pubspecVersionPrefix = 'version:'; const editablePubspecSections = [ pubspecVersionPrefix, 'dependencies:', 'dev_dependencies:', ]; const devToolsDependencyPrefixes = [ 'devtools: ', 'devtools_app: ', 'devtools_server: ', 'devtools_shared: ', 'devtools_testing: ', ]; extension JoinExtension on List<String> { String joinWithNewLine() { return join('\n') + '\n'; } }
devtools/tool/update_version.dart/0
{'file_path': 'devtools/tool/update_version.dart', 'repo_id': 'devtools', 'token_count': 1697}
import 'dart:async'; import 'dart:collection'; import 'dio_error.dart'; import 'options.dart'; import 'response.dart'; typedef InterceptorSendCallback = dynamic Function(RequestOptions options); typedef InterceptorErrorCallback = dynamic Function(DioError e); typedef InterceptorSuccessCallback = dynamic Function(Response e); /// Add lock/unlock API for interceptors. class Lock { Future _lock; Completer _completer; /// Whether this interceptor has been locked. bool get locked => _lock != null; /// Lock the interceptor. /// /// Once the request/response interceptor is locked, the incoming request/response /// will be added to a queue before they enter the interceptor, they will not be /// continued until the interceptor is unlocked. void lock() { if (!locked) { _completer = new Completer(); _lock = _completer.future; } } /// Unlock the interceptor. please refer to [lock()] void unlock() { if (locked) { _completer.complete(); _lock = null; } } /// Clean the interceptor queue. void clear([String msg = "cancelled"]) { if (locked) { _completer.completeError(msg); _lock = null; } } /// If the interceptor is locked, the incoming request/response task /// will enter a queue. /// /// [callback] the function will return a `Future<Response>` /// @nodoc Future<Response> enqueue(Future<Response> callback()) { if (locked) { // we use a future as a queue return _lock.then((d) => callback()); } return null; } } /// Dio instance may have interceptor(s) by which you can intercept /// requests or responses before they are handled by `then` or `catchError`. class Interceptor { /// The callback will be executed before the request is initiated. /// /// If you want to resolve the request with some custom data, /// you can return a [Response] object or return [dio.resolve]. /// If you want to reject the request with a error message, /// you can return a [DioError] object or return [dio.reject] . /// If you want to continue the request, return the [Options] object. onRequest(RequestOptions options) => options; /// The callback will be executed on success. /// /// If you want to reject the request with a error message, /// you can return a [DioError] object or return [dio.reject] . /// If you want to continue the request, return the [Response] object. onResponse(Response response) => response; /// The callback will be executed on error. /// /// If you want to resolve the request with some custom data, /// you can return a [Response] object or return [dio.resolve]. /// If you want to continue the request, return the [DioError] object. onError(DioError err) => err; } class InterceptorsWrapper extends Interceptor { final InterceptorSendCallback _onRequest; final InterceptorSuccessCallback _onResponse; final InterceptorErrorCallback _onError; InterceptorsWrapper({ InterceptorSendCallback onRequest, InterceptorSuccessCallback onResponse, InterceptorErrorCallback onError, }) : _onRequest = onRequest, _onResponse = onResponse, _onError = onError; @override onRequest(RequestOptions options) { if (_onRequest != null) { return _onRequest(options); } } @override onResponse(Response response) { if (_onResponse != null) { return _onResponse(response); } } @override onError(DioError err) { if (_onError != null) { return _onError(err); } } } class Interceptors extends ListMixin<Interceptor> { List<Interceptor> _list = new List(); Lock _requestLock = new Lock(); Lock _responseLock = new Lock(); Lock _errorLock = new Lock(); Lock get requestLock => _requestLock; Lock get responseLock => _responseLock; Lock get errorLock => _errorLock; @override int length = 0; @override operator [](int index) { return _list[index]; } @override void operator []=(int index, value) { if (_list.length == index) { _list.add(value); } else { _list[index] = value; } } }
dio/package_src/lib/src/interceptor.dart/0
{'file_path': 'dio/package_src/lib/src/interceptor.dart', 'repo_id': 'dio', 'token_count': 1327}
sudo: false language: node_js node_js: stable
docsify/.travis.yml/0
{'file_path': 'docsify/.travis.yml', 'repo_id': 'docsify', 'token_count': 16}
import 'package:flutter/foundation.dart'; class ItemData { ItemData({@required this.name, @required this.price, @required this.url}); final String name; final String price; final String url; }
duck_duck_shop/lib/data/models/item_data.dart/0
{'file_path': 'duck_duck_shop/lib/data/models/item_data.dart', 'repo_id': 'duck_duck_shop', 'token_count': 62}
import 'package:flutter/cupertino.dart'; import 'domain.dart'; class Repository { const Repository({@required this.auth, @required this.items}); final AuthRepository auth; final ItemsRepository items; }
duck_duck_shop/lib/repository.dart/0
{'file_path': 'duck_duck_shop/lib/repository.dart', 'repo_id': 'duck_duck_shop', 'token_count': 66}
name: effective_dart version: 1.2.4 description: Linter rules corresponding to the guidelines in Effective Dart. homepage: https://github.com/tenhobi/effective_dart repository: https://github.com/tenhobi/effective_dart issue_tracker: https://github.com/tenhobi/effective_dart/issues environment: sdk: '>=2.0.0 <3.0.0'
effective_dart/pubspec.yaml/0
{'file_path': 'effective_dart/pubspec.yaml', 'repo_id': 'effective_dart', 'token_count': 112}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /// The Flutter GPU library. /// /// To use, import `package:flutter_gpu/gpu.dart`. /// /// See also: /// /// * [Flutter GPU Wiki page](https://github.com/flutter/flutter/wiki/Flutter-GPU). library flutter_gpu; import 'dart:ffi'; import 'dart:nativewrappers'; import 'dart:typed_data'; // ignore: uri_does_not_exist import 'dart:ui' as ui; export 'src/smoketest.dart'; part 'src/buffer.dart'; part 'src/command_buffer.dart'; part 'src/context.dart'; part 'src/formats.dart'; part 'src/texture.dart'; part 'src/render_pass.dart'; part 'src/render_pipeline.dart'; part 'src/shader.dart'; part 'src/shader_library.dart';
engine/lib/gpu/lib/gpu.dart/0
{'file_path': 'engine/lib/gpu/lib/gpu.dart', 'repo_id': 'engine', 'token_count': 290}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:io'; import 'package:test_api/src/backend/runtime.dart'; import 'browser.dart'; import 'browser_process.dart'; import 'common.dart'; import 'edge_installation.dart'; import 'package_lock.dart'; /// Provides an environment for the desktop Microsoft Edge (Chromium-based). class EdgeEnvironment implements BrowserEnvironment { @override final String name = 'Edge'; @override Future<Browser> launchBrowserInstance(Uri url, {bool debug = false}) async { return Edge(url); } @override Runtime get packageTestRuntime => Runtime.edge; @override Future<void> prepare() async { // Edge doesn't need any special prep. } @override Future<void> cleanup() async {} @override String get packageTestConfigurationYamlFile => 'dart_test_edge.yaml'; } /// Runs desktop Edge. /// /// Most of the communication with the browser is expected to happen via HTTP, /// so this exposes a bare-bones API. The browser starts as soon as the class is /// constructed, and is killed when [close] is called. /// /// Any errors starting or running the process are reported through [onExit]. class Edge extends Browser { /// Starts a new instance of Safari open to the given [url], which may be a /// [Uri] or a [String]. factory Edge(Uri url) { return Edge._(BrowserProcess(() async { final BrowserInstallation installation = await getEdgeInstallation( packageLock.edgeLock.launcherVersion, infoLog: DevNull(), ); // Debug is not a valid option for Edge. Remove it. String pathToOpen = url.toString(); if(pathToOpen.contains('debug')) { final int index = pathToOpen.indexOf('debug'); pathToOpen = pathToOpen.substring(0, index-1); } final Process process = await Process.start( installation.executable, <String>[pathToOpen,'-k'], ); return process; })); } Edge._(this._process); final BrowserProcess _process; @override Future<void> get onExit => _process.onExit; @override Future<void> close() => _process.close(); }
engine/lib/web_ui/dev/edge.dart/0
{'file_path': 'engine/lib/web_ui/dev/edge.dart', 'repo_id': 'engine', 'token_count': 731}
// 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 ByteConversionSink, jsonDecode, utf8; import 'dart:io' as io; import 'dart:typed_data'; import 'package:args/command_runner.dart'; import 'package:convert/convert.dart'; import 'package:crypto/crypto.dart' as crypto; import 'package:http/http.dart' as http; import 'package:path/path.dart' as path; // ignore: avoid_relative_lib_imports import '../lib/src/engine/noto_font_encoding.dart'; import 'cipd.dart'; import 'environment.dart'; import 'exceptions.dart'; import 'utils.dart'; const String expectedUrlPrefix = 'https://fonts.gstatic.com/s/'; class RollFallbackFontsCommand extends Command<bool> with ArgUtils<bool> { RollFallbackFontsCommand() { argParser.addOption( 'key', defaultsTo: '', help: 'The Google Fonts API key. Used to get data about fonts hosted on ' 'Google Fonts.', ); argParser.addFlag( 'dry-run', help: 'Whether or not to push changes to CIPD. When --dry-run is set, the ' 'script will download everything and attempt to prepare the bundle ' 'but will stop before publishing. When not set, the bundle will be ' 'published.', negatable: false, ); } @override final String name = 'roll-fallback-fonts'; @override final String description = 'Generate fallback font data from GoogleFonts and ' 'upload fonts to cipd.'; String get apiKey => stringArg('key'); bool get isDryRun => boolArg('dry-run'); @override Future<bool> run() async { await _generateFallbackFontData(); return true; } Future<void> _generateFallbackFontData() async { if (apiKey.isEmpty) { throw UsageException('No Google Fonts API key provided', argParser.usage); } final http.Client client = http.Client(); final http.Response response = await client.get(Uri.parse( 'https://www.googleapis.com/webfonts/v1/webfonts?key=$apiKey')); if (response.statusCode != 200) { throw ToolExit('Failed to download Google Fonts list.'); } final Map<String, dynamic> googleFontsResult = jsonDecode(response.body) as Map<String, dynamic>; final List<Map<String, dynamic>> fontDatas = (googleFontsResult['items'] as List<dynamic>) .cast<Map<String, dynamic>>(); final Map<String, Uri> urlForFamily = <String, Uri>{}; for (final Map<String, dynamic> fontData in fontDatas) { if (fallbackFonts.contains(fontData['family'])) { final Uri uri = Uri.parse(fontData['files']['regular'] as String) .replace(scheme: 'https'); urlForFamily[fontData['family'] as String] = uri; } } final Map<String, String> charsetForFamily = <String, String>{}; final io.Directory fontDir = await io.Directory.systemTemp.createTemp('flutter_fallback_fonts'); print('Downloading fonts into temp directory: ${fontDir.path}'); final AccumulatorSink<crypto.Digest> hashSink = AccumulatorSink<crypto.Digest>(); final ByteConversionSink hasher = crypto.sha256.startChunkedConversion(hashSink); for (final String family in fallbackFonts) { print('Downloading $family...'); final Uri? uri = urlForFamily[family]; if (uri == null) { throw ToolExit('Unable to determine URL to download $family. ' 'Check if it is still hosted on Google Fonts.'); } final http.Response fontResponse = await client.get(uri); if (fontResponse.statusCode != 200) { throw ToolExit('Failed to download font for $family'); } final String urlString = uri.toString(); if (!urlString.startsWith(expectedUrlPrefix)) { throw ToolExit('Unexpected url format received from Google Fonts API: $urlString.'); } final String urlSuffix = urlString.substring(expectedUrlPrefix.length); final io.File fontFile = io.File(path.join(fontDir.path, urlSuffix)); final Uint8List bodyBytes = fontResponse.bodyBytes; if (!_checkForLicenseAttribution(bodyBytes)) { throw ToolExit( 'Expected license attribution not found in file: $urlString'); } hasher.add(utf8.encode(urlSuffix)); hasher.add(bodyBytes); await fontFile.create(recursive: true); await fontFile.writeAsBytes(bodyBytes, flush: true); final io.ProcessResult fcQueryResult = await io.Process.run('fc-query', <String>[ '--format=%{charset}', '--', fontFile.path, ]); final String encodedCharset = fcQueryResult.stdout as String; charsetForFamily[family] = encodedCharset; } final StringBuffer sb = StringBuffer(); final List<_Font> fonts = <_Font>[]; for (final String family in fallbackFonts) { final List<int> starts = <int>[]; final List<int> ends = <int>[]; final String charset = charsetForFamily[family]!; for (final String range in charset.split(' ')) { // Range is one hexadecimal number or two, separated by `-`. final List<String> parts = range.split('-'); if (parts.length != 1 && parts.length != 2) { throw ToolExit('Malformed charset range "$range"'); } final int first = int.parse(parts.first, radix: 16); final int last = int.parse(parts.last, radix: 16); starts.add(first); ends.add(last); } fonts.add(_Font(family, fonts.length, starts, ends)); } final String fontSetsCode = _computeEncodedFontSets(fonts); sb.writeln('// Copyright 2013 The Flutter Authors. All rights reserved.'); sb.writeln('// Use of this source code is governed by a BSD-style license ' 'that can be'); sb.writeln('// found in the LICENSE file.'); sb.writeln(); sb.writeln('// DO NOT EDIT! This file is generated. See:'); sb.writeln('// dev/roll_fallback_fonts.dart'); sb.writeln("import 'noto_font.dart';"); sb.writeln(); sb.writeln('List<NotoFont> getFallbackFontList(bool useColorEmoji) => <NotoFont>['); for (final _Font font in fonts) { final String family = font.family; String enabledArgument = ''; if (family == 'Noto Emoji') { enabledArgument = 'enabled: !useColorEmoji, '; } if (family == 'Noto Color Emoji') { enabledArgument = 'enabled: useColorEmoji, '; } final String urlString = urlForFamily[family]!.toString(); if (!urlString.startsWith(expectedUrlPrefix)) { throw ToolExit( 'Unexpected url format received from Google Fonts API: $urlString.'); } final String urlSuffix = urlString.substring(expectedUrlPrefix.length); sb.writeln(" NotoFont('$family', $enabledArgument'$urlSuffix'),"); } sb.writeln('];'); sb.writeln(); sb.write(fontSetsCode); final io.File fontDataFile = io.File(path.join( environment.webUiRootDir.path, 'lib', 'src', 'engine', 'font_fallback_data.dart', )); await fontDataFile.writeAsString(sb.toString()); final io.File licenseFile = io.File(path.join( fontDir.path, 'LICENSE.txt', )); const String licenseString = r''' © Copyright 2015-2021 Google LLC. All Rights Reserved. This Font Software is licensed under the SIL Open Font License, Version 1.1. This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL ----------------------------------------------------------- SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 ----------------------------------------------------------- PREAMBLE The goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font projects, to support the font creation efforts of academic and linguistic communities, and to provide a free and open framework in which fonts may be shared and improved in partnership with others. The OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not sold by themselves. The fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reserved names are not used by derivative works. The fonts and derivatives, however, cannot be released under any other type of license. The requirement for fonts to remain under this license does not apply to any document created using the fonts or their derivatives. DEFINITIONS "Font Software" refers to the set of files released by the Copyright Holder(s) under this license and clearly marked as such. This may include source files, build scripts and documentation. "Reserved Font Name" refers to any names specified as such after the copyright statement(s). "Original Version" refers to the collection of Font Software components as distributed by the Copyright Holder(s). "Modified Version" refers to any derivative made by adding to, deleting, or substituting -- in part or in whole -- any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment. "Author" refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software. PERMISSION & CONDITIONS Permission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font Software, subject to the following conditions: 1) Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold by itself. 2) Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user. 3) No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users. 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission. 5) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software. TERMINATION This license becomes null and void if any of the above conditions are not met. DISCLAIMER THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE. '''; final List<int> licenseData = utf8.encode(licenseString); await licenseFile.create(recursive: true); await licenseFile.writeAsBytes(licenseData); hasher.add(licenseData); hasher.close(); final crypto.Digest digest = hashSink.events.single; final String versionString = digest.toString(); const String packageName = 'flutter/flutter_font_fallbacks'; if (await cipdKnowsPackageVersion( package: packageName, versionTag: versionString)) { print('Package already exists with hash $versionString. Skipping upload'); } else { print('Uploading fallback fonts to CIPD with hash $versionString'); await uploadDirectoryToCipd( directory: fontDir, packageName: packageName, configFileName: 'cipd.flutter_font_fallbacks.yaml', description: 'A set of Noto fonts to fall back to for use in testing.', root: fontDir.path, version: versionString, isDryRun: isDryRun, ); } print('Setting new fallback fonts deps version to $versionString'); final String depFilePath = path.join( environment.engineSrcDir.path, 'flutter', 'DEPS', ); await runProcess('gclient', <String>[ 'setdep', '--revision=src/third_party/google_fonts_for_unit_tests:$packageName@$versionString', '--deps-file=$depFilePath' ]); } } const List<String> fallbackFonts = <String>[ 'Noto Sans', 'Noto Color Emoji', 'Noto Emoji', 'Noto Music', 'Noto Sans Symbols', 'Noto Sans Symbols 2', 'Noto Sans Adlam', 'Noto Sans Anatolian Hieroglyphs', 'Noto Sans Arabic', 'Noto Sans Armenian', 'Noto Sans Avestan', 'Noto Sans Balinese', 'Noto Sans Bamum', 'Noto Sans Bassa Vah', 'Noto Sans Batak', 'Noto Sans Bengali', 'Noto Sans Bhaiksuki', 'Noto Sans Brahmi', 'Noto Sans Buginese', 'Noto Sans Buhid', 'Noto Sans Canadian Aboriginal', 'Noto Sans Carian', 'Noto Sans Caucasian Albanian', 'Noto Sans Chakma', 'Noto Sans Cham', 'Noto Sans Cherokee', 'Noto Sans Coptic', 'Noto Sans Cuneiform', 'Noto Sans Cypriot', 'Noto Sans Deseret', 'Noto Sans Devanagari', 'Noto Sans Duployan', 'Noto Sans Egyptian Hieroglyphs', 'Noto Sans Elbasan', 'Noto Sans Elymaic', 'Noto Sans Georgian', 'Noto Sans Glagolitic', 'Noto Sans Gothic', 'Noto Sans Grantha', 'Noto Sans Gujarati', 'Noto Sans Gunjala Gondi', 'Noto Sans Gurmukhi', 'Noto Sans HK', 'Noto Sans Hanunoo', 'Noto Sans Hatran', 'Noto Sans Hebrew', 'Noto Sans Imperial Aramaic', 'Noto Sans Indic Siyaq Numbers', 'Noto Sans Inscriptional Pahlavi', 'Noto Sans Inscriptional Parthian', 'Noto Sans JP', 'Noto Sans Javanese', 'Noto Sans KR', 'Noto Sans Kaithi', 'Noto Sans Kannada', 'Noto Sans Kayah Li', 'Noto Sans Kharoshthi', 'Noto Sans Khmer', 'Noto Sans Khojki', 'Noto Sans Khudawadi', 'Noto Sans Lao', 'Noto Sans Lepcha', 'Noto Sans Limbu', 'Noto Sans Linear A', 'Noto Sans Linear B', 'Noto Sans Lisu', 'Noto Sans Lycian', 'Noto Sans Lydian', 'Noto Sans Mahajani', 'Noto Sans Malayalam', 'Noto Sans Mandaic', 'Noto Sans Manichaean', 'Noto Sans Marchen', 'Noto Sans Masaram Gondi', 'Noto Sans Math', 'Noto Sans Mayan Numerals', 'Noto Sans Medefaidrin', 'Noto Sans Meetei Mayek', 'Noto Sans Meroitic', 'Noto Sans Miao', 'Noto Sans Modi', 'Noto Sans Mongolian', 'Noto Sans Mro', 'Noto Sans Multani', 'Noto Sans Myanmar', 'Noto Sans NKo', 'Noto Sans Nabataean', 'Noto Sans New Tai Lue', 'Noto Sans Newa', 'Noto Sans Nushu', 'Noto Sans Ogham', 'Noto Sans Ol Chiki', 'Noto Sans Old Hungarian', 'Noto Sans Old Italic', 'Noto Sans Old North Arabian', 'Noto Sans Old Permic', 'Noto Sans Old Persian', 'Noto Sans Old Sogdian', 'Noto Sans Old South Arabian', 'Noto Sans Old Turkic', 'Noto Sans Oriya', 'Noto Sans Osage', 'Noto Sans Osmanya', 'Noto Sans Pahawh Hmong', 'Noto Sans Palmyrene', 'Noto Sans Pau Cin Hau', 'Noto Sans Phags Pa', 'Noto Sans Phoenician', 'Noto Sans Psalter Pahlavi', 'Noto Sans Rejang', 'Noto Sans Runic', 'Noto Sans SC', 'Noto Sans Saurashtra', 'Noto Sans Sharada', 'Noto Sans Shavian', 'Noto Sans Siddham', 'Noto Sans Sinhala', 'Noto Sans Sogdian', 'Noto Sans Sora Sompeng', 'Noto Sans Soyombo', 'Noto Sans Sundanese', 'Noto Sans Syloti Nagri', 'Noto Sans Syriac', 'Noto Sans TC', 'Noto Sans Tagalog', 'Noto Sans Tagbanwa', 'Noto Sans Tai Le', 'Noto Sans Tai Tham', 'Noto Sans Tai Viet', 'Noto Sans Takri', 'Noto Sans Tamil', 'Noto Sans Tamil Supplement', 'Noto Sans Telugu', 'Noto Sans Thaana', 'Noto Sans Thai', 'Noto Sans Tifinagh', 'Noto Sans Tirhuta', 'Noto Sans Ugaritic', 'Noto Sans Vai', 'Noto Sans Wancho', 'Noto Sans Warang Citi', 'Noto Sans Yi', 'Noto Sans Zanabazar Square', ]; bool _checkForLicenseAttribution(Uint8List fontBytes) { final ByteData fontData = fontBytes.buffer.asByteData(); final int codePointCount = fontData.lengthInBytes ~/ 2; const String attributionString = 'This Font Software is licensed under the SIL Open Font License, Version 1.1.'; for (int i = 0; i < codePointCount - attributionString.length; i++) { bool match = true; for (int j = 0; j < attributionString.length; j++) { if (fontData.getUint16((i + j) * 2) != attributionString.codeUnitAt(j)) { match = false; break; } } if (match) { return true; } } return false; } class _Font { _Font(this.family, this.index, this.starts, this.ends); final String family; final int index; final List<int> starts; final List<int> ends; // inclusive ends static int compare(_Font a, _Font b) => a.index.compareTo(b.index); String get shortName => _shortName + String.fromCharCodes( '$index'.codeUnits.map((int ch) => ch - 48 + 0x2080)); String get _shortName => family.startsWith('Noto Sans ') ? family.substring('Noto Sans '.length) : family; } /// The boundary of a range of a font. class _Boundary { _Boundary(this.value, this.isStart, this.font); final int value; // inclusive start or exclusive end. final bool isStart; final _Font font; static int compare(_Boundary a, _Boundary b) => a.value.compareTo(b.value); } class _Range { _Range(this.start, this.end, this.fontSet); final int start; final int end; final _FontSet fontSet; @override String toString() { return '[${start.toRadixString(16)}, ${end.toRadixString(16)}]' ' (${end - start + 1})' ' ${fontSet.description()}'; } } /// A canonical representative for a set of _Fonts. The fonts are stored in /// order of increasing `_Font.index`. class _FontSet { _FontSet(this.fonts); /// The number of [_Font]s in this set. int get length => fonts.length; /// The members of this set. final List<_Font> fonts; /// Number of unicode ranges that are supported by this set of fonts. int rangeCount = 0; /// The serialization order of this set. This index is assigned after building /// all the sets. late final int index; static int orderByDecreasingRangeCount(_FontSet a, _FontSet b) { final int r = b.rangeCount.compareTo(a.rangeCount); if (r != 0) { return r; } return orderByLexicographicFontIndexes(a, b); } static int orderByLexicographicFontIndexes(_FontSet a, _FontSet b) { for (int i = 0; i < a.length && i < b.length; i++) { final int r = _Font.compare(a.fonts[i], b.fonts[i]); if (r != 0) { return r; } } assert(a.length != b.length); // _FontSets are canonical. return a.length - b.length; } @override String toString() { return description(); } String description() { return fonts.map((_Font font) => font.shortName).join(', '); } } /// A trie node [1] used to find the canonical _FontSet. /// /// [1]: https://en.wikipedia.org/wiki/Trie class _TrieNode { final Map<_Font, _TrieNode> _children = <_Font, _TrieNode>{}; _FontSet? fontSet; /// Inserts a string of fonts into the trie and returns the trie node /// representing the string. [this] must be the root node of the trie. /// /// Inserting the same sequence again will traverse the same path through the /// trie and return the same node, canonicalizing the sequence to its /// representative node. _TrieNode insertSequenceAtRoot(Iterable<_Font> fonts) { _TrieNode node = this; for (final _Font font in fonts) { node = node._children[font] ??= _TrieNode(); } return node; } } /// Computes the Dart source code for the encoded data structures used by the /// fallback font selection algorithm. /// /// The data structures allow the fallback font selection algorithm to quickly /// determine which fonts support a given code point. The structures are /// essentially a map from a code point to a set of fonts that support that code /// point. /// /// The universe of code points is partitioned into a set of subsets, or /// components, where each component contains all the code points that are in /// exactly the same set of fonts. A font can be considered to be a union of /// some subset of the components and may share components with other fonts. A /// `_FontSet` is used to represent a component and the set of fonts that use /// the component. One way to visualize this is as a Venn diagram. The fonts are /// the overlapping circles and the components are the spaces between the lines. /// /// The emitted data structures are /// /// (1) A list of sets of fonts. /// (2) A list of code point ranges mapping to an index of list (1). /// /// Each set of fonts is represented as a list of font indexes. The indexes are /// always increasing so the delta is stored. The stored value is biased by -1 /// (i.e. `delta - 1`) since a delta is never less than 1. The deltas are STMR /// encoded. /// /// A code point with no fonts is mapped to an empty set of fonts. This allows /// the list of code point ranges to be complete, covering every code /// point. There are no gaps between ranges; instead there are some ranges that /// map to the empty set. Each range is encoded as the size (number of code /// points) in the range followed by the value which is the index of the /// corresponding set in the list of sets. /// /// /// STMR (Self terminating multiple radix) encoding /// --- /// /// This encoding is a minor adaptation of [VLQ encoding][1], using different /// ranges of characters to represent continuing or terminating digits instead /// of using a 'continuation' bit. /// /// The separators between the numbers can be a significant proportion of the /// number of characters needed to encode a sequence of numbers as a string. /// Instead values are encoded with two kinds of digits: prefix digits and /// terminating digits. Each kind of digit uses a different set of characters, /// and the radix (number of digit characters) can differ between the different /// kinds of digit. Lets say we use decimal digits `0`..`9` for prefix digits /// and `A`..`Z` as terminating digits. /// /// M = ('M' - 'A') = 12 /// 38M = (3 * 10 + 8) * 26 + 12 = 38 * 26 + 12 = 1000 /// /// Choosing a large terminating radix is especially effective when most of the /// encoded values are small, as is the case with delta-encoding. /// /// There can be multiple terminating digit kinds to represent different sorts /// of values. For the range table, the size uses a different terminating digit, /// 'a'..'z'. This allows the very common size of 1 (accounting over a third of /// the range sizes) to be omitted. A range is encoded as either /// `<size><value>`, or `<value>` with an implicit size of 1. Since the size 1 /// can be implicit, it is always implicit, and the stored sizes are biased by /// -2. /// /// | encoding | value | size | /// | :--- | ---: | ---: | /// | A | 0 | 1 | /// | B | 1 | 1 | /// | 38M | 1000 | 1 | /// | aA | 0 | 2 | /// | bB | 1 | 3 | /// | zZ | 25 | 27 | /// | 1a1A | 26 | 28 | /// | 38a38M | 1000 | 1002 | /// /// STMR-encoded strings are decoded efficiently by a simple loop that updates /// the current value and performs some additional operation for a terminating /// digit, e.g. recording the optional size, or creating a range. /// /// [1]: https://en.wikipedia.org/wiki/Variable-length_quantity String _computeEncodedFontSets(List<_Font> fonts) { final List<_Range> ranges = <_Range>[]; final List<_FontSet> allSets = <_FontSet>[]; { // The fonts have their supported code points provided as list of inclusive // [start, end] ranges. We want to intersect all of these ranges and find // the fonts that overlap each intersected range. // // It is easier to work with the boundaries of the ranges rather than the // ranges themselves. The boundaries of the intersected ranges is the union // of the boundaries of the individual font ranges. We scan the boundaries // in increasing order, keeping track of the current set of fonts that are // in the current intersected range. Each time the boundary value changes, // the current set of fonts is canonicalized and recorded. // // There has to be a wiki article for this algorithm but I didn't find one. final List<_Boundary> boundaries = <_Boundary>[]; for (final _Font font in fonts) { for (final int start in font.starts) { boundaries.add(_Boundary(start, true, font)); } for (final int end in font.ends) { boundaries.add(_Boundary(end + 1, false, font)); } } boundaries.sort(_Boundary.compare); // The trie root represents the empty set of fonts. final _TrieNode trieRoot = _TrieNode(); final Set<_Font> currentElements = <_Font>{}; void newRange(int start, int end) { // Ensure we are using the canonical font order. final List<_Font> fonts = List<_Font>.of(currentElements) ..sort(_Font.compare); final _TrieNode node = trieRoot.insertSequenceAtRoot(fonts); final _FontSet fontSet = node.fontSet ??= _FontSet(fonts); if (fontSet.rangeCount == 0) { allSets.add(fontSet); } fontSet.rangeCount++; final _Range range = _Range(start, end, fontSet); ranges.add(range); } int start = 0; for (final _Boundary boundary in boundaries) { final int value = boundary.value; if (value > start) { // Boundary has changed, record the pending range `[start, value - 1]`, // and start a new range at `value`. `value` must be > 0 to get here. newRange(start, value - 1); start = value; } if (boundary.isStart) { currentElements.add(boundary.font); } else { currentElements.remove(boundary.font); } } assert(currentElements.isEmpty); // Ensure the ranges cover the whole unicode code point space. if (start <= kMaxCodePoint) { newRange(start, kMaxCodePoint); } } print('${allSets.length} sets covering ${ranges.length} ranges'); // Sort _FontSets by the number of ranges that map to that _FontSet, so that // _FontSets that are referenced from many ranges have smaller indexes. This // makes the range table encoding smaller, by about half. allSets.sort(_FontSet.orderByDecreasingRangeCount); for (int i = 0; i < allSets.length; i++) { allSets[i].index = i; } final StringBuffer code = StringBuffer(); final StringBuffer sb = StringBuffer(); int totalEncodedLength = 0; void encode(int value, int radix, int firstDigitCode) { final int prefix = value ~/ radix; assert(kPrefixDigit0 == '0'.codeUnitAt(0) && kPrefixRadix == 10); if (prefix != 0) { sb.write(prefix); } sb.writeCharCode(firstDigitCode + value.remainder(radix)); } for (final _FontSet fontSet in allSets) { int previousFontIndex = -1; for (final _Font font in fontSet.fonts) { final int fontIndexDelta = font.index - previousFontIndex; previousFontIndex = font.index; encode(fontIndexDelta - 1, kFontIndexRadix, kFontIndexDigit0); } if (fontSet != allSets.last) { sb.write(','); } final String fragment = sb.toString(); sb.clear(); totalEncodedLength += fragment.length; final int length = fontSet.fonts.length; code.write(' // #${fontSet.index}: $length font'); if (length != 1) { code.write('s'); } if (length > 0) { code.write(': ${fontSet.description()}'); } code.writeln('.'); code.writeln(" '$fragment'"); } final StringBuffer declarations = StringBuffer(); final int references = allSets.fold(0, (int sum, _FontSet set) => sum + set.length); declarations ..writeln('// ${allSets.length} unique sets of fonts' ' containing $references font references' ' encoded in $totalEncodedLength characters') ..writeln('const String encodedFontSets =') ..write(code) ..writeln(' ;'); // Encode ranges. code.clear(); totalEncodedLength = 0; for (final _Range range in ranges) { final int start = range.start; final int end = range.end; final int index = range.fontSet.index; final int size = end - start + 1; // Encode <size><index> or <index> for unit ranges. if (size >= 2) { encode(size - 2, kRangeSizeRadix, kRangeSizeDigit0); } encode(index, kRangeValueRadix, kRangeValueDigit0); final String encoding = sb.toString(); sb.clear(); totalEncodedLength += encoding.length; String description = start.toRadixString(16); if (end != start) { description = '$description-${end.toRadixString(16)}'; } if (range.fontSet.fonts.isNotEmpty) { description = '${description.padRight(12)} #$index'; } final String encodingText = "'$encoding'".padRight(10); code.writeln(' $encodingText // $description'); } declarations ..writeln() ..writeln( '// ${ranges.length} ranges encoded in $totalEncodedLength characters') ..writeln('const String encodedFontSetRanges =') ..write(code) ..writeln(' ;'); return declarations.toString(); }
engine/lib/web_ui/dev/roll_fallback_fonts.dart/0
{'file_path': 'engine/lib/web_ui/dev/roll_fallback_fonts.dart', 'repo_id': 'engine', 'token_count': 10415}
// 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; /// Linearly interpolate between two numbers, `a` and `b`, by an extrapolation /// factor `t`. /// /// When `a` and `b` are equal or both NaN, `a` is returned. Otherwise, if /// `a`, `b`, and `t` are required to be finite or null, and the result of `a + /// (b - a) * t` is returned, where nulls are defaulted to 0.0. double? lerpDouble(num? a, num? b, double t) { if (a == b || (a?.isNaN ?? false) && (b?.isNaN ?? false)) { return a?.toDouble(); } a ??= 0.0; b ??= 0.0; assert(a.isFinite, 'Cannot interpolate between finite and non-finite values'); assert(b.isFinite, 'Cannot interpolate between finite and non-finite values'); assert(t.isFinite, 't must be finite when interpolating between values'); return a * (1.0 - t) + b * t; } /// Linearly interpolate between two doubles. /// /// Same as [lerpDouble] but specialized for non-null `double` type. double _lerpDouble(double a, double b, double t) { return a * (1.0 - t) + b * t; } /// Linearly interpolate between two integers. /// /// Same as [lerpDouble] but specialized for non-null `int` type. double _lerpInt(int a, int b, double t) { return a * (1.0 - t) + b * t; }
engine/lib/web_ui/lib/lerp.dart/0
{'file_path': 'engine/lib/web_ui/lib/lerp.dart', 'repo_id': 'engine', 'token_count': 464}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:math' as math; import 'dart:typed_data'; import 'package:ui/ui.dart' as ui; import '../vector_math.dart'; import 'canvaskit_api.dart'; import 'path.dart'; /// An error related to the CanvasKit rendering backend. class CanvasKitError extends Error { CanvasKitError(this.message); /// Describes this error. final String message; @override String toString() => 'CanvasKitError: $message'; } /// Creates a new color array. Float32List makeFreshSkColor(ui.Color color) { final Float32List result = Float32List(4); result[0] = color.red / 255.0; result[1] = color.green / 255.0; result[2] = color.blue / 255.0; result[3] = color.alpha / 255.0; return result; } ui.TextPosition fromPositionWithAffinity(SkTextPosition positionWithAffinity) { final ui.TextAffinity affinity = ui.TextAffinity.values[positionWithAffinity.affinity.value.toInt()]; return ui.TextPosition( offset: positionWithAffinity.pos.toInt(), affinity: affinity, ); } /// Shadow flag constants derived from Skia's SkShadowFlags.h. class SkiaShadowFlags { /// The occluding object is opaque, making the part of the shadow under the /// occluder invisible. This allows some optimizations because some parts of /// the shadow do not need to be accurate. static const int kNone_ShadowFlag = 0x00; /// The occluding object is not opaque, making the part of the shadow under the /// occluder visible. This requires that the shadow is rendered more accurately /// and therefore is slightly more expensive. static const int kTransparentOccluder_ShadowFlag = 0x01; /// Light position represents a direction, light radius is blur radius at /// elevation 1. /// /// This makes the shadow to have a fixed position relative to the shape that /// casts it. static const int kDirectionalLight_ShadowFlag = 0x04; /// Complete value for the `flags` argument for opaque occluder. static const int kDefaultShadowFlags = kDirectionalLight_ShadowFlag | kNone_ShadowFlag; /// Complete value for the `flags` argument for transparent occluder. static const int kTransparentOccluderShadowFlags = kDirectionalLight_ShadowFlag | kTransparentOccluder_ShadowFlag; } // These numbers have been chosen empirically to give a result closest to the // material spec. const double ckShadowAmbientAlpha = 0.039; const double ckShadowSpotAlpha = 0.25; const double ckShadowLightXOffset = 0; const double ckShadowLightYOffset = -450; const double ckShadowLightHeight = 600; const double ckShadowLightRadius = 800; const double ckShadowLightXTangent = ckShadowLightXOffset / ckShadowLightHeight; const double ckShadowLightYTangent = ckShadowLightYOffset / ckShadowLightHeight; /// Computes the smallest rectangle that contains the shadow. // Most of this logic is borrowed from SkDrawShadowInfo.cpp in Skia. // TODO(yjbanov): switch to SkDrawShadowMetrics::GetLocalBounds when available // See: // - https://bugs.chromium.org/p/skia/issues/detail?id=11146 // - https://github.com/flutter/flutter/issues/73492 ui.Rect computeSkShadowBounds( CkPath path, double elevation, double devicePixelRatio, Matrix4 matrix, ) { ui.Rect pathBounds = path.getBounds(); if (elevation == 0) { return pathBounds; } // For visual correctness the shadow offset and blur does not change with // parent transforms. Therefore, in general case we have to first transform // the shape bounds to device coordinates, then compute the shadow bounds, // then transform the bounds back to local coordinates. However, if the // transform is an identity or translation (a common case), we can skip this // step. With directional lighting translation does not affect the size or // shape of the shadow. Skipping this step saves us two transformRects and // one matrix inverse. final bool isComplex = !matrix.isIdentityOrTranslation(); if (isComplex) { pathBounds = matrix.transformRect(pathBounds); } double left = pathBounds.left; double top = pathBounds.top; double right = pathBounds.right; double bottom = pathBounds.bottom; final double ambientBlur = ambientBlurRadius(elevation); final double spotBlur = ckShadowLightRadius * elevation; final double spotOffsetX = -elevation * ckShadowLightXTangent; final double spotOffsetY = -elevation * ckShadowLightYTangent; // The extra +1/-1 are to cover possible floating point errors. left = left - 1 + (spotOffsetX - ambientBlur - spotBlur) * devicePixelRatio; top = top - 1 + (spotOffsetY - ambientBlur - spotBlur) * devicePixelRatio; right = right + 1 + (spotOffsetX + ambientBlur + spotBlur) * devicePixelRatio; bottom = bottom + 1 + (spotOffsetY + ambientBlur + spotBlur) * devicePixelRatio; final ui.Rect shadowBounds = ui.Rect.fromLTRB(left, top, right, bottom); if (isComplex) { final Matrix4 inverse = Matrix4.zero(); // The inverse only makes sense if the determinat is non-zero. if (inverse.copyInverse(matrix) != 0.0) { return inverse.transformRect(shadowBounds); } else { return shadowBounds; } } else { return shadowBounds; } } const double kAmbientHeightFactor = 1.0 / 128.0; const double kAmbientGeomFactor = 64.0; const double kMaxAmbientRadius = 300 * kAmbientHeightFactor * kAmbientGeomFactor; double ambientBlurRadius(double height) { return math.min( height * kAmbientHeightFactor * kAmbientGeomFactor, kMaxAmbientRadius); } void drawSkShadow( SkCanvas skCanvas, CkPath path, ui.Color color, double elevation, bool transparentOccluder, double devicePixelRatio, ) { int flags = transparentOccluder ? SkiaShadowFlags.kTransparentOccluderShadowFlags : SkiaShadowFlags.kDefaultShadowFlags; flags |= SkiaShadowFlags.kDirectionalLight_ShadowFlag; final ui.Color inAmbient = color.withAlpha((color.alpha * ckShadowAmbientAlpha).round()); final ui.Color inSpot = color.withAlpha((color.alpha * ckShadowSpotAlpha).round()); final SkTonalColors inTonalColors = SkTonalColors( ambient: makeFreshSkColor(inAmbient), spot: makeFreshSkColor(inSpot), ); final SkTonalColors tonalColors = canvasKit.computeTonalColors(inTonalColors); skCanvas.drawShadow( path.skiaObject, Float32List(3)..[2] = devicePixelRatio * elevation, Float32List(3) ..[0] = 0 ..[1] = -1 ..[2] = 1, ckShadowLightRadius / ckShadowLightHeight, tonalColors.ambient, tonalColors.spot, flags.toDouble(), ); }
engine/lib/web_ui/lib/src/engine/canvaskit/util.dart/0
{'file_path': 'engine/lib/web_ui/lib/src/engine/canvaskit/util.dart', 'repo_id': 'engine', 'token_count': 2186}
// 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 'package:ui/ui.dart' as ui; import 'path_ref.dart'; /// Mask used to keep track of types of verbs used in a path segment. class SPathSegmentMask { static const int kLine_SkPathSegmentMask = 1 << 0; static const int kQuad_SkPathSegmentMask = 1 << 1; static const int kConic_SkPathSegmentMask = 1 << 2; static const int kCubic_SkPathSegmentMask = 1 << 3; } /// Types of path operations. class SPathVerb { static const int kMove = 0; // 1 point static const int kLine = 1; // 2 points static const int kQuad = 2; // 3 points static const int kConic = 3; // 3 points + 1 weight static const int kCubic = 4; // 4 points static const int kClose = 5; // 0 points } abstract final class SPath { static const int kMoveVerb = SPathVerb.kMove; static const int kLineVerb = SPathVerb.kLine; static const int kQuadVerb = SPathVerb.kQuad; static const int kConicVerb = SPathVerb.kConic; static const int kCubicVerb = SPathVerb.kCubic; static const int kCloseVerb = SPathVerb.kClose; static const int kDoneVerb = SPathVerb.kClose + 1; static const int kLineSegmentMask = SPathSegmentMask.kLine_SkPathSegmentMask; static const int kQuadSegmentMask = SPathSegmentMask.kQuad_SkPathSegmentMask; static const int kConicSegmentMask = SPathSegmentMask.kConic_SkPathSegmentMask; static const int kCubicSegmentMask = SPathSegmentMask.kCubic_SkPathSegmentMask; static const double scalarNearlyZero = 1.0 / (1 << 12); /// Square root of 2 divided by 2. Useful for sin45 = cos45 = 1/sqrt(2). static const double scalarRoot2Over2 = 0.707106781; /// True if (a <= b <= c) || (a >= b >= c) static bool between(double a, double b, double c) { return (a - b) * (c - b) <= 0; } /// Returns -1 || 0 || 1 depending on the sign of value: /// -1 if x < 0 /// 0 if x == 0 /// 1 if x > 0 static int scalarSignedAsInt(double x) { return x < 0 ? -1 : ((x > 0) ? 1 : 0); } static bool nearlyEqual(double value1, double value2) => (value1 - value2).abs() < SPath.scalarNearlyZero; // Snaps a value to zero if almost zero (within tolerance). static double snapToZero(double value) => SPath.nearlyEqual(value, 0.0) ? 0.0 : value; static bool isInteger(double value) => value.floor() == value; } class SPathAddPathMode { // Append to destination unaltered. static const int kAppend = 0; // Add line if prior contour is not closed. static const int kExtend = 1; } class SPathDirection { /// Uninitialized value for empty paths. static const int kUnknown = -1; /// clockwise direction for adding closed contours. static const int kCW = 0; /// counter-clockwise direction for adding closed contours. static const int kCCW = 1; } class SPathConvexityType { static const int kUnknown = -1; static const int kConvex = 0; static const int kConcave = 1; } class SPathSegmentState { /// The current contour is empty. Starting processing or have just closed /// a contour. static const int kEmptyContour = 0; /// Have seen a move, but nothing else. static const int kAfterMove = 1; /// Have seen a primitive but not yet closed the path. Also the initial state. static const int kAfterPrimitive = 2; } /// Quadratic roots. See Numerical Recipes in C. /// /// Q = -1/2 (B + sign(B) sqrt[B*B - 4*A*C]) /// x1 = Q / A /// x2 = C / Q class QuadRoots { QuadRoots(); double? root0; double? root1; /// Returns roots as list. List<double> get roots => (root0 == null) ? <double>[] : (root1 == null ? <double>[root0!] : <double>[root0!, root1!]); int findRoots(double a, double b, double c) { int rootCount = 0; if (a == 0) { root0 = validUnitDivide(-c, b); return root0 == null ? 0 : 1; } double dr = b * b - 4 * a * c; if (dr < 0) { return 0; } dr = math.sqrt(dr); if (!dr.isFinite) { return 0; } final double q = (b < 0) ? -(b - dr) / 2 : -(b + dr) / 2; double? res = validUnitDivide(q, a); if (res != null) { root0 = res; ++rootCount; } res = validUnitDivide(c, q); if (res != null) { if (rootCount == 0) { root0 = res; ++rootCount; } else { root1 = res; ++rootCount; } } if (rootCount == 2) { if (root0! > root1!) { final double swap = root0!; root0 = root1; root1 = swap; } else if (root0 == root1) { return 1; // skip the double root } } return rootCount; } } double? validUnitDivide(double numer, double denom) { if (numer < 0) { numer = -numer; denom = -denom; } if (denom == 0 || numer == 0 || numer >= denom) { return null; } final double r = numer / denom; if (r.isNaN) { return null; } if (r == 0) { // catch underflow if numer <<<< denom return null; } return r; } bool isRRectOval(ui.RRect rrect) { if ((rrect.tlRadiusX + rrect.trRadiusX) != rrect.width) { return false; } if ((rrect.tlRadiusY + rrect.trRadiusY) != rrect.height) { return false; } if (rrect.tlRadiusX != rrect.blRadiusX || rrect.trRadiusX != rrect.brRadiusX || rrect.tlRadiusY != rrect.blRadiusY || rrect.trRadiusY != rrect.brRadiusY) { return false; } return true; } /// Evaluates degree 2 polynomial (quadratic). double polyEval(double A, double B, double C, double t) => (A * t + B) * t + C; /// Evaluates degree 3 polynomial (cubic). double polyEval4(double A, double B, double C, double D, double t) => ((A * t + B) * t + C) * t + D; // Interpolate between two doubles (Not using lerpDouble here since it null // checks and treats values as 0). double interpolate(double startValue, double endValue, double t) => (startValue * (1 - t)) + endValue * t; double dotProduct(double x0, double y0, double x1, double y1) { return x0 * x1 + y0 * y1; } // Helper class for computing convexity for a single contour. // // Iteratively looks at angle (using cross product) between consecutive vectors // formed by path. class Convexicator { static const int kValueNeverReturnedBySign = 2; // Second point of contour start that forms a vector. // Used to handle close operator to compute angle between last vector and // first. double? firstVectorEndPointX; double? firstVectorEndPointY; double? priorX; double? priorY; double? lastX; double? lastY; double? currX; double? currY; // Last vector to use to compute angle. double? lastVecX; double? lastVecY; bool _isFinite = true; int _firstDirection = SPathDirection.kUnknown; int _reversals = 0; /// SPathDirection of contour. int get firstDirection => _firstDirection; DirChange _expectedDirection = DirChange.kInvalid; void setMovePt(double x, double y) { currX = priorX = lastX = x; currY = priorY = lastY = y; } bool addPoint(double x, double y) { if (x == currX && y == currY) { // Skip zero length vector. return true; } currX = x; currY = y; final double vecX = currX! - lastX!; final double vecY = currY! - lastY!; if (priorX == lastX && priorY == lastY) { // First non-zero vector. lastVecX = vecX; lastVecY = vecY; firstVectorEndPointX = x; firstVectorEndPointY = y; } else if (!_addVector(vecX, vecY)) { return false; } priorX = lastX; priorY = lastY; lastX = x; lastY = y; return true; } bool close() { // Add another point from path closing point to end of first vector. return addPoint(firstVectorEndPointX!, firstVectorEndPointY!); } bool get isFinite => _isFinite; int get reversals => _reversals; DirChange _directionChange(double curVecX, double curVecY) { // Cross product = ||lastVec|| * ||curVec|| * sin(theta) * N // sin(theta) angle between two vectors is positive for angles 0..180 and // negative for greater, providing left or right direction. final double lastX = lastVecX!; final double lastY = lastVecY!; final double cross = lastX * curVecY - lastY * curVecX; if (!cross.isFinite) { return DirChange.kUnknown; } // Detect straight and backwards direction change. // Instead of comparing absolute crossproduct size, compare // largest component double+crossproduct. final double smallest = math.min(curVecX, math.min(curVecY, math.min(lastX, lastY))); final double largest = math.max( math.max(curVecX, math.max(curVecY, math.max(lastX, lastY))), -smallest); if (SPath.nearlyEqual(largest, largest + cross)) { const double nearlyZeroSquared = SPath.scalarNearlyZero * SPath.scalarNearlyZero; if (SPath.nearlyEqual(lengthSquared(lastX, lastY), nearlyZeroSquared) || SPath.nearlyEqual(lengthSquared(curVecX, curVecY), nearlyZeroSquared)) { // Length of either vector is smaller than tolerance to be able // to compute direction. return DirChange.kUnknown; } // The vectors are parallel, sign of dot product gives us direction. // cosine is positive for straight -90 < Theta < 90 return dotProduct(lastX, lastY, curVecX, curVecY) < 0 ? DirChange.kBackwards : DirChange.kStraight; } return cross > 0 ? DirChange.kRight : DirChange.kLeft; } bool _addVector(double curVecX, double curVecY) { final DirChange dir = _directionChange(curVecX, curVecY); final bool isDirectionRight = dir == DirChange.kRight; if (dir == DirChange.kLeft || isDirectionRight) { if (_expectedDirection == DirChange.kInvalid) { // First valid direction. From this point on expect always left. _expectedDirection = dir; _firstDirection = isDirectionRight ? SPathDirection.kCW : SPathDirection.kCCW; } else if (dir != _expectedDirection) { _firstDirection = SPathDirection.kUnknown; return false; } lastVecX = curVecX; lastVecY = curVecY; } else { switch (dir) { case DirChange.kBackwards: // Allow path to reverse direction twice. // Given path.moveTo(0,0) lineTo(1,1) // - First reversal: direction change formed by line (0,0 1,1), // line (1,1 0,0) // - Second reversal: direction change formed by line (1,1 0,0), // line (0,0 1,1) lastVecX = curVecX; lastVecY = curVecY; return ++_reversals < 3; case DirChange.kUnknown: return _isFinite = false; default: break; } } return true; } // Quick test to detect concave by looking at number of changes in direction // of vectors formed by path points (excluding control points). static int bySign(PathRef pathRef, int pointIndex, int numPoints) { final int lastPointIndex = pointIndex + numPoints; int currentPoint = pointIndex++; final int firstPointIndex = currentPoint; int signChangeCountX = 0; int signChangeCountY = 0; int lastSx = kValueNeverReturnedBySign; int lastSy = kValueNeverReturnedBySign; for (int outerLoop = 0; outerLoop < 2; ++outerLoop) { while (pointIndex != lastPointIndex) { final double vecX = pathRef.pointXAt(pointIndex) - pathRef.pointXAt(currentPoint); final double vecY = pathRef.pointYAt(pointIndex) - pathRef.pointYAt(currentPoint); if (!(vecX == 0 && vecY == 0)) { // Give up if vector construction failed. // give up if vector construction failed if (!(vecX.isFinite && vecY.isFinite)) { return SPathConvexityType.kUnknown; } final int sx = vecX < 0 ? 1 : 0; final int sy = vecY < 0 ? 1 : 0; signChangeCountX += (sx != lastSx) ? 1 : 0; signChangeCountY += (sy != lastSy) ? 1 : 0; if (signChangeCountX > 3 || signChangeCountY > 3) { return SPathConvexityType.kConcave; } lastSx = sx; lastSy = sy; } currentPoint = pointIndex++; if (outerLoop != 0) { break; } } pointIndex = firstPointIndex; } return SPathConvexityType.kConvex; } } enum DirChange { kUnknown, kLeft, kRight, kStraight, kBackwards, // if double back, allow simple lines to be convex kInvalid } double lengthSquaredOffset(ui.Offset offset) { final double dx = offset.dx; final double dy = offset.dy; return dx * dx + dy * dy; } double lengthSquared(double dx, double dy) => dx * dx + dy * dy; /// Evaluates A * t^2 + B * t + C = 0 for quadratic curve. class SkQuadCoefficients { SkQuadCoefficients( double x0, double y0, double x1, double y1, double x2, double y2) : cx = x0, cy = y0, bx = 2 * (x1 - x0), by = 2 * (y1 - y0), ax = x2 - (2 * x1) + x0, ay = y2 - (2 * y1) + y0; final double ax, ay, bx, by, cx, cy; double evalX(double t) => (ax * t + bx) * t + cx; double evalY(double t) => (ay * t + by) * t + cy; }
engine/lib/web_ui/lib/src/engine/html/path/path_utils.dart/0
{'file_path': 'engine/lib/web_ui/lib/src/engine/html/path/path_utils.dart', 'repo_id': 'engine', 'token_count': 5325}
// 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 '../../browser_detection.dart'; import 'shader_builder.dart'; /// Provides common shaders used for gradients and drawVertices APIs. abstract final class VertexShaders { static final Uint16List vertexIndicesForRect = Uint16List.fromList(<int>[0, 1, 2, 2, 3, 0]); /// Cached vertex shaders. static String? _baseVertexShader; static String? _textureVertexShader; /// Creates a vertex shader transforms pixel space [Vertices.positions] to /// final clipSpace -1..1 coordinates with inverted Y Axis. /// #version 300 es /// layout (location=0) in vec4 position; /// layout (location=1) in vec4 color; /// uniform mat4 u_ctransform; /// uniform vec4 u_scale; /// uniform vec4 u_shift; /// out vec4 vColor; /// void main() { /// gl_Position = ((u_ctransform * position) * u_scale) + u_shift; /// v_color = color.zyxw; /// } static String writeBaseVertexShader() { if (_baseVertexShader == null) { final ShaderBuilder builder = ShaderBuilder(webGLVersion); builder.addIn(ShaderType.kVec4, name: 'position'); builder.addIn(ShaderType.kVec4, name: 'color'); builder.addUniform(ShaderType.kMat4, name: 'u_ctransform'); builder.addUniform(ShaderType.kVec4, name: 'u_scale'); builder.addUniform(ShaderType.kVec4, name: 'u_shift'); builder.addOut(ShaderType.kVec4, name: 'v_color'); final ShaderMethod method = builder.addMethod('main'); method.addStatement( 'gl_Position = ((u_ctransform * position) * u_scale) + u_shift;'); method.addStatement('v_color = color.zyxw;'); _baseVertexShader = builder.build(); } return _baseVertexShader!; } static String writeTextureVertexShader() { if (_textureVertexShader == null) { final ShaderBuilder builder = ShaderBuilder(webGLVersion); builder.addIn(ShaderType.kVec4, name: 'position'); builder.addUniform(ShaderType.kMat4, name: 'u_ctransform'); builder.addUniform(ShaderType.kVec4, name: 'u_scale'); builder.addUniform(ShaderType.kVec4, name: 'u_textransform'); builder.addUniform(ShaderType.kVec4, name: 'u_shift'); builder.addOut(ShaderType.kVec2, name: 'v_texcoord'); final ShaderMethod method = builder.addMethod('main'); method.addStatement( 'gl_Position = ((u_ctransform * position) * u_scale) + u_shift;'); method.addStatement('v_texcoord = vec2((u_textransform.z + position.x) * u_textransform.x, ' '((u_textransform.w + position.y) * u_textransform.y));'); _textureVertexShader = builder.build(); } return _textureVertexShader!; } } abstract final class FragmentShaders { static String writeTextureFragmentShader( bool isWebGl2, ui.TileMode? tileModeX, ui.TileMode? tileModeY) { final ShaderBuilder builder = ShaderBuilder.fragment(webGLVersion); builder.floatPrecision = ShaderPrecision.kMedium; builder.addIn(ShaderType.kVec2, name: 'v_texcoord'); builder.addUniform(ShaderType.kSampler2D, name: 'u_texture'); final ShaderMethod method = builder.addMethod('main'); if (isWebGl2 || tileModeX == null || tileModeY == null || (tileModeX == ui.TileMode.clamp && tileModeY == ui.TileMode.clamp)) { method.addStatement('${builder.fragmentColor.name} = ' '${builder.texture2DFunction}(u_texture, v_texcoord);'); } else { // Repeat and mirror are not supported for webgl1. Write code to // adjust texture coordinate. // // This will write u and v floats, clamp/repeat and mirror the value and // pass it to sampler. method.addTileStatements('v_texcoord.x', 'u', tileModeX); method.addTileStatements('v_texcoord.y', 'v', tileModeY); method.addStatement('vec2 uv = vec2(u, v);'); method.addStatement('${builder.fragmentColor.name} = ' '${builder.texture2DFunction}(u_texture, uv);'); } return builder.build(); } }
engine/lib/web_ui/lib/src/engine/html/shaders/vertex_shaders.dart/0
{'file_path': 'engine/lib/web_ui/lib/src/engine/html/shaders/vertex_shaders.dart', 'repo_id': 'engine', 'token_count': 1659}
// 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 '../dom.dart'; /// Listener for DOM events that prevents the default browser behavior. final DomEventListener preventDefaultListener = createDomEventListener((DomEvent event) { event.preventDefault(); });
engine/lib/web_ui/lib/src/engine/mouse/prevent_default.dart/0
{'file_path': 'engine/lib/web_ui/lib/src/engine/mouse/prevent_default.dart', 'repo_id': 'engine', 'token_count': 95}
// 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:js_interop'; import 'package:ui/ui.dart' as ui; import 'package:ui/ui_web/src/ui_web.dart' as ui_web; import 'dom.dart'; import 'platform_dispatcher.dart'; import 'util.dart'; // TODO(mdebbar): Deprecate this and remove it. // https://github.com/flutter/flutter/issues/127395 @JS('window._flutter_internal_on_benchmark') external JSExportedDartFunction? get jsBenchmarkValueCallback; ui_web.BenchmarkValueCallback? engineBenchmarkValueCallback; /// A function that computes a value of type [R]. /// /// Functions of this signature can be passed to [timeAction] for performance /// profiling. typedef Action<R> = R Function(); /// Uses the [Profiler] to time a synchronous [action] function and reports the /// result under the give metric [name]. /// /// If profiling is disabled, simply calls [action] and returns the result. /// /// Use this for situations when the cost of an extra closure is negligible. /// This function reduces the boilerplate associated with checking if profiling /// is enabled and exercising the stopwatch. /// /// Example: /// /// ``` /// final result = timeAction('expensive_operation', () { /// ... expensive work ... /// return someValue; /// }); /// ``` R timeAction<R>(String name, Action<R> action) { if (!Profiler.isBenchmarkMode) { return action(); } else { final Stopwatch stopwatch = Stopwatch()..start(); final R result = action(); stopwatch.stop(); Profiler.instance.benchmark(name, stopwatch.elapsedMicroseconds.toDouble()); return result; } } /// The purpose of this class is to facilitate communication of /// profiling/benchmark data to the outside world (e.g. a macrobenchmark that's /// running a flutter app). /// /// To use the [Profiler]: /// /// 1. Set the environment variable `FLUTTER_WEB_ENABLE_PROFILING` to true. /// /// 2. Using JS interop, assign a listener function to /// `window._flutter_internal_on_benchmark` in the browser. /// /// The listener function will be called every time a new benchmark number is /// calculated. The signature is `Function(String name, num value)`. class Profiler { Profiler._() { _checkBenchmarkMode(); } static bool isBenchmarkMode = const bool.fromEnvironment( 'FLUTTER_WEB_ENABLE_PROFILING', ); static Profiler ensureInitialized() { _checkBenchmarkMode(); return Profiler._instance ??= Profiler._(); } static Profiler get instance { _checkBenchmarkMode(); final Profiler? profiler = _instance; if (profiler == null) { throw Exception( 'Profiler has not been properly initialized. ' 'Make sure Profiler.ensureInitialized() is being called before you ' 'access Profiler.instance', ); } return profiler; } static Profiler? _instance; static void _checkBenchmarkMode() { if (!isBenchmarkMode) { throw Exception( 'Cannot use Profiler unless benchmark mode is enabled. ' 'You can enable it by setting the `FLUTTER_WEB_ENABLE_PROFILING` ' 'environment variable to true.', ); } } /// Used to send benchmark data to whoever is listening to them. void benchmark(String name, double value) { _checkBenchmarkMode(); final ui_web.BenchmarkValueCallback? callback = jsBenchmarkValueCallback?.toDart as ui_web.BenchmarkValueCallback?; if (callback != null) { printWarning( 'The JavaScript benchmarking API (i.e. `window._flutter_internal_on_benchmark`) ' 'is deprecated and will be removed in a future release. Please use ' '`benchmarkValueCallback` from `dart:ui_web` instead.', ); callback(name, value); } if (engineBenchmarkValueCallback != null) { engineBenchmarkValueCallback!(name, value); } } } /// Whether we are collecting [ui.FrameTiming]s. bool get _frameTimingsEnabled { return EnginePlatformDispatcher.instance.onReportTimings != null; } /// Collects frame timings from frames. /// /// This list is periodically reported to the framework (see /// [_kFrameTimingsSubmitInterval]). List<ui.FrameTiming> _frameTimings = <ui.FrameTiming>[]; /// The amount of time in microseconds we wait between submitting /// frame timings. const int _kFrameTimingsSubmitInterval = 100000; // 100 milliseconds /// The last time (in microseconds) we submitted frame timings. int _frameTimingsLastSubmitTime = _nowMicros(); // These variables store individual [ui.FrameTiming] properties. int _vsyncStartMicros = -1; int _buildStartMicros = -1; int _buildFinishMicros = -1; int _rasterStartMicros = -1; int _rasterFinishMicros = -1; /// Records the vsync timestamp for this frame. void frameTimingsOnVsync() { if (!_frameTimingsEnabled) { return; } _vsyncStartMicros = _nowMicros(); } /// Records the time when the framework started building the frame. void frameTimingsOnBuildStart() { if (!_frameTimingsEnabled) { return; } _buildStartMicros = _nowMicros(); } /// Records the time when the framework finished building the frame. void frameTimingsOnBuildFinish() { if (!_frameTimingsEnabled) { return; } _buildFinishMicros = _nowMicros(); } /// Records the time when the framework started rasterizing the frame. /// /// On the web, this value is almost always the same as [_buildFinishMicros] /// because it's single-threaded so there's no delay between building /// and rasterization. /// /// This also means different things between HTML and CanvasKit renderers. /// /// In HTML "rasterization" only captures DOM updates, but not the work that /// the browser performs after the DOM updates are committed. The browser /// does not report that information. /// /// CanvasKit captures everything because we control the rasterization /// process, so we know exactly when rasterization starts and ends. void frameTimingsOnRasterStart() { if (!_frameTimingsEnabled) { return; } _rasterStartMicros = _nowMicros(); } /// Records the time when the framework started rasterizing the frame. /// /// See [_frameTimingsOnRasterStart] for more details on what rasterization /// timings mean on the web. void frameTimingsOnRasterFinish() { if (!_frameTimingsEnabled) { return; } final int now = _nowMicros(); _rasterFinishMicros = now; _frameTimings.add(ui.FrameTiming( vsyncStart: _vsyncStartMicros, buildStart: _buildStartMicros, buildFinish: _buildFinishMicros, rasterStart: _rasterStartMicros, rasterFinish: _rasterFinishMicros, rasterFinishWallTime: _rasterFinishMicros, )); _vsyncStartMicros = -1; _buildStartMicros = -1; _buildFinishMicros = -1; _rasterStartMicros = -1; _rasterFinishMicros = -1; if (now - _frameTimingsLastSubmitTime > _kFrameTimingsSubmitInterval) { _frameTimingsLastSubmitTime = now; EnginePlatformDispatcher.instance.invokeOnReportTimings(_frameTimings); _frameTimings = <ui.FrameTiming>[]; } } /// Current timestamp in microseconds taken from the high-precision /// monotonically increasing timer. /// /// See also: /// /// * https://developer.mozilla.org/en-US/docs/Web/API/Performance/now, /// particularly notes about Firefox rounding to 1ms for security reasons, /// which can be bypassed in tests by setting certain browser options. int _nowMicros() { return (domWindow.performance.now() * 1000).toInt(); } /// Counts various events that take place while the app is running. /// /// This class will slow down the app, and therefore should be disabled while /// benchmarking. For example, avoid using it in conjunction with [Profiler]. class Instrumentation { Instrumentation._() { _checkInstrumentationEnabled(); } /// Whether instrumentation is enabled. /// /// Check this value before calling any other methods in this class. static bool get enabled => _enabled; static set enabled(bool value) { if (_enabled == value) { return; } if (!value) { _instance._counters.clear(); _instance._printTimer = null; } _enabled = value; } static bool _enabled = const bool.fromEnvironment( 'FLUTTER_WEB_ENABLE_INSTRUMENTATION', ); /// Returns the singleton that provides instrumentation API. static Instrumentation get instance { _checkInstrumentationEnabled(); return _instance; } static final Instrumentation _instance = Instrumentation._(); static void _checkInstrumentationEnabled() { if (!enabled) { throw StateError( 'Cannot use Instrumentation unless it is enabled. ' 'You can enable it by setting the `FLUTTER_WEB_ENABLE_INSTRUMENTATION` ' 'environment variable to true, or by passing ' '--dart-define=FLUTTER_WEB_ENABLE_INSTRUMENTATION=true to the flutter ' 'tool.', ); } } Map<String, int> get debugCounters => _counters; final Map<String, int> _counters = <String, int>{}; Timer? get debugPrintTimer => _printTimer; Timer? _printTimer; /// Increments the count of a particular event by one. void incrementCounter(String event) { _checkInstrumentationEnabled(); final int currentCount = _counters[event] ?? 0; _counters[event] = currentCount + 1; _printTimer ??= Timer( const Duration(seconds: 2), () { if (_printTimer == null || !_enabled) { return; } final StringBuffer message = StringBuffer('Engine counters:\n'); // Entries are sorted for readability and testability. final List<MapEntry<String, int>> entries = _counters.entries.toList() ..sort((MapEntry<String, int> a, MapEntry<String, int> b) { return a.key.compareTo(b.key); }); for (final MapEntry<String, int> entry in entries) { message.writeln(' ${entry.key}: ${entry.value}'); } print(message); _printTimer = null; }, ); } }
engine/lib/web_ui/lib/src/engine/profiler.dart/0
{'file_path': 'engine/lib/web_ui/lib/src/engine/profiler.dart', 'repo_id': 'engine', 'token_count': 3288}
// 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 '../dom.dart'; import '../semantics.dart'; /// Provides accessibility for links. class Link extends PrimaryRoleManager { Link(SemanticsObject semanticsObject) : super.withBasics(PrimaryRole.link, semanticsObject); @override DomElement createElement() { final DomElement element = domDocument.createElement('a'); // TODO(chunhtai): Fill in the real link once the framework sends entire uri. // https://github.com/flutter/flutter/issues/102535. element.setAttribute('href', '#'); element.style.display = 'block'; return element; } @override bool focusAsRouteDefault() => focusable?.focusAsRouteDefault() ?? false; }
engine/lib/web_ui/lib/src/engine/semantics/link.dart/0
{'file_path': 'engine/lib/web_ui/lib/src/engine/semantics/link.dart', 'repo_id': 'engine', 'token_count': 246}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:ffi'; import 'dart:typed_data'; import 'package:ui/src/engine.dart'; import 'package:ui/src/engine/skwasm/skwasm_impl.dart'; import 'package:ui/ui.dart' as ui; class SkwasmCanvas implements SceneCanvas { factory SkwasmCanvas(SkwasmPictureRecorder recorder, ui.Rect cullRect) => SkwasmCanvas.fromHandle(withStackScope((StackScope s) => pictureRecorderBeginRecording( recorder.handle, s.convertRectToNative(cullRect)))); SkwasmCanvas.fromHandle(this._handle); CanvasHandle _handle; // Note that we do not need to deal with the finalizer registry here, because // the underlying native skia object is tied directly to the lifetime of the // associated SkPictureRecorder. @override void save() { canvasSave(_handle); } @override void saveLayer(ui.Rect? bounds, ui.Paint paint) { paint as SkwasmPaint; if (bounds != null) { withStackScope((StackScope s) { canvasSaveLayer(_handle, s.convertRectToNative(bounds), paint.handle, nullptr); }); } else { canvasSaveLayer(_handle, nullptr, paint.handle, nullptr); } } @override void saveLayerWithFilter(ui.Rect? bounds, ui.Paint paint, ui.ImageFilter imageFilter) { final SkwasmImageFilter nativeFilter = SkwasmImageFilter.fromUiFilter(imageFilter); paint as SkwasmPaint; if (bounds != null) { withStackScope((StackScope s) { canvasSaveLayer(_handle, s.convertRectToNative(bounds), paint.handle, nativeFilter.handle); }); } else { canvasSaveLayer(_handle, nullptr, paint.handle, nativeFilter.handle); } } @override void restore() { canvasRestore(_handle); } @override void restoreToCount(int count) { canvasRestoreToCount(_handle, count); } @override int getSaveCount() => canvasGetSaveCount(_handle); @override void translate(double dx, double dy) => canvasTranslate(_handle, dx, dy); @override void scale(double sx, [double? sy]) => canvasScale(_handle, sx, sy ?? sx); @override void rotate(double radians) => canvasRotate(_handle, ui.toDegrees(radians)); @override void skew(double sx, double sy) => canvasSkew(_handle, sx, sy); @override void transform(Float64List matrix4) { withStackScope((StackScope s) { canvasTransform(_handle, s.convertMatrix44toNative(matrix4)); }); } @override void clipRect(ui.Rect rect, {ui.ClipOp clipOp = ui.ClipOp.intersect, bool doAntiAlias = true}) { withStackScope((StackScope s) { canvasClipRect(_handle, s.convertRectToNative(rect), clipOp.index, doAntiAlias); }); } @override void clipRRect(ui.RRect rrect, {bool doAntiAlias = true}) { withStackScope((StackScope s) { canvasClipRRect(_handle, s.convertRRectToNative(rrect), doAntiAlias); }); } @override void clipPath(ui.Path path, {bool doAntiAlias = true}) { path as SkwasmPath; canvasClipPath(_handle, path.handle, doAntiAlias); } @override void drawColor(ui.Color color, ui.BlendMode blendMode) => canvasDrawColor(_handle, color.value, blendMode.index); @override void drawLine(ui.Offset p1, ui.Offset p2, ui.Paint paint) { paint as SkwasmPaint; canvasDrawLine(_handle, p1.dx, p1.dy, p2.dx, p2.dy, paint.handle); } @override void drawPaint(ui.Paint paint) { paint as SkwasmPaint; canvasDrawPaint(_handle, paint.handle); } @override void drawRect(ui.Rect rect, ui.Paint paint) { paint as SkwasmPaint; withStackScope((StackScope s) { canvasDrawRect( _handle, s.convertRectToNative(rect), paint.handle ); }); } @override void drawRRect(ui.RRect rrect, ui.Paint paint) { paint as SkwasmPaint; withStackScope((StackScope s) { canvasDrawRRect( _handle, s.convertRRectToNative(rrect), paint.handle ); }); } @override void drawDRRect(ui.RRect outer, ui.RRect inner, ui.Paint paint) { paint as SkwasmPaint; withStackScope((StackScope s) { canvasDrawDRRect( _handle, s.convertRRectToNative(outer), s.convertRRectToNative(inner), paint.handle ); }); } @override void drawOval(ui.Rect rect, ui.Paint paint) { paint as SkwasmPaint; withStackScope((StackScope s) { canvasDrawOval(_handle, s.convertRectToNative(rect), paint.handle); }); } @override void drawCircle(ui.Offset center, double radius, ui.Paint paint) { paint as SkwasmPaint; canvasDrawCircle(_handle, center.dx, center.dy, radius, paint.handle); } @override void drawArc(ui.Rect rect, double startAngle, double sweepAngle, bool useCenter, ui.Paint paint) { paint as SkwasmPaint; withStackScope((StackScope s) { canvasDrawArc( _handle, s.convertRectToNative(rect), ui.toDegrees(startAngle), ui.toDegrees(sweepAngle), useCenter, paint.handle ); }); } @override void drawPath(ui.Path path, ui.Paint paint) { paint as SkwasmPaint; path as SkwasmPath; canvasDrawPath(_handle, path.handle, paint.handle); } @override void drawImage(ui.Image image, ui.Offset offset, ui.Paint paint) => canvasDrawImage( _handle, (image as SkwasmImage).handle, offset.dx, offset.dy, (paint as SkwasmPaint).handle, paint.filterQuality.index, ); @override void drawImageRect( ui.Image image, ui.Rect src, ui.Rect dst, ui.Paint paint) => withStackScope((StackScope scope) { final Pointer<Float> sourceRect = scope.convertRectToNative(src); final Pointer<Float> destRect = scope.convertRectToNative(dst); canvasDrawImageRect( _handle, (image as SkwasmImage).handle, sourceRect, destRect, (paint as SkwasmPaint).handle, paint.filterQuality.index, ); }); @override void drawImageNine( ui.Image image, ui.Rect center, ui.Rect dst, ui.Paint paint) => withStackScope((StackScope scope) { final Pointer<Int32> centerRect = scope.convertIRectToNative(center); final Pointer<Float> destRect = scope.convertRectToNative(dst); canvasDrawImageNine( _handle, (image as SkwasmImage).handle, centerRect, destRect, (paint as SkwasmPaint).handle, paint.filterQuality.index, ); }); @override void drawPicture(ui.Picture picture) { canvasDrawPicture(_handle, (picture as SkwasmPicture).handle); } @override void drawParagraph(ui.Paragraph paragraph, ui.Offset offset) { canvasDrawParagraph( _handle, (paragraph as SkwasmParagraph).handle, offset.dx, offset.dy, ); } @override void drawPoints( ui.PointMode pointMode, List<ui.Offset> points, ui.Paint paint ) => withStackScope((StackScope scope) { final RawPointArray rawPoints = scope.convertPointArrayToNative(points); canvasDrawPoints( _handle, pointMode.index, rawPoints, points.length, (paint as SkwasmPaint).handle, ); }); @override void drawRawPoints( ui.PointMode pointMode, Float32List points, ui.Paint paint ) => withStackScope((StackScope scope) { final RawPointArray rawPoints = scope.convertDoublesToNative(points); canvasDrawPoints( _handle, pointMode.index, rawPoints, points.length ~/ 2, (paint as SkwasmPaint).handle, ); }); @override void drawVertices( ui.Vertices vertices, ui.BlendMode blendMode, ui.Paint paint, ) => canvasDrawVertices( _handle, (vertices as SkwasmVertices).handle, blendMode.index, (paint as SkwasmPaint).handle, ); @override void drawAtlas( ui.Image atlas, List<ui.RSTransform> transforms, List<ui.Rect> rects, List<ui.Color>? colors, ui.BlendMode? blendMode, ui.Rect? cullRect, ui.Paint paint, ) => withStackScope((StackScope scope) { final RawRSTransformArray rawTransforms = scope.convertRSTransformsToNative(transforms); final RawRect rawRects = scope.convertRectsToNative(rects); final RawColorArray rawColors = colors != null ? scope.convertColorArrayToNative(colors) : nullptr; final RawRect rawCullRect = cullRect != null ? scope.convertRectToNative(cullRect) : nullptr; canvasDrawAtlas( _handle, (atlas as SkwasmImage).handle, rawTransforms, rawRects, rawColors, transforms.length, (blendMode ?? ui.BlendMode.src).index, rawCullRect, (paint as SkwasmPaint).handle, ); }); @override void drawRawAtlas( ui.Image atlas, Float32List rstTransforms, Float32List rects, Int32List? colors, ui.BlendMode? blendMode, ui.Rect? cullRect, ui.Paint paint, ) => withStackScope((StackScope scope) { final RawRSTransformArray rawTransforms = scope.convertDoublesToNative(rstTransforms); final RawRect rawRects = scope.convertDoublesToNative(rects); final RawColorArray rawColors = colors != null ? scope.convertIntsToUint32Native(colors) : nullptr; final RawRect rawCullRect = cullRect != null ? scope.convertRectToNative(cullRect) : nullptr; canvasDrawAtlas( _handle, (atlas as SkwasmImage).handle, rawTransforms, rawRects, rawColors, rstTransforms.length ~/ 4, (blendMode ?? ui.BlendMode.src).index, rawCullRect, (paint as SkwasmPaint).handle, ); }); @override void drawShadow( ui.Path path, ui.Color color, double elevation, bool transparentOccluder, ) { path as SkwasmPath; canvasDrawShadow( _handle, path.handle, elevation, EngineFlutterDisplay.instance.devicePixelRatio, color.value, transparentOccluder); } @override ui.Rect getDestinationClipBounds() { return withStackScope((StackScope scope) { final Pointer<Int32> outRect = scope.allocInt32Array(4); canvasGetDeviceClipBounds(_handle, outRect); return scope.convertIRectFromNative(outRect); }); } @override ui.Rect getLocalClipBounds() { final Float64List transform = getTransform(); final Matrix4 matrix = Matrix4.fromFloat32List(Float32List.fromList(transform)); if (matrix.invert() == 0) { // non-invertible transforms collapse space to a line or point return ui.Rect.zero; } return matrix.transformRect(getDestinationClipBounds()); } @override Float64List getTransform() { return withStackScope((StackScope scope) { final Pointer<Float> outMatrix = scope.allocFloatArray(16); canvasGetTransform(_handle, outMatrix); return scope.convertMatrix44FromNative(outMatrix); }); } }
engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/canvas.dart/0
{'file_path': 'engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/canvas.dart', 'repo_id': 'engine', 'token_count': 4418}
// 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:convert'; import 'dart:ffi'; import 'dart:typed_data'; import 'package:ui/ui.dart' as ui; final class Stack extends Opaque {} typedef StackPointer = Pointer<Stack>; /// Generic linear memory allocation @Native<StackPointer Function(Size)>(symbol: 'stackAlloc', isLeaf: true) external StackPointer stackAlloc(int length); @Native<StackPointer Function()>(symbol: 'stackSave', isLeaf: true) external StackPointer stackSave(); @Native<Void Function(StackPointer)>(symbol: 'stackRestore', isLeaf: true) external void stackRestore(StackPointer pointer); class StackScope { Pointer<Int8> convertStringToNative(String string) { final Uint8List encoded = utf8.encode(string); final Pointer<Int8> pointer = allocInt8Array(encoded.length + 1); for (int i = 0; i < encoded.length; i++) { pointer[i] = encoded[i]; } pointer[encoded.length] = 0; return pointer; } Pointer<Float> convertMatrix4toSkMatrix(List<double> matrix4) { final Pointer<Float> pointer = allocFloatArray(9); final int matrixLength = matrix4.length; double getVal(int index) { return (index < matrixLength) ? matrix4[index] : 0.0; } pointer[0] = getVal(0); pointer[1] = getVal(4); pointer[2] = getVal(12); pointer[3] = getVal(1); pointer[4] = getVal(5); pointer[5] = getVal(13); pointer[6] = getVal(3); pointer[7] = getVal(7); pointer[8] = getVal(15); return pointer; } Pointer<Float> convertMatrix44toNative(Float64List matrix4) { assert(matrix4.length == 16); final Pointer<Float> pointer = allocFloatArray(16); for (int i = 0; i < 16; i++) { pointer[i] = matrix4[i]; } return pointer; } Float64List convertMatrix44FromNative(Pointer<Float> buffer) { final Float64List matrix = Float64List(16); for (int i = 0; i < 16; i++) { matrix[i] = buffer[i]; } return matrix; } Pointer<Float> convertRectToNative(ui.Rect rect) { final Pointer<Float> pointer = allocFloatArray(4); pointer[0] = rect.left; pointer[1] = rect.top; pointer[2] = rect.right; pointer[3] = rect.bottom; return pointer; } Pointer<Float> convertRectsToNative(List<ui.Rect> rects) { final Pointer<Float> pointer = allocFloatArray(rects.length * 4); for (int i = 0; i < rects.length; i++) { final ui.Rect rect = rects[i]; pointer[i * 4] = rect.left; pointer[i * 4 + 1] = rect.top; pointer[i * 4 + 2] = rect.right; pointer[i * 4 + 3] = rect.bottom; } return pointer; } ui.Rect convertRectFromNative(Pointer<Float> buffer) { return ui.Rect.fromLTRB( buffer[0], buffer[1], buffer[2], buffer[3], ); } Pointer<Int32> convertIRectToNative(ui.Rect rect) { final Pointer<Int32> pointer = allocInt32Array(4); pointer[0] = rect.left.floor(); pointer[1] = rect.top.floor(); pointer[2] = rect.right.ceil(); pointer[3] = rect.bottom.ceil(); return pointer; } ui.Rect convertIRectFromNative(Pointer<Int32> buffer) { return ui.Rect.fromLTRB( buffer[0].toDouble(), buffer[1].toDouble(), buffer[2].toDouble(), buffer[3].toDouble(), ); } Pointer<Float> convertRRectToNative(ui.RRect rect) { final Pointer<Float> pointer = allocFloatArray(12); pointer[0] = rect.left; pointer[1] = rect.top; pointer[2] = rect.right; pointer[3] = rect.bottom; pointer[4] = rect.tlRadiusX; pointer[5] = rect.tlRadiusY; pointer[6] = rect.trRadiusX; pointer[7] = rect.trRadiusY; pointer[8] = rect.brRadiusX; pointer[9] = rect.brRadiusY; pointer[10] = rect.blRadiusX; pointer[11] = rect.blRadiusY; return pointer; } Pointer<Float> convertRSTransformsToNative(List<ui.RSTransform> transforms) { final Pointer<Float> pointer = allocFloatArray(transforms.length * 4); for (int i = 0; i < transforms.length; i++) { final ui.RSTransform transform = transforms[i]; pointer[i * 4] = transform.scos; pointer[i * 4 + 1] = transform.ssin; pointer[i * 4 + 2] = transform.tx; pointer[i * 4 + 3] = transform.ty; } return pointer; } Pointer<Float> convertDoublesToNative(List<double> values) { final Pointer<Float> pointer = allocFloatArray(values.length); for (int i = 0; i < values.length; i++) { pointer[i] = values[i]; } return pointer; } Pointer<Uint16> convertIntsToUint16Native(List<int> values) { final Pointer<Uint16> pointer = allocUint16Array(values.length); for (int i = 0; i < values.length; i++) { pointer[i] = values[i]; } return pointer; } Pointer<Uint32> convertIntsToUint32Native(List<int> values) { final Pointer<Uint32> pointer = allocUint32Array(values.length); for (int i = 0; i < values.length; i++) { pointer[i] = values[i]; } return pointer; } Pointer<Float> convertPointArrayToNative(List<ui.Offset> points) { final Pointer<Float> pointer = allocFloatArray(points.length * 2); for (int i = 0; i < points.length; i++) { pointer[i * 2] = points[i].dx; pointer[i * 2 + 1] = points[i].dy; } return pointer; } Pointer<Uint32> convertColorArrayToNative(List<ui.Color> colors) { final Pointer<Uint32> pointer = allocUint32Array(colors.length); for (int i = 0; i < colors.length; i++) { pointer[i] = colors[i].value; } return pointer; } Pointer<Bool> allocBoolArray(int count) { final int length = count * sizeOf<Bool>(); return stackAlloc(length).cast<Bool>(); } Pointer<Int8> allocInt8Array(int count) { final int length = count * sizeOf<Int8>(); return stackAlloc(length).cast<Int8>(); } Pointer<Uint16> allocUint16Array(int count) { final int length = count * sizeOf<Uint16>(); return stackAlloc(length).cast<Uint16>(); } Pointer<Int32> allocInt32Array(int count) { final int length = count * sizeOf<Int32>(); return stackAlloc(length).cast<Int32>(); } Pointer<Uint32> allocUint32Array(int count) { final int length = count * sizeOf<Uint32>(); return stackAlloc(length).cast<Uint32>(); } Pointer<Float> allocFloatArray(int count) { final int length = count * sizeOf<Float>(); return stackAlloc(length).cast<Float>(); } Pointer<Pointer<Void>> allocPointerArray(int count) { final int length = count * sizeOf<Pointer<Void>>(); return stackAlloc(length).cast<Pointer<Void>>(); } } T withStackScope<T>(T Function(StackScope scope) f) { final StackPointer stack = stackSave(); final T result = f(StackScope()); stackRestore(stack); return result; }
engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/raw/raw_memory.dart/0
{'file_path': 'engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/raw/raw_memory.dart', 'repo_id': 'engine', 'token_count': 2721}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import '../../engine.dart' show registerHotRestartListener; import '../dom.dart'; import '../platform_dispatcher.dart'; import '../view_embedder/dom_manager.dart'; // TODO(yjbanov): this is a hack we use to compute ideographic baseline; this // number is the ratio ideographic/alphabetic for font Ahem, // which matches the Flutter number. It may be completely wrong // for any other font. We'll need to eventually fix this. That // said Flutter doesn't seem to use ideographic baseline for // anything as of this writing. const double baselineRatioHack = 1.1662499904632568; /// Hosts ruler DOM elements in a hidden container under [DomManager.renderingHost]. class RulerHost { RulerHost() { _rulerHost.style ..position = 'fixed' ..visibility = 'hidden' ..overflow = 'hidden' ..top = '0' ..left = '0' ..width = '0' ..height = '0'; // TODO(mdebbar): There could be multiple views with multiple rendering hosts. // https://github.com/flutter/flutter/issues/137344 final DomNode renderingHost = EnginePlatformDispatcher.instance.implicitView!.dom.renderingHost; renderingHost.appendChild(_rulerHost); registerHotRestartListener(dispose); } /// Hosts a cache of rulers that measure text. /// /// This element exists purely for organizational purposes. Otherwise the /// rulers would be attached to the `<body>` element polluting the element /// tree and making it hard to navigate. It does not serve any functional /// purpose. final DomElement _rulerHost = createDomElement('flt-ruler-host'); /// Releases the resources used by this [RulerHost]. /// /// After this is called, this object is no longer usable. void dispose() { _rulerHost.remove(); } /// Adds an element used for measuring text as a child of [_rulerHost]. void addElement(DomHTMLElement element) { _rulerHost.append(element); } } // These global variables are used to memoize calls to [measureSubstring]. They // are used to remember the last arguments passed to it, and the last return // value. // They are being initialized so that the compiler knows they'll never be null. int _lastStart = -1; int _lastEnd = -1; String _lastText = ''; String _lastCssFont = ''; double _lastWidth = -1; /// Measures the width of the substring of [text] starting from the index /// [start] (inclusive) to [end] (exclusive). /// /// This method assumes that the correct font has already been set on /// [canvasContext]. double measureSubstring( DomCanvasRenderingContext2D canvasContext, String text, int start, int end, { double? letterSpacing, }) { assert(0 <= start); assert(start <= end); assert(end <= text.length); if (start == end) { return 0; } final String cssFont = canvasContext.font; double width; // TODO(mdebbar): Explore caching all widths in a map, not only the last one. if (start == _lastStart && end == _lastEnd && text == _lastText && cssFont == _lastCssFont) { // Reuse the previously calculated width if all factors that affect width // are unchanged. The only exception is letter-spacing. We always add // letter-spacing to the width later below. width = _lastWidth; } else { final String sub = start == 0 && end == text.length ? text : text.substring(start, end); width = canvasContext.measureText(sub).width!; } _lastStart = start; _lastEnd = end; _lastText = text; _lastCssFont = cssFont; _lastWidth = width; // Now add letter spacing to the width. letterSpacing ??= 0.0; if (letterSpacing != 0.0) { width += letterSpacing * (end - start); } // What we are doing here is we are rounding to the nearest 2nd decimal // point. So 39.999423 becomes 40, and 11.243982 becomes 11.24. // The reason we are doing this is because we noticed that canvas API has a // ±0.001 error margin. return _roundWidth(width); } double _roundWidth(double width) { return (width * 100).round() / 100; }
engine/lib/web_ui/lib/src/engine/text/measurement.dart/0
{'file_path': 'engine/lib/web_ui/lib/src/engine/text/measurement.dart', 'repo_id': 'engine', 'token_count': 1397}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert'; import 'dart:typed_data'; import 'package:ui/src/engine.dart'; /// Provides the [AssetManager] used by the Flutter Engine. AssetManager get assetManager => engineAssetManager; /// This class downloads assets over the network. /// /// Assets are resolved relative to [assetsDir] inside the absolute base /// specified by [assetBase] (optional). /// /// By default, URLs are relative to the `<base>` of the current website. class AssetManager { /// Initializes [AssetManager] with paths. AssetManager({ this.assetsDir = _defaultAssetsDir, String? assetBase, }) : assert( assetBase == null || assetBase.endsWith('/'), '`assetBase` must end with a `/` character.', ), _assetBase = assetBase; static const String _defaultAssetsDir = 'assets'; /// The directory containing the assets. final String assetsDir; /// The absolute base URL for assets. String? _assetBase; // Cache a value for `_assetBase` so we don't hit the DOM multiple times. String get _baseUrl => _assetBase ??= _deprecatedAssetBase ?? ''; // Retrieves the `assetBase` value from the DOM. // // This warns the user and points them to the new initializeEngine style. String? get _deprecatedAssetBase { final DomHTMLMetaElement? meta = domWindow.document .querySelector('meta[name=assetBase]') as DomHTMLMetaElement?; final String? fallbackBaseUrl = meta?.content; if (fallbackBaseUrl != null) { // Warn users that they're using a deprecated configuration style... domWindow.console.warn('The `assetBase` meta tag is now deprecated.\n' 'Use engineInitializer.initializeEngine(config) instead.\n' 'See: https://docs.flutter.dev/development/platform-integration/web/initialization'); } return fallbackBaseUrl; } /// Returns the URL to load the asset from, given the asset key. /// /// We URL-encode the asset URL in order to correctly issue the right /// HTTP request to the server. /// /// For example, if you have an asset in the file "assets/hello world.png", /// two things will happen. When the app is built, the asset will be copied /// to an asset directory with the file name URL-encoded. So our asset will /// be copied to something like "assets/hello%20world.png". To account for /// the assets being copied over with a URL-encoded name, the Flutter /// framework URL-encodes the asset key so when it sends a request to the /// engine to load "assets/hello world.png", it actually sends a request to /// load "assets/hello%20world.png". However, on the web, if we try to load /// "assets/hello%20world.png", the request will be URL-decoded, we will /// request "assets/hello world.png", and the request will 404. Therefore, we /// must URL-encode the asset key *again* so when it is decoded, it is /// requesting the once-URL-encoded asset key. String getAssetUrl(String asset) { if (Uri.parse(asset).hasScheme) { return Uri.encodeFull(asset); } return Uri.encodeFull('$_baseUrl$assetsDir/$asset'); } /// Loads an asset and returns the server response. Future<Object> loadAsset(String asset) { return httpFetch(getAssetUrl(asset)); } /// Loads an asset using an [XMLHttpRequest] and returns data as [ByteData]. Future<ByteData> load(String asset) async { final String url = getAssetUrl(asset); final HttpFetchResponse response = await httpFetch(url); if (response.status == 404 && asset == 'AssetManifest.json') { printWarning('Asset manifest does not exist at `$url` - ignoring.'); return ByteData.sublistView(utf8.encode('{}')); } return (await response.payload.asByteBuffer()).asByteData(); } }
engine/lib/web_ui/lib/ui_web/src/ui_web/asset_manager.dart/0
{'file_path': 'engine/lib/web_ui/lib/ui_web/src/ui_web/asset_manager.dart', 'repo_id': 'engine', 'token_count': 1227}
// 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; import 'common.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } const ui.Rect region = ui.Rect.fromLTRB(0, 0, 500, 250); /// Test that we can render even if `createImageBitmap` is not supported. void testMain() { group('CanvasKit', () { setUpCanvasKitTest(withImplicitView: true); setUp(() async { EngineFlutterDisplay.instance.debugOverrideDevicePixelRatio(1.0); }); tearDown(() { debugDisableCreateImageBitmapSupport = false; debugIsChrome110OrOlder = null; }); test('can render without createImageBitmap', () async { debugDisableCreateImageBitmapSupport = true; expect(browserSupportsCreateImageBitmap, isFalse); final CkPictureRecorder recorder = CkPictureRecorder(); final CkCanvas canvas = recorder.beginRecording(region); final CkGradientLinear gradient = CkGradientLinear( ui.Offset(region.left + region.width / 4, region.height / 2), ui.Offset(region.right - region.width / 8, region.height / 2), const <ui.Color>[ ui.Color(0xFF4285F4), ui.Color(0xFF34A853), ui.Color(0xFFFBBC05), ui.Color(0xFFEA4335), ui.Color(0xFF4285F4), ], const <double>[ 0.0, 0.25, 0.5, 0.75, 1.0, ], ui.TileMode.clamp, null); final CkPaint paint = CkPaint()..shader = gradient; canvas.drawRect(region, paint); await matchPictureGolden( 'canvaskit_linear_gradient_no_create_image_bitmap.png', recorder.endRecording(), region: region, ); }); test( 'createImageBitmap support is disabled on ' 'Windows on Chrome version 110 or older', () async { debugIsChrome110OrOlder = true; debugDisableCreateImageBitmapSupport = false; expect(browserSupportsCreateImageBitmap, isFalse); }); }); }
engine/lib/web_ui/test/canvaskit/no_create_image_bitmap_test.dart/0
{'file_path': 'engine/lib/web_ui/test/canvaskit/no_create_image_bitmap_test.dart', 'repo_id': 'engine', 'token_count': 981}
// 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 '../common/mock_engine_canvas.dart'; import '../common/test_initialization.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } void testMain() { setUpUnitTests( withImplicitView: true, setUpTestViewDimensions: false, ); late RecordingCanvas underTest; late MockEngineCanvas mockCanvas; const Rect screenRect = Rect.largest; setUp(() { underTest = RecordingCanvas(screenRect); mockCanvas = MockEngineCanvas(); }); group('paragraph bounds', () { Paragraph paragraphForBoundsTest(TextAlign alignment) { final ParagraphBuilder builder = ParagraphBuilder(ParagraphStyle( fontFamily: 'Ahem', fontSize: 20, textAlign: alignment, )); builder.addText('A AAAAA AAA'); return builder.build(); } test('not laid out', () { final Paragraph paragraph = paragraphForBoundsTest(TextAlign.start); underTest.drawParagraph(paragraph, Offset.zero); underTest.endRecording(); expect(underTest.pictureBounds, Rect.zero); }); test('finite width', () { final Paragraph paragraph = paragraphForBoundsTest(TextAlign.start); paragraph.layout(const ParagraphConstraints(width: 110)); underTest.drawParagraph(paragraph, Offset.zero); underTest.endRecording(); expect(paragraph.width, 110); expect(paragraph.height, 60); expect(underTest.pictureBounds, const Rect.fromLTRB(0, 0, 100, 60)); }); test('finite width center-aligned', () { final Paragraph paragraph = paragraphForBoundsTest(TextAlign.center); paragraph.layout(const ParagraphConstraints(width: 110)); underTest.drawParagraph(paragraph, Offset.zero); underTest.endRecording(); expect(paragraph.width, 110); expect(paragraph.height, 60); expect(underTest.pictureBounds, const Rect.fromLTRB(5, 0, 105, 60)); }); test('infinite width', () { final Paragraph paragraph = paragraphForBoundsTest(TextAlign.start); paragraph.layout(const ParagraphConstraints(width: double.infinity)); underTest.drawParagraph(paragraph, Offset.zero); underTest.endRecording(); expect(paragraph.width, double.infinity); expect(paragraph.height, 20); expect(underTest.pictureBounds, const Rect.fromLTRB(0, 0, 220, 20)); }); }); group('drawDRRect', () { final RRect rrect = RRect.fromLTRBR(10, 10, 50, 50, const Radius.circular(3)); final SurfacePaint somePaint = SurfacePaint() ..color = const Color(0xFFFF0000); test('Happy case', () { underTest.drawDRRect(rrect, rrect.deflate(1), somePaint); underTest.endRecording(); underTest.apply(mockCanvas, screenRect); _expectDrawDRRectCall(mockCanvas, <String, dynamic>{ 'path': 'Path(' 'MoveTo(${10.0}, ${47.0}) ' 'LineTo(${10.0}, ${13.0}) ' 'Conic(${10.0}, ${10.0}, ${10.0}, ${13.0}, w = ${0.7071067690849304}) ' 'LineTo(${47.0}, ${10.0}) ' 'Conic(${50.0}, ${10.0}, ${10.0}, ${50.0}, w = ${0.7071067690849304}) ' 'LineTo(${50.0}, ${47.0}) ' 'Conic(${50.0}, ${50.0}, ${50.0}, ${47.0}, w = ${0.7071067690849304}) ' 'LineTo(${13.0}, ${50.0}) ' 'Conic(${10.0}, ${50.0}, ${50.0}, ${10.0}, w = ${0.7071067690849304}) ' 'Close() ' 'MoveTo(${11.0}, ${47.0}) ' 'LineTo(${11.0}, ${13.0}) ' 'Conic(${11.0}, ${11.0}, ${11.0}, ${13.0}, w = ${0.7071067690849304}) ' 'LineTo(${47.0}, ${11.0}) ' 'Conic(${49.0}, ${11.0}, ${11.0}, ${49.0}, w = ${0.7071067690849304}) ' 'LineTo(${49.0}, ${47.0}) ' 'Conic(${49.0}, ${49.0}, ${49.0}, ${47.0}, w = ${0.7071067690849304}) ' 'LineTo(${13.0}, ${49.0}) ' 'Conic(${11.0}, ${49.0}, ${49.0}, ${11.0}, w = ${0.7071067690849304}) ' 'Close()' ')', 'paint': somePaint.paintData, }); }); test('Inner RRect > Outer RRect', () { underTest.drawDRRect(rrect, rrect.inflate(1), somePaint); underTest.endRecording(); underTest.apply(mockCanvas, screenRect); // Expect nothing to be called expect(mockCanvas.methodCallLog.length, equals(1)); expect(mockCanvas.methodCallLog.single.methodName, 'endOfPaint'); }); test('Inner RRect not completely inside Outer RRect', () { underTest.drawDRRect( rrect, rrect.deflate(1).shift(const Offset(0.0, 10)), somePaint); underTest.endRecording(); underTest.apply(mockCanvas, screenRect); // Expect nothing to be called expect(mockCanvas.methodCallLog.length, equals(1)); expect(mockCanvas.methodCallLog.single.methodName, 'endOfPaint'); }); test('Inner RRect same as Outer RRect', () { underTest.drawDRRect(rrect, rrect, somePaint); underTest.endRecording(); underTest.apply(mockCanvas, screenRect); // Expect nothing to be called expect(mockCanvas.methodCallLog.length, equals(1)); expect(mockCanvas.methodCallLog.single.methodName, 'endOfPaint'); }); test('deflated corners in inner RRect get passed through to draw', () { // This comes from github issue #40728 final RRect outer = RRect.fromRectAndCorners( const Rect.fromLTWH(0, 0, 88, 48), topLeft: const Radius.circular(6), bottomLeft: const Radius.circular(6)); final RRect inner = outer.deflate(1); expect(inner.brRadius, equals(Radius.zero)); expect(inner.trRadius, equals(Radius.zero)); underTest.drawDRRect(outer, inner, somePaint); underTest.endRecording(); underTest.apply(mockCanvas, screenRect); // Expect to draw, even when inner has negative radii (which get ignored by canvas) _expectDrawDRRectCall(mockCanvas, <String, dynamic>{ 'path': 'Path(' 'MoveTo(${0.0}, ${42.0}) ' 'LineTo(${0.0}, ${6.0}) ' 'Conic(${0.0}, ${0.0}, ${0.0}, ${6.0}, w = ${0.7071067690849304}) ' 'LineTo(${88.0}, ${0.0}) ' 'Conic(${88.0}, ${0.0}, ${0.0}, ${88.0}, w = ${0.7071067690849304}) ' 'LineTo(${88.0}, ${48.0}) ' 'Conic(${88.0}, ${48.0}, ${48.0}, ${88.0}, w = ${0.7071067690849304}) ' 'LineTo(${6.0}, ${48.0}) ' 'Conic(${0.0}, ${48.0}, ${48.0}, ${0.0}, w = ${0.7071067690849304}) ' 'Close() ' 'MoveTo(${1.0}, ${42.0}) ' 'LineTo(${1.0}, ${6.0}) ' 'Conic(${1.0}, ${1.0}, ${1.0}, ${6.0}, w = ${0.7071067690849304}) ' 'LineTo(${87.0}, ${1.0}) ' 'Conic(${87.0}, ${1.0}, ${1.0}, ${87.0}, w = ${0.7071067690849304}) ' 'LineTo(${87.0}, ${47.0}) ' 'Conic(${87.0}, ${47.0}, ${47.0}, ${87.0}, w = ${0.7071067690849304}) ' 'LineTo(${6.0}, ${47.0}) ' 'Conic(${1.0}, ${47.0}, ${47.0}, ${1.0}, w = ${0.7071067690849304}) ' 'Close()' ')', 'paint': somePaint.paintData, }); }); test('preserve old golden test behavior', () { final RRect outer = RRect.fromRectAndCorners(const Rect.fromLTRB(10, 20, 30, 40)); final RRect inner = RRect.fromRectAndCorners(const Rect.fromLTRB(12, 22, 28, 38)); underTest.drawDRRect(outer, inner, somePaint); underTest.endRecording(); underTest.apply(mockCanvas, screenRect); _expectDrawDRRectCall(mockCanvas, <String, dynamic>{ 'path': 'Path(' 'MoveTo(${10.0}, ${20.0}) ' 'LineTo(${30.0}, ${20.0}) ' 'LineTo(${30.0}, ${40.0}) ' 'LineTo(${10.0}, ${40.0}) ' 'Close() ' 'MoveTo(${12.0}, ${22.0}) ' 'LineTo(${28.0}, ${22.0}) ' 'LineTo(${28.0}, ${38.0}) ' 'LineTo(${12.0}, ${38.0}) ' 'Close()' ')', 'paint': somePaint.paintData, }); }); }); test('Filters out paint commands outside the clip rect', () { // Outside to the left underTest.drawRect(const Rect.fromLTWH(0.0, 20.0, 10.0, 10.0), SurfacePaint()); // Outside above underTest.drawRect(const Rect.fromLTWH(20.0, 0.0, 10.0, 10.0), SurfacePaint()); // Visible underTest.drawRect(const Rect.fromLTWH(20.0, 20.0, 10.0, 10.0), SurfacePaint()); // Inside the layer clip rect but zero-size underTest.drawRect(const Rect.fromLTRB(20.0, 20.0, 30.0, 20.0), SurfacePaint()); // Inside the layer clip but clipped out by a canvas clip underTest.save(); underTest.clipRect(const Rect.fromLTWH(0, 0, 10, 10), ClipOp.intersect); underTest.drawRect(const Rect.fromLTWH(20.0, 20.0, 10.0, 10.0), SurfacePaint()); underTest.restore(); // Outside to the right underTest.drawRect(const Rect.fromLTWH(40.0, 20.0, 10.0, 10.0), SurfacePaint()); // Outside below underTest.drawRect(const Rect.fromLTWH(20.0, 40.0, 10.0, 10.0), SurfacePaint()); underTest.endRecording(); expect(underTest.debugPaintCommands, hasLength(10)); final PaintDrawRect outsideLeft = underTest.debugPaintCommands[0] as PaintDrawRect; expect(outsideLeft.isClippedOut, isFalse); expect(outsideLeft.leftBound, 0); expect(outsideLeft.topBound, 20); expect(outsideLeft.rightBound, 10); expect(outsideLeft.bottomBound, 30); final PaintDrawRect outsideAbove = underTest.debugPaintCommands[1] as PaintDrawRect; expect(outsideAbove.isClippedOut, isFalse); final PaintDrawRect visible = underTest.debugPaintCommands[2] as PaintDrawRect; expect(visible.isClippedOut, isFalse); final PaintDrawRect zeroSize = underTest.debugPaintCommands[3] as PaintDrawRect; expect(zeroSize.isClippedOut, isTrue); expect(underTest.debugPaintCommands[4], isA<PaintSave>()); final PaintClipRect clip = underTest.debugPaintCommands[5] as PaintClipRect; expect(clip.isClippedOut, isFalse); final PaintDrawRect clippedOut = underTest.debugPaintCommands[6] as PaintDrawRect; expect(clippedOut.isClippedOut, isTrue); expect(underTest.debugPaintCommands[7], isA<PaintRestore>()); final PaintDrawRect outsideRight = underTest.debugPaintCommands[8] as PaintDrawRect; expect(outsideRight.isClippedOut, isFalse); final PaintDrawRect outsideBelow = underTest.debugPaintCommands[9] as PaintDrawRect; expect(outsideBelow.isClippedOut, isFalse); // Give it the entire screen so everything paints. underTest.apply(mockCanvas, screenRect); expect(mockCanvas.methodCallLog, hasLength(11)); expect(mockCanvas.methodCallLog[0].methodName, 'drawRect'); expect(mockCanvas.methodCallLog[1].methodName, 'drawRect'); expect(mockCanvas.methodCallLog[2].methodName, 'drawRect'); expect(mockCanvas.methodCallLog[3].methodName, 'drawRect'); expect(mockCanvas.methodCallLog[4].methodName, 'save'); expect(mockCanvas.methodCallLog[5].methodName, 'clipRect'); expect(mockCanvas.methodCallLog[6].methodName, 'drawRect'); expect(mockCanvas.methodCallLog[7].methodName, 'restore'); expect(mockCanvas.methodCallLog[8].methodName, 'drawRect'); expect(mockCanvas.methodCallLog[9].methodName, 'drawRect'); expect(mockCanvas.methodCallLog[10].methodName, 'endOfPaint'); // Clip out a middle region that only contains 'drawRect' mockCanvas.methodCallLog.clear(); underTest.apply(mockCanvas, const Rect.fromLTRB(15, 15, 35, 35)); expect(mockCanvas.methodCallLog, hasLength(4)); expect(mockCanvas.methodCallLog[0].methodName, 'drawRect'); expect(mockCanvas.methodCallLog[1].methodName, 'save'); expect(mockCanvas.methodCallLog[2].methodName, 'restore'); expect(mockCanvas.methodCallLog[3].methodName, 'endOfPaint'); }); // Regression test for https://github.com/flutter/flutter/issues/61697. test('Allows restore calls after recording has ended', () { final RecordingCanvas rc = RecordingCanvas(const Rect.fromLTRB(0, 0, 200, 400)); rc.endRecording(); // Should not throw exception on restore. expect(() => rc.restore(), returnsNormally); }); // Regression test for https://github.com/flutter/flutter/issues/61697. test('Allows restore calls even if recording is not ended', () { final RecordingCanvas rc = RecordingCanvas(const Rect.fromLTRB(0, 0, 200, 400)); // Should not throw exception on restore. expect(() => rc.restore(), returnsNormally); }); } // Expect a drawDRRect call to be registered in the mock call log, with the expectedArguments void _expectDrawDRRectCall( MockEngineCanvas mock, Map<String, dynamic> expectedArguments) { expect(mock.methodCallLog.length, equals(2)); final MockCanvasCall mockCall = mock.methodCallLog[0]; expect(mockCall.methodName, equals('drawPath')); final Map<String, dynamic> argMap = mockCall.arguments as Map<String, dynamic>; final Map<String, dynamic> argContents = <String, dynamic>{}; argMap.forEach((String key, dynamic value) { argContents[key] = value is SurfacePath ? value.toString() : value; }); expect(argContents, equals(expectedArguments)); }
engine/lib/web_ui/test/engine/recording_canvas_test.dart/0
{'file_path': 'engine/lib/web_ui/test/engine/recording_canvas_test.dart', 'repo_id': 'engine', 'token_count': 5694}
// 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_util' as js_util; 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'; void main() { internalBootstrapBrowserTest(() => testMain); } Future<void> testMain() async { setUpUnitTests( setUpTestViewDimensions: false, ); test('Blend circles with difference and color', () async { final RecordingCanvas rc = RecordingCanvas(const Rect.fromLTRB(0, 0, 400, 300)); rc.save(); rc.drawRect( const Rect.fromLTRB(0, 0, 400, 400), SurfacePaint() ..style = PaintingStyle.fill ..color = const Color.fromARGB(255, 255, 255, 255)); rc.drawCircle( const Offset(100, 100), 80.0, SurfacePaint() ..style = PaintingStyle.fill ..color = const Color.fromARGB(128, 255, 0, 0) ..blendMode = BlendMode.difference); rc.drawCircle( const Offset(170, 100), 80.0, SurfacePaint() ..style = PaintingStyle.fill ..blendMode = BlendMode.color ..color = const Color.fromARGB(128, 0, 255, 0)); rc.drawCircle( const Offset(135, 170), 80.0, SurfacePaint() ..style = PaintingStyle.fill ..color = const Color.fromARGB(128, 255, 0, 0)); rc.restore(); await canvasScreenshot(rc, 'canvas_blend_circle_diff_color'); }); test('Blend circle and text with multiply', () async { final RecordingCanvas rc = RecordingCanvas(const Rect.fromLTRB(0, 0, 400, 300)); rc.save(); rc.drawRect( const Rect.fromLTRB(0, 0, 400, 400), SurfacePaint() ..style = PaintingStyle.fill ..color = const Color.fromARGB(255, 255, 255, 255)); rc.drawCircle( const Offset(100, 100), 80.0, SurfacePaint() ..style = PaintingStyle.fill ..color = const Color.fromARGB(128, 255, 0, 0) ..blendMode = BlendMode.difference); rc.drawCircle( const Offset(170, 100), 80.0, SurfacePaint() ..style = PaintingStyle.fill ..blendMode = BlendMode.color ..color = const Color.fromARGB(128, 0, 255, 0)); rc.drawCircle( const Offset(135, 170), 80.0, SurfacePaint() ..style = PaintingStyle.fill ..color = const Color.fromARGB(128, 255, 0, 0)); rc.drawImage(createTestImage(), const Offset(135.0, 130.0), SurfacePaint()..blendMode = BlendMode.multiply); rc.restore(); await canvasScreenshot(rc, 'canvas_blend_image_multiply'); }); } HtmlImage createTestImage() { const int width = 100; const int height = 50; final DomCanvasElement canvas = createDomCanvasElement(width: width, height: height); final DomCanvasRenderingContext2D ctx = canvas.context2D; ctx.fillStyle = '#E04040'; ctx.fillRect(0, 0, 33, 50); ctx.fill(); ctx.fillStyle = '#40E080'; ctx.fillRect(33, 0, 33, 50); ctx.fill(); ctx.fillStyle = '#2040E0'; ctx.fillRect(66, 0, 33, 50); ctx.fill(); final DomHTMLImageElement imageElement = createDomHTMLImageElement(); imageElement.src = js_util.callMethod<String>(canvas, 'toDataURL', <dynamic>[]); return HtmlImage(imageElement, width, height); }
engine/lib/web_ui/test/html/compositing/canvas_blend_golden_test.dart/0
{'file_path': 'engine/lib/web_ui/test/html/compositing/canvas_blend_golden_test.dart', 'repo_id': 'engine', 'token_count': 1520}
// 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 '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(0, 0, 300, 300); late BitmapCanvas canvas; setUp(() { canvas = BitmapCanvas(region, RenderStrategy()); }); tearDown(() { canvas.rootElement.remove(); }); test('draws rects side by side with fill and stroke', () async { paintSideBySideRects(canvas); domDocument.body!.append(canvas.rootElement); await matchGoldenFile('canvas_stroke_rects.png', region: region); }); } void paintSideBySideRects(BitmapCanvas canvas) { canvas.drawRect(const Rect.fromLTRB(0, 0, 300, 300), SurfacePaintData() ..color = 0xFFFFFFFF ..style = PaintingStyle.fill); // white canvas.drawRect(const Rect.fromLTRB(0, 20, 40, 60), SurfacePaintData() ..style = PaintingStyle.fill ..color = 0x7f0000ff); canvas.drawRect(const Rect.fromLTRB(40, 20, 80, 60), SurfacePaintData() ..style = PaintingStyle.stroke ..strokeWidth = 4 ..color = 0x7fff0000); // Rotate 30 degrees (in rad: deg*pi/180) canvas.transform(Matrix4.rotationZ(30.0 * math.pi / 180.0).storage); canvas.drawRect(const Rect.fromLTRB(100, 60, 140, 100), SurfacePaintData() ..style = PaintingStyle.fill ..color = 0x7fff00ff); canvas.drawRect(const Rect.fromLTRB(140, 60, 180, 100), SurfacePaintData() ..style = PaintingStyle.stroke ..strokeWidth = 4 ..color = 0x7fffff00); }
engine/lib/web_ui/test/html/drawing/canvas_stroke_rects_golden_test.dart/0
{'file_path': 'engine/lib/web_ui/test/html/drawing/canvas_stroke_rects_golden_test.dart', 'repo_id': 'engine', 'token_count': 780}
// 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/matchers.dart'; import '../common/test_initialization.dart'; import 'screenshot.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } Future<void> testMain() async { const double screenWidth = 600.0; const double screenHeight = 800.0; const Rect screenRect = Rect.fromLTWH(0, 0, screenWidth, screenHeight); const Color black12Color = Color(0x1F000000); const Color redAccentColor = Color(0xFFFF1744); const double kDashLength = 5.0; setUpUnitTests( setUpTestViewDimensions: false, ); test('Should calculate tangent on line', () async { final Path path = Path(); path.moveTo(50, 130); path.lineTo(150, 20); final PathMetric metric = path.computeMetrics().first; final Tangent t = metric.getTangentForOffset(50.0)!; expect(t.position.dx, within(from: 83.633, distance: 0.01)); expect(t.position.dy, within(from: 93.0, distance: 0.01)); expect(t.vector.dx, within(from: 0.672, distance: 0.01)); expect(t.vector.dy, within(from: -0.739, distance: 0.01)); }); test('Should calculate tangent on cubic curve', () async { final Path path = Path(); const double p1x = 240; const double p1y = 120; const double p2x = 320; const double p2y = 25; path.moveTo(150, 20); path.quadraticBezierTo(p1x, p1y, p2x, p2y); final PathMetric metric = path.computeMetrics().first; final Tangent t = metric.getTangentForOffset(50.0)!; expect(t.position.dx, within(from: 187.25, distance: 0.01)); expect(t.position.dy, within(from: 53.33, distance: 0.01)); expect(t.vector.dx, within(from: 0.82, distance: 0.01)); expect(t.vector.dy, within(from: 0.56, distance: 0.01)); }); test('Should calculate tangent on quadratic curve', () async { final Path path = Path(); const double p0x = 150; const double p0y = 20; const double p1x = 320; const double p1y = 25; path.moveTo(150, 20); path.quadraticBezierTo(p0x, p0y, p1x, p1y); final PathMetric metric = path.computeMetrics().first; final Tangent t = metric.getTangentForOffset(50.0)!; expect(t.position.dx, within(from: 199.82, distance: 0.01)); expect(t.position.dy, within(from: 21.46, distance: 0.01)); expect(t.vector.dx, within(from: 0.99, distance: 0.01)); expect(t.vector.dy, within(from: 0.02, distance: 0.01)); }); // Test for extractPath to draw 5 pixel length dashed line using quad curve. test('Should draw dashed line on quadratic curve.', () async { final RecordingCanvas rc = RecordingCanvas(const Rect.fromLTRB(0, 0, 500, 500)); final SurfacePaint paint = SurfacePaint() ..style = PaintingStyle.stroke ..strokeWidth = 3 ..color = black12Color; final SurfacePaint redPaint = SurfacePaint() ..style = PaintingStyle.stroke ..strokeWidth = 1 ..color = redAccentColor; final SurfacePath path = SurfacePath(); path.moveTo(50, 130); path.lineTo(150, 20); const double p1x = 240; const double p1y = 120; const double p2x = 320; const double p2y = 25; path.quadraticBezierTo(p1x, p1y, p2x, p2y); rc.drawPath(path, paint); const double t0 = 0.2; const double t1 = 0.7; final List<PathMetric> metrics = path.computeMetrics().toList(); double totalLength = 0; for (final PathMetric m in metrics) { totalLength += m.length; } final Path dashedPath = Path(); for (final PathMetric measurePath in path.computeMetrics()) { double distance = totalLength * t0; bool draw = true; while (distance < measurePath.length * t1) { const double length = kDashLength; if (draw) { dashedPath.addPath( measurePath.extractPath(distance, distance + length), Offset.zero); } distance += length; draw = !draw; } } rc.drawPath(dashedPath, redPaint); await canvasScreenshot(rc, 'path_dash_quadratic', canvasRect: screenRect); }); // Test for extractPath to draw 5 pixel length dashed line using cubic curve. test('Should draw dashed line on cubic curve.', () async { final RecordingCanvas rc = RecordingCanvas(const Rect.fromLTRB(0, 0, 500, 500)); final SurfacePaint paint = SurfacePaint() ..style = PaintingStyle.stroke ..strokeWidth = 3 ..color = black12Color; final SurfacePaint redPaint = SurfacePaint() ..style = PaintingStyle.stroke ..strokeWidth = 1 ..color = redAccentColor; final Path path = Path(); path.moveTo(50, 130); path.lineTo(150, 20); const double p1x = 40; const double p1y = 120; const double p2x = 300; const double p2y = 130; const double p3x = 320; const double p3y = 25; path.cubicTo(p1x, p1y, p2x, p2y, p3x, p3y); rc.drawPath(path, paint); const double t0 = 0.2; const double t1 = 0.7; final List<PathMetric> metrics = path.computeMetrics().toList(); double totalLength = 0; for (final PathMetric m in metrics) { totalLength += m.length; } final Path dashedPath = Path(); for (final PathMetric measurePath in path.computeMetrics()) { double distance = totalLength * t0; bool draw = true; while (distance < measurePath.length * t1) { const double length = kDashLength; if (draw) { dashedPath.addPath( measurePath.extractPath(distance, distance + length), Offset.zero); } distance += length; draw = !draw; } } rc.drawPath(dashedPath, redPaint); await canvasScreenshot(rc, 'path_dash_cubic', canvasRect: screenRect); }); }
engine/lib/web_ui/test/html/path_metrics_golden_test.dart/0
{'file_path': 'engine/lib/web_ui/test/html/path_metrics_golden_test.dart', 'repo_id': 'engine', 'token_count': 2357}