code
stringlengths 8
3.25M
| repository
stringlengths 15
175
| metadata
stringlengths 66
249
|
---|---|---|
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
library dartpad.parameter_popup;
import 'dart:convert';
import 'dart:html';
import 'dart:math' as math;
import 'context.dart';
import 'dart_pad.dart';
import 'editing/editor.dart';
import 'services/common.dart';
import 'services/dartservices.dart';
class ParameterPopup {
static const List parKeys = [
KeyCode.COMMA,
KeyCode.NINE,
KeyCode.ZERO,
KeyCode.LEFT,
KeyCode.RIGHT,
KeyCode.UP,
KeyCode.DOWN
];
final Context context;
final Editor editor;
final HtmlEscape sanitizer = const HtmlEscape();
ParameterPopup(this.context, this.editor) {
document.onKeyDown.listen(_handleKeyDown);
document.onKeyUp.listen(_handleKeyUp);
document.onClick.listen((e) => _handleClick());
editor.onMouseDown.listen((e) => _handleClick());
}
bool get parPopupActive => querySelector('.parameter-hints') != null;
void remove() {
document.body.children.remove(querySelector('.parameter-hints'));
}
void _handleKeyDown(KeyboardEvent e) {
if (e.keyCode == KeyCode.ENTER) {
// TODO: Use the onClose event of the completion event to trigger this
_lookupParameterInfo();
}
}
void _handleKeyUp(KeyboardEvent e) {
if (e.keyCode == KeyCode.ESC ||
context.focusedEditor != 'dart' ||
!editor.hasFocus) {
remove();
} else if (parPopupActive || parKeys.contains(e.keyCode)) {
_lookupParameterInfo();
}
}
void _handleClick() {
if (context.focusedEditor != 'dart' || !editor.hasFocus) {
remove();
} else {
_lookupParameterInfo();
}
}
void _lookupParameterInfo() {
var offset = editor.document.indexFromPos(editor.document.cursor);
var source = editor.document.value;
var parInfo = _parameterInfo(source, offset);
if (parInfo == null) {
remove();
return;
}
var openingParenIndex = parInfo['openingParenIndex'];
var parameterIndex = parInfo['parameterIndex'];
offset = openingParenIndex - 1;
// We request documentation info of what is before the parenthesis.
var input = SourceRequest()
..source = source
..offset = offset;
dartServices
.document(input)
.timeout(serviceCallTimeout)
.then((DocumentResponse result) {
if (!result.info.containsKey('parameters')) {
remove();
return;
}
var parameterInfo = result.info['parameters'];
var outputString = '';
if (parameterInfo.isEmpty) {
outputString += '<code><no parameters></code>';
} else if (parameterInfo.length < parameterIndex + 1) {
outputString += '<code>too many parameters listed</code>';
} else {
outputString += '<code>';
for (var i = 0; i < parameterInfo.length; i++) {
if (i == parameterIndex) {
outputString += '<em>${sanitizer.convert(parameterInfo[i])}</em>';
} else {
outputString +=
'<span>${sanitizer.convert(parameterInfo[i])}</span>';
}
if (i != parameterInfo.length - 1) {
outputString += ', ';
}
}
outputString += '</code>';
}
// Check if cursor is still in parameter position
parInfo = _parameterInfo(editor.document.value,
editor.document.indexFromPos(editor.document.cursor));
if (parInfo == null) {
remove();
return;
}
_showParameterPopup(outputString, offset);
});
}
void _showParameterPopup(String string, int methodOffset) {
var editorDiv = querySelector('#editpanel .CodeMirror') as DivElement;
var lineHeightStr =
editorDiv.getComputedStyle().getPropertyValue('line-height');
var lineHeight =
int.parse(lineHeightStr.substring(0, lineHeightStr.indexOf('px')));
// var charWidth = editorDiv.getComputedStyle().getPropertyValue('letter-spacing');
var charWidth = 8;
var methodPosition = editor.document.posFromIndex(methodOffset);
var cursorCoords = editor.getCursorCoords();
var methodCoords = editor.getCursorCoords(position: methodPosition);
var heightOfMethod = (methodCoords.y - lineHeight - 5).round();
DivElement parameterPopup;
if (parPopupActive) {
var parameterHint = querySelector('.parameter-hint');
parameterHint.innerHtml = string;
//update popup position
var newLeft = math
.max(cursorCoords.x - (parameterHint.text.length * charWidth / 2), 22)
.round();
parameterPopup = querySelector('.parameter-hints') as DivElement
..style.top = '${heightOfMethod}px';
var oldLeftString = parameterPopup.style.left;
var oldLeft =
int.parse(oldLeftString.substring(0, oldLeftString.indexOf('px')));
if ((newLeft - oldLeft).abs() > 50) {
parameterPopup.style.left = '${newLeft}px';
}
} else {
var parameterHint = SpanElement()
..innerHtml = string
..classes.add('parameter-hint');
var left = math
.max(cursorCoords.x - (parameterHint.text.length * charWidth / 2), 22)
.round();
parameterPopup = DivElement()
..classes.add('parameter-hints')
..style.left = '${left}px'
..style.top = '${heightOfMethod}px'
..style.maxWidth =
"${querySelector("#editpanel").getBoundingClientRect().width}px";
parameterPopup.append(parameterHint);
document.body.append(parameterPopup);
}
var activeParameter = querySelector('.parameter-hints em');
if (activeParameter != null &&
activeParameter.previousElementSibling != null) {
parameterPopup.scrollLeft =
activeParameter.previousElementSibling.offsetLeft;
}
}
/// Returns null if the offset is not contained in parenthesis.
/// Otherwise it will return information about the parameters.
/// For example, if the source is `substring(1, <caret>)`, it will return
/// `{openingParenIndex: 9, parameterIndex: 1}`.
Map<String, int> _parameterInfo(String source, int offset) {
var parameterIndex = 0;
var openingParenIndex;
var nesting = 0;
while (openingParenIndex == null && offset > 0) {
offset += -1;
if (nesting == 0) {
switch (source[offset]) {
case '(':
openingParenIndex = offset;
break;
case ',':
parameterIndex += 1;
break;
case ';':
return null;
case ')':
nesting += 1;
break;
}
} else {
switch (source[offset]) {
case '(':
nesting += -1;
break;
case ')':
nesting += 1;
break;
}
}
}
return openingParenIndex == null
? null
: {
'openingParenIndex': openingParenIndex as int,
'parameterIndex': parameterIndex
};
}
}
| dart-pad/lib/parameter_popup.dart/0 | {'file_path': 'dart-pad/lib/parameter_popup.dart', 'repo_id': 'dart-pad', 'token_count': 2928} |
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
library dart_pad.ga;
import 'dart:js';
/// Very lightweight Google Analytics integration. This class depends on having
/// the JavaScript GA library available.
class Analytics {
Analytics();
bool get isAvailable => _gaFunction != null;
void sendPage({String pageName}) {
if (pageName != null && pageName.isNotEmpty) {
_ga2('send', 'pageview');
} else {
_ga3('send', 'pageview', pageName);
}
}
void sendEvent(String category, String action, {String label}) {
var m = <String, dynamic>{
'hitType': 'event',
'eventCategory': category,
'eventAction': action,
};
if (label != null) m['eventLabel'] = label;
_ga('send', m);
}
void sendTiming(String category, String variable, int valueMillis,
{String label}) {
var m = <String, dynamic>{
'hitType': 'timing',
'timingCategory': category,
'timingVar': variable,
'timingValue': valueMillis
};
if (label != null) m['timingLabel'] = label;
_ga('send', m);
}
void sendException(String description, {bool fatal}) {
var m = <String, dynamic>{
'exDescription': description,
};
if (fatal != null) m['exFatal'] = fatal;
_ga2('send', 'exception', m);
}
void _ga(String method, [Map args]) {
if (isAvailable) {
var params = <dynamic>[method];
if (args != null) params.add(JsObject.jsify(args));
_gaFunction.apply(params);
}
}
void _ga2(String method, String type, [Map args]) {
if (isAvailable) {
var params = <dynamic>[method, type];
if (args != null) params.add(JsObject.jsify(args));
_gaFunction.apply(params);
}
}
void _ga3(String method, String type, String arg, [Map args]) {
if (isAvailable) {
var params = <dynamic>[method, type, arg];
if (args != null) params.add(JsObject.jsify(args));
_gaFunction.apply(params);
}
}
JsFunction get _gaFunction => context['ga'] as JsFunction;
}
| dart-pad/lib/src/ga.dart/0 | {'file_path': 'dart-pad/lib/src/ga.dart', 'repo_id': 'dart-pad', 'token_count': 810} |
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
@TestOn('browser')
library dartpad.documentation_test;
import 'package:dart_pad/documentation.dart';
import 'package:test/test.dart';
void main() => defineTests();
void defineTests() {
group('documentation', () {
// Verify that the MDN documentation address hasn't changed.
test('MDN link exists', () {
return createMdnMarkdownLink('HTMLDivElement').then((linkText) {
expect(linkText, contains('HTMLDivElement'));
});
});
test('MDN no link', () {
return createMdnMarkdownLink('FooBar').then((linkText) {
expect(linkText, null);
});
});
});
}
| dart-pad/test/documentation_test.dart/0 | {'file_path': 'dart-pad/test/documentation_test.dart', 'repo_id': 'dart-pad', 'token_count': 283} |
// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
/// A wrapper around an analysis server instance
library services.analysis_server;
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:analysis_server_lib/analysis_server_lib.dart';
import 'package:logging/logging.dart';
import 'package:path/path.dart' as path;
import 'common.dart';
import 'flutter_web.dart';
import 'protos/dart_services.pb.dart' as proto;
import 'pub.dart';
import 'scheduler.dart';
final Logger _logger = Logger('analysis_server');
/// Flag to determine whether we should dump the communication with the server
/// to stdout.
bool dumpServerMessages = false;
const String _WARMUP_SRC_HTML =
"import 'dart:html'; main() { int b = 2; b++; b. }";
const String _WARMUP_SRC = 'main() { int b = 2; b++; b. }';
// Use very long timeouts to ensure that the server has enough time to restart.
const Duration _ANALYSIS_SERVER_TIMEOUT = Duration(seconds: 35);
class AnalysisServerWrapper {
final String sdkPath;
final FlutterWebManager flutterWebManager;
Future<AnalysisServer> _init;
String mainPath;
TaskScheduler serverScheduler;
/// Instance to handle communication with the server.
AnalysisServer analysisServer;
AnalysisServerWrapper(this.sdkPath, this.flutterWebManager) {
_logger.info('AnalysisServerWrapper ctor');
mainPath = _getPathFromName(kMainDart);
serverScheduler = TaskScheduler();
}
String get _sourceDirPath => flutterWebManager.projectDirectory.path;
Future<AnalysisServer> init() {
if (_init == null) {
void onRead(String str) {
if (dumpServerMessages) _logger.info('<-- $str');
}
void onWrite(String str) {
if (dumpServerMessages) _logger.info('--> $str');
}
final serverArgs = <String>[
'--dartpad',
'--client-id=DartPad',
'--client-version=$_sdkVersion'
];
_logger.info(
'About to start with server with SDK path `$sdkPath` and args: $serverArgs');
_init = AnalysisServer.create(
onRead: onRead,
onWrite: onWrite,
sdkPath: sdkPath,
serverArgs: serverArgs,
).then((AnalysisServer server) async {
analysisServer = server;
analysisServer.server.onError.listen((ServerError error) {
_logger.severe('server error${error.isFatal ? ' (fatal)' : ''}',
error.message, StackTrace.fromString(error.stackTrace));
});
await analysisServer.server.onConnected.first;
await analysisServer.server.setSubscriptions(<String>['STATUS']);
listenForCompletions();
listenForAnalysisComplete();
listenForErrors();
final analysisComplete = getAnalysisCompleteCompleter();
await analysisServer.analysis
.setAnalysisRoots(<String>[_sourceDirPath], <String>[]);
await _sendAddOverlays(<String, String>{mainPath: _WARMUP_SRC});
await analysisComplete.future;
await _sendRemoveOverlays();
return analysisServer;
}).catchError((err, st) {
_logger.severe('Error starting analysis server ($sdkPath): $err.\n$st');
});
}
return _init;
}
String get _sdkVersion {
return File(path.join(sdkPath, 'version')).readAsStringSync().trim();
}
Future<int> get onExit {
// Return when the analysis server exits. We introduce a delay so that when
// we terminate the analysis server we can exit normally.
return analysisServer.processCompleter.future.then((int code) {
return Future<int>.delayed(const Duration(seconds: 1), () {
return code;
});
});
}
Future<proto.CompleteResponse> complete(String src, int offset) async {
final sources = <String, String>{kMainDart: src};
final location = Location(kMainDart, offset);
final results =
await _completeImpl(sources, location.sourceName, location.offset);
var suggestions = results.results;
final source = sources[location.sourceName];
final prefix = source.substring(results.replacementOffset, location.offset);
suggestions = suggestions
.where(
(s) => s.completion.toLowerCase().startsWith(prefix.toLowerCase()))
// This hack filters out of scope completions. It needs removing when we
// have categories of completions.
// TODO(devoncarew): Remove this filter code.
.where((CompletionSuggestion c) => c.relevance > 500)
.toList();
suggestions.sort((CompletionSuggestion x, CompletionSuggestion y) {
if (x.relevance == y.relevance) {
return x.completion.compareTo(y.completion);
} else {
return y.relevance.compareTo(x.relevance);
}
});
return proto.CompleteResponse()
..replacementOffset = results.replacementOffset
..replacementLength = results.replacementLength
..completions
.addAll(suggestions.map((CompletionSuggestion c) => proto.Completion()
..completion.addAll(c.toMap().map((key, value) {
// TODO: Properly support Lists, Maps (this is a hack).
if (value is Map || value is List) {
value = json.encode(value);
}
return MapEntry(key.toString(), value.toString());
}))));
}
Future<proto.FixesResponse> getFixes(String src, int offset) {
return getFixesMulti(
<String, String>{kMainDart: src},
Location(kMainDart, offset),
);
}
Future<proto.FixesResponse> getFixesMulti(
Map<String, String> sources, Location location) async {
final results =
await _getFixesImpl(sources, location.sourceName, location.offset);
final responseFixes = results.fixes.map(_convertAnalysisErrorFix);
return proto.FixesResponse()..fixes.addAll(responseFixes);
}
Future<proto.AssistsResponse> getAssists(String src, int offset) async {
final sources = {kMainDart: src};
final sourceName = Location(kMainDart, offset).sourceName;
final results = await _getAssistsImpl(sources, sourceName, offset);
final fixes = _convertSourceChangesToCandidateFixes(results.assists);
return proto.AssistsResponse()..assists.addAll(fixes);
}
Future<proto.FormatResponse> format(String src, int offset) {
return _formatImpl(src, offset).then((FormatResult editResult) {
final edits = editResult.edits;
edits.sort((SourceEdit e1, SourceEdit e2) =>
-1 * e1.offset.compareTo(e2.offset));
for (final edit in edits) {
src = src.replaceRange(
edit.offset, edit.offset + edit.length, edit.replacement);
}
return proto.FormatResponse()
..newString = src
..offset = editResult.selectionOffset;
}).catchError((dynamic error) {
_logger.fine('format error: $error');
return proto.FormatResponse()
..newString = src
..offset = offset;
});
}
Future<Map<String, String>> dartdoc(String source, int offset) {
_logger.fine('dartdoc: Scheduler queue: ${serverScheduler.queueCount}');
return serverScheduler.schedule(ClosureTask<Map<String, String>>(() async {
final analysisCompleter = getAnalysisCompleteCompleter();
await _loadSources(<String, String>{mainPath: source});
await analysisCompleter.future;
final result = await analysisServer.analysis.getHover(mainPath, offset);
await _unloadSources();
if (result.hovers.isEmpty) {
return null;
}
final info = result.hovers.first;
final m = <String, String>{};
m['description'] = info.elementDescription;
m['kind'] = info.elementKind;
m['dartdoc'] = info.dartdoc;
m['enclosingClassName'] = info.containingClassDescription;
m['libraryName'] = info.containingLibraryName;
m['deprecated'] = info.parameter;
if (info.isDeprecated != null) m['deprecated'] = '${info.isDeprecated}';
m['staticType'] = info.staticType;
m['propagatedType'] = info.propagatedType;
for (final key in m.keys.toList()) {
if (m[key] == null) m.remove(key);
}
return m;
}, timeoutDuration: _ANALYSIS_SERVER_TIMEOUT));
}
Future<proto.AnalysisResults> analyze(String source) {
var sources = <String, String>{kMainDart: source};
_logger
.fine('analyzeMulti: Scheduler queue: ${serverScheduler.queueCount}');
return serverScheduler
.schedule(ClosureTask<proto.AnalysisResults>(() async {
clearErrors();
final analysisCompleter = getAnalysisCompleteCompleter();
sources = _getOverlayMapWithPaths(sources);
await _loadSources(sources);
await analysisCompleter.future;
// Calculate the issues.
final issues = getErrors().map((AnalysisError error) {
return proto.AnalysisIssue()
..kind = error.severity.toLowerCase()
..line = error.location.startLine
..message = error.message
..sourceName = path.basename(error.location.file)
..hasFixes = error.hasFix
..charStart = error.location.offset
..charLength = error.location.length;
}).toList();
issues.sort((a, b) {
// Order issues by character position of the bug/warning.
return a.charStart.compareTo(b.charStart);
});
// Calculate the imports.
final packageImports = <String>{};
for (final source in sources.values) {
packageImports
.addAll(filterSafePackagesFromImports(getAllImportsFor(source)));
}
return proto.AnalysisResults()
..issues.addAll(issues)
..packageImports.addAll(packageImports);
}, timeoutDuration: _ANALYSIS_SERVER_TIMEOUT));
}
Future<AssistsResult> _getAssistsImpl(
Map<String, String> sources, String sourceName, int offset) {
sources = _getOverlayMapWithPaths(sources);
final path = _getPathFromName(sourceName);
if (serverScheduler.queueCount > 0) {
_logger.fine(
'getRefactoringsImpl: Scheduler queue: ${serverScheduler.queueCount}');
}
return serverScheduler.schedule(ClosureTask<AssistsResult>(() async {
final analysisCompleter = getAnalysisCompleteCompleter();
await _loadSources(sources);
await analysisCompleter.future;
const length = 1;
final assists =
await analysisServer.edit.getAssists(path, offset, length);
await _unloadSources();
return assists;
}, timeoutDuration: _ANALYSIS_SERVER_TIMEOUT));
}
/// Convert between the Analysis Server type and the API protocol types.
static proto.ProblemAndFixes _convertAnalysisErrorFix(
AnalysisErrorFixes analysisFixes) {
final problemMessage = analysisFixes.error.message;
final problemOffset = analysisFixes.error.location.offset;
final problemLength = analysisFixes.error.location.length;
final possibleFixes = <proto.CandidateFix>[];
for (final sourceChange in analysisFixes.fixes) {
final edits = <proto.SourceEdit>[];
// A fix that tries to modify other files is considered invalid.
var invalidFix = false;
for (final sourceFileEdit in sourceChange.edits) {
// TODO(lukechurch): replace this with a more reliable test based on the
// psuedo file name in Analysis Server
if (!sourceFileEdit.file.endsWith('/main.dart')) {
invalidFix = true;
break;
}
for (final sourceEdit in sourceFileEdit.edits) {
edits.add(proto.SourceEdit()
..offset = sourceEdit.offset
..length = sourceEdit.length
..replacement = sourceEdit.replacement);
}
}
if (!invalidFix) {
final possibleFix = proto.CandidateFix()
..message = sourceChange.message
..edits.addAll(edits);
possibleFixes.add(possibleFix);
}
}
return proto.ProblemAndFixes()
..fixes.addAll(possibleFixes)
..problemMessage = problemMessage
..offset = problemOffset
..length = problemLength;
}
static List<proto.CandidateFix> _convertSourceChangesToCandidateFixes(
List<SourceChange> sourceChanges) {
final assists = <proto.CandidateFix>[];
for (final sourceChange in sourceChanges) {
for (final sourceFileEdit in sourceChange.edits) {
if (!sourceFileEdit.file.endsWith('/main.dart')) {
break;
}
final sourceEdits = sourceFileEdit.edits.map((sourceEdit) {
return proto.SourceEdit()
..offset = sourceEdit.offset
..length = sourceEdit.length
..replacement = sourceEdit.replacement;
});
final candidateFix = proto.CandidateFix();
candidateFix.message = sourceChange.message;
candidateFix.edits.addAll(sourceEdits);
final selectionOffset = sourceChange.selection?.offset;
if (selectionOffset != null) {
candidateFix.selectionOffset = selectionOffset;
}
candidateFix.linkedEditGroups
.addAll(_convertLinkedEditGroups(sourceChange.linkedEditGroups));
assists.add(candidateFix);
}
}
return assists;
}
/// Convert a list of the analysis server's [LinkedEditGroup]s into the API's
/// equivalent.
static Iterable<proto.LinkedEditGroup> _convertLinkedEditGroups(
Iterable<LinkedEditGroup> groups) {
return groups?.map<proto.LinkedEditGroup>((g) {
return proto.LinkedEditGroup()
..positions.addAll(g.positions?.map((p) => p.offset)?.toList())
..length = g.length
..suggestions.addAll(g.suggestions
?.map((s) => proto.LinkedEditSuggestion()
..value = s.value
..kind = s.kind)
?.toList());
}) ??
[];
}
/// Cleanly shutdown the Analysis Server.
Future<dynamic> shutdown() {
// TODO(jcollins-g): calling dispose() sometimes prevents
// --pause-isolates-on-exit from working; fix.
return analysisServer.server
.shutdown()
.timeout(const Duration(seconds: 1))
.catchError((dynamic e) => null);
}
/// Internal implementation of the completion mechanism.
Future<CompletionResults> _completeImpl(
Map<String, String> sources, String sourceName, int offset) async {
if (serverScheduler.queueCount > 0) {
_logger
.info('completeImpl: Scheduler queue: ${serverScheduler.queueCount}');
}
return serverScheduler.schedule(ClosureTask<CompletionResults>(() async {
sources = _getOverlayMapWithPaths(sources);
await _loadSources(sources);
final id = await analysisServer.completion.getSuggestions(
_getPathFromName(sourceName),
offset,
);
final results = await getCompletionResults(id.id);
await _unloadSources();
return results;
}, timeoutDuration: _ANALYSIS_SERVER_TIMEOUT));
}
Future<FixesResult> _getFixesImpl(
Map<String, String> sources, String sourceName, int offset) async {
sources = _getOverlayMapWithPaths(sources);
final path = _getPathFromName(sourceName);
if (serverScheduler.queueCount > 0) {
_logger
.fine('getFixesImpl: Scheduler queue: ${serverScheduler.queueCount}');
}
return serverScheduler.schedule(ClosureTask<FixesResult>(() async {
final analysisCompleter = getAnalysisCompleteCompleter();
await _loadSources(sources);
await analysisCompleter.future;
final fixes = await analysisServer.edit.getFixes(path, offset);
await _unloadSources();
return fixes;
}, timeoutDuration: _ANALYSIS_SERVER_TIMEOUT));
}
Future<FormatResult> _formatImpl(String src, int offset) async {
_logger.fine('FormatImpl: Scheduler queue: ${serverScheduler.queueCount}');
return serverScheduler.schedule(ClosureTask<FormatResult>(() async {
await _loadSources(<String, String>{mainPath: src});
final result = await analysisServer.edit.format(mainPath, offset, 0);
await _unloadSources();
return result;
}, timeoutDuration: _ANALYSIS_SERVER_TIMEOUT));
}
Map<String, String> _getOverlayMapWithPaths(Map<String, String> overlay) {
final newOverlay = <String, String>{};
for (final key in overlay.keys) {
newOverlay[_getPathFromName(key)] = overlay[key];
}
return newOverlay;
}
String _getPathFromName(String sourceName) =>
path.join(_sourceDirPath, sourceName);
/// Warm up the analysis server to be ready for use.
Future<proto.CompleteResponse> warmup({bool useHtml = false}) =>
complete(useHtml ? _WARMUP_SRC_HTML : _WARMUP_SRC, 10);
final Set<String> _overlayPaths = <String>{};
Future<void> _loadSources(Map<String, String> sources) async {
if (_overlayPaths.isNotEmpty) {
await _sendRemoveOverlays();
}
await _sendAddOverlays(sources);
await analysisServer.analysis.setPriorityFiles(sources.keys.toList());
}
Future<dynamic> _unloadSources() {
return Future.wait(<Future<dynamic>>[
_sendRemoveOverlays(),
analysisServer.analysis.setPriorityFiles(<String>[]),
]);
}
Future<dynamic> _sendAddOverlays(Map<String, String> overlays) {
final params = <String, ContentOverlayType>{};
for (final overlayPath in overlays.keys) {
params[overlayPath] = AddContentOverlay(overlays[overlayPath]);
}
_logger.fine('About to send analysis.updateContent');
_logger.fine(' ${params.keys}');
_overlayPaths.addAll(params.keys);
return analysisServer.analysis.updateContent(params);
}
Future<dynamic> _sendRemoveOverlays() {
_logger.fine('About to send analysis.updateContent remove overlays:');
_logger.fine(' $_overlayPaths');
final params = <String, ContentOverlayType>{};
for (final overlayPath in _overlayPaths) {
params[overlayPath] = RemoveContentOverlay();
}
_overlayPaths.clear();
return analysisServer.analysis.updateContent(params);
}
final Map<String, Completer<CompletionResults>> _completionCompleters =
<String, Completer<CompletionResults>>{};
void listenForCompletions() {
analysisServer.completion.onResults.listen((CompletionResults result) {
if (result.isLast) {
final completer = _completionCompleters.remove(result.id);
if (completer != null) {
completer.complete(result);
}
}
});
}
Future<CompletionResults> getCompletionResults(String id) {
_completionCompleters[id] = Completer<CompletionResults>();
return _completionCompleters[id].future;
}
final List<Completer<dynamic>> _analysisCompleters = <Completer<dynamic>>[];
void listenForAnalysisComplete() {
analysisServer.server.onStatus.listen((ServerStatus status) {
if (status.analysis == null) return;
if (!status.analysis.isAnalyzing) {
for (final completer in _analysisCompleters) {
completer.complete();
}
_analysisCompleters.clear();
}
});
}
Completer<dynamic> getAnalysisCompleteCompleter() {
final completer = Completer<dynamic>();
_analysisCompleters.add(completer);
return completer;
}
final Map<String, List<AnalysisError>> _errors =
<String, List<AnalysisError>>{};
void listenForErrors() {
analysisServer.analysis.onErrors.listen((AnalysisErrors result) {
if (result.errors.isEmpty) {
_errors.remove(result.file);
} else {
_errors[result.file] = result.errors;
}
});
}
void clearErrors() => _errors.clear();
List<AnalysisError> getErrors() {
final errors = <AnalysisError>[];
for (final e in _errors.values) {
errors.addAll(e);
}
return errors;
}
}
class Location {
final String sourceName;
final int offset;
const Location(this.sourceName, this.offset);
}
| dart-services/lib/src/analysis_server.dart/0 | {'file_path': 'dart-services/lib/src/analysis_server.dart', 'repo_id': 'dart-services', 'token_count': 7623} |
// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
/// Tests which run as part of integration testing; these test high level
/// services.
library services.integration;
import 'gae_deployed_test.dart' as gae_test_test;
void main() {
gae_test_test.defineTests(skip: false);
}
| dart-services/test/integration.dart/0 | {'file_path': 'dart-services/test/integration.dart', 'repo_id': 'dart-services', 'token_count': 130} |
name: in_memory_todos_data_source
description: An in-memory implementation of the TodosDataSource interface.
version: 0.1.0+1
publish_to: none
environment:
sdk: ">=2.17.0 <3.0.0"
dependencies:
todos_data_source:
path: ../todos_data_source
uuid: ^3.0.6
dev_dependencies:
mocktail: ^0.3.0
test: ^1.19.2
very_good_analysis: ^3.0.1
| dart-todos-backend/packages/in_memory_todos_data_source/pubspec.yaml/0 | {'file_path': 'dart-todos-backend/packages/in_memory_todos_data_source/pubspec.yaml', 'repo_id': 'dart-todos-backend', 'token_count': 157} |
analyzer:
exclude: [bricks/**/__brick__/**] | dart_edge/analysis_options.yaml/0 | {'file_path': 'dart_edge/analysis_options.yaml', 'repo_id': 'dart_edge', 'token_count': 18} |
import 'dart:js_util' as js_util;
import 'package:js/js.dart';
import 'package:edge/runtime/interop/promise_interop.dart';
@JS()
@staticInterop
class ExecutionContext {
external factory ExecutionContext();
}
extension PropsExecutionContext on ExecutionContext {
void waitUntil(Future f) =>
js_util.callMethod(this, 'waitUntil', [futureToPromise(f)]);
void passThroughOnException() =>
js_util.callMethod(this, 'passThroughOnException', []);
}
| dart_edge/packages/cloudflare_workers/lib/interop/execution_context_interop.dart/0 | {'file_path': 'dart_edge/packages/cloudflare_workers/lib/interop/execution_context_interop.dart', 'repo_id': 'dart_edge', 'token_count': 157} |
import 'kv_namespace.dart';
import 'do/durable_object_namespace.dart';
import '../interop/environment_interop.dart' as interop;
class Environment {
final interop.Environment _delegate;
Environment._(this._delegate);
KVNamespace getKVNamespace(String name) =>
kvNamespaceFromJsObject(_delegate.getKVNamespace(name));
DurableObjectNamespace getDurableObjectNamespace(String name) =>
durableObjectNamespaceFromJsObject(
_delegate.getDurableObjectNamespace(name));
}
Environment environmentFromJsObject(interop.Environment obj) =>
Environment._(obj);
| dart_edge/packages/cloudflare_workers/lib/public/environment.dart/0 | {'file_path': 'dart_edge/packages/cloudflare_workers/lib/public/environment.dart', 'repo_id': 'dart_edge', 'token_count': 196} |
import 'package:edge/cli/cli.dart' as cli;
void main(List<String> args) {
return cli.main(args);
}
| dart_edge/packages/edge/bin/edge.dart/0 | {'file_path': 'dart_edge/packages/edge/bin/edge.dart', 'repo_id': 'dart_edge', 'token_count': 41} |
import 'dart:io' as io;
import 'package:ansi_styles/ansi_styles.dart';
import 'package:cli_util/cli_logging.dart';
export 'package:ansi_styles/extension.dart';
final successMessageColor = AnsiStyles.green;
final warningMessageColor = AnsiStyles.yellow;
final errorMessageColor = AnsiStyles.red;
final hintMessageColor = AnsiStyles.gray;
Logger? _globalLogger;
/// Initializes the global logger.
void initLogger(Logger logger) {
if (_globalLogger != null) {
return;
}
_globalLogger = logger;
}
/// Returns the global logger.
_Logger get logger {
if (_globalLogger == null) {
throw StateError('Logger not initialized');
}
return _Logger(_globalLogger!);
}
/// A utility class that wraps the [Logger] class, providing some useful
/// methods for logging success, warning, error, and hint messages.
class _Logger {
final Logger _delegate;
_Logger(this._delegate);
int _terminalWidth = io.stdout.hasTerminal ? io.stdout.terminalColumns : 80;
void stdout(String message) {
_delegate.stdout(message);
}
void stderr(String message) {
_delegate.stdout(message);
}
void verbose(String message) {
_delegate.trace(message);
}
void write(String message) {
_delegate.stdout(message);
}
Progress progress(String message) {
return _delegate.progress(message);
}
void hint(String message) {
stdout(hintMessageColor(message));
}
void success(String message) {
stdout(successMessageColor(message));
}
void warning(String message) {
stdout(warningMessageColor(message));
}
void error(String message) {
stderr(errorMessageColor(message));
}
void lineBreak() => stdout('');
void horizontalLine() => stdout('-' * _terminalWidth);
}
extension LoggerStringX on String {
String indent(int width) {
return (' ' * width) + this;
}
String prefix(String char) {
return hintMessageColor(char) + ' ' + this;
}
}
| dart_edge/packages/edge/lib/cli/logger.dart/0 | {'file_path': 'dart_edge/packages/edge/lib/cli/logger.dart', 'repo_id': 'dart_edge', 'token_count': 649} |
import 'package:js/js.dart' as js;
import 'package:js_bindings/js_bindings.dart' as interop;
@js.JS('crypto')
external interop.Crypto get crypto;
| dart_edge/packages/edge/lib/runtime/interop/crypto_interop.dart/0 | {'file_path': 'dart_edge/packages/edge/lib/runtime/interop/crypto_interop.dart', 'repo_id': 'dart_edge', 'token_count': 57} |
import 'package:test/test.dart';
import 'package:edge/runtime.dart';
import 'utils.dart';
void main() {
group('fetch', () {
test('it performs a GET request', () async {
final response = await fetchFromServer('/200');
expect(response.status, 200);
expect(await response.text(), 'GET');
});
test('it performs a POST request', () async {
final response = await fetchFromServer('/200', method: 'POST');
expect(response.status, 200);
expect(await response.text(), 'POST');
});
});
}
| dart_edge/packages/edge/test/fetch_test.dart/0 | {'file_path': 'dart_edge/packages/edge/test/fetch_test.dart', 'repo_id': 'dart_edge', 'token_count': 194} |
import '../interop/context_interop.dart' as interop;
class NetlifyContext {
final interop.NetlifyContext _delegate;
String get ip => _delegate.ip;
String get requestId => _delegate.requestId;
NetlifyContext._(this._delegate);
Account get account => Account._(_delegate.account);
Geo get geo => Geo._(_delegate.geo);
Site get site => Site._(_delegate.site);
}
NetlifyContext netlifyContextFromJsObject(interop.NetlifyContext delegate) =>
NetlifyContext._(delegate);
class Geo {
final interop.Geo _delegate;
Geo._(this._delegate);
String? get city => _delegate.city;
String? get timezone => _delegate.timezone;
num? get latitude => _delegate.latitude;
num? get longitude => _delegate.longitude;
Country? get country =>
_delegate.country == null ? null : Country._(_delegate.country!);
Subdivision? get subdivision => _delegate.subdivision == null
? null
: Subdivision._(_delegate.subdivision!);
}
class Site {
final interop.Site _delegate;
Site._(this._delegate);
String? get id => _delegate.id;
String? get name => _delegate.name;
String? get url => _delegate.url;
}
class Country {
final interop.Country _delegate;
Country._(this._delegate);
String? get code => _delegate.code;
String? get name => _delegate.name;
}
class Subdivision {
final interop.Subdivision _delegate;
Subdivision._(this._delegate);
String? get code => _delegate.code;
String? get name => _delegate.name;
}
class Account {
final interop.Account _delegate;
Account._(this._delegate);
String get id => _delegate.id;
}
| dart_edge/packages/netlify_edge/lib/public/context.dart/0 | {'file_path': 'dart_edge/packages/netlify_edge/lib/public/context.dart', 'repo_id': 'dart_edge', 'token_count': 540} |
name: bump_bundles
on:
schedule:
# weekly on mondays at 8 am utc
- cron: '0 8 * * 1'
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3.3.0
- uses: dart-lang/setup-dart@v1
- name: Install mason
run: dart pub global activate mason_cli
- name: Bump templates
run: tool/generate_bundles.sh
- name: Config Git User
run: |
git config user.name VGV Bot
git config user.email vgvbot@users.noreply.github.com
- name: Create Pull Request
uses: peter-evans/create-pull-request@v5.0.1
with:
base: main
branch: feat/bump-template-bundles
commit-message: "chore: bump cli bundles"
title: "chore: bump cli bundles"
body: Please squash and merge me!
labels: bot
author: VGV Bot <vgvbot@users.noreply.github.com>
assignees: vgvbot
committer: VGV Bot <vgvbot@users.noreply.github.com>
| dart_frog/.github/bump_bundles.yaml/0 | {'file_path': 'dart_frog/.github/bump_bundles.yaml', 'repo_id': 'dart_frog', 'token_count': 489} |
analyzer:
exclude:
- bricks/**/__brick__/** | dart_frog/analysis_options.yaml/0 | {'file_path': 'dart_frog/analysis_options.yaml', 'repo_id': 'dart_frog', 'token_count': 20} |
name: create_dart_frog_hooks
environment:
sdk: ">=3.0.0 <4.0.0"
dependencies:
mason: ^0.1.0-dev.39
path: ^1.8.1
dev_dependencies:
mocktail: ^1.0.0
test: ^1.19.2
very_good_analysis: ^5.0.0
| dart_frog/bricks/create_dart_frog/hooks/pubspec.yaml/0 | {'file_path': 'dart_frog/bricks/create_dart_frog/hooks/pubspec.yaml', 'repo_id': 'dart_frog', 'token_count': 108} |
import 'dart:io' as io;
import 'package:dart_frog_new_hooks/post_gen.dart';
import 'package:dart_frog_new_hooks/src/exit_overrides.dart';
import 'package:mason/mason.dart';
import 'package:mocktail/mocktail.dart';
import 'package:path/path.dart' as path;
import 'package:test/test.dart';
class _MockLogger extends Mock implements Logger {}
class _FakeHookContext extends Fake implements HookContext {
_FakeHookContext({Logger? logger}) : _logger = logger ?? _MockLogger();
final Logger _logger;
var _vars = <String, dynamic>{};
@override
Map<String, dynamic> get vars => _vars;
@override
set vars(Map<String, dynamic> value) => _vars = value;
@override
Logger get logger => _logger;
}
void main() {
group('postGen', () {
late HookContext context;
late Logger logger;
setUp(() {
logger = _MockLogger();
context = _FakeHookContext(logger: logger);
});
test('postGen completes', () {
context.vars['dir_path'] = 'routes/new_route';
context.vars['filename'] = 'index.dart';
expect(
ExitOverrides.runZoned(
() async => postGen(context),
exit: (_) {},
),
completes,
);
});
test('exit(1) if dir_path is not defined', () {
final exitCalls = <int>[];
postGen(context, exit: exitCalls.add);
expect(exitCalls, equals([1]));
});
test('moves file to supposed directory', () {
final directory = io.Directory.systemTemp.createTempSync(
'dart_frog_new_hooks_test',
);
addTearDown(() {
directory.deleteSync(recursive: true);
});
final filePath = path.join(directory.path, 'index.dart');
io.File(filePath)
..createSync(recursive: true)
..writeAsStringSync('content');
context.vars['dir_path'] = 'routes/new_route';
context.vars['filename'] = 'index.dart';
postGen(context, directory: directory);
expect(
io.File(path.join(directory.path, 'routes/new_route/index.dart'))
.readAsStringSync(),
'content',
);
});
});
}
| dart_frog/bricks/dart_frog_new/hooks/test/post_gen_test.dart/0 | {'file_path': 'dart_frog/bricks/dart_frog_new/hooks/test/post_gen_test.dart', 'repo_id': 'dart_frog', 'token_count': 882} |
import 'dart:async';
import 'dart:io' as io;
import 'package:mason/mason.dart' show HookContext, lightCyan;
import 'package:path/path.dart' as path;
import 'src/dart_pub_get.dart';
import 'src/exit_overrides.dart';
void _defaultExit(int code) => ExitOverrides.current?.exit ?? io.exit;
Future<void> run(HookContext context) => postGen(context);
Future<void> postGen(
HookContext context, {
io.Directory? directory,
ProcessRunner runProcess = io.Process.run,
void Function(int exitCode) exit = _defaultExit,
}) async {
final projectDirectory = directory ?? io.Directory.current;
final buildDirectoryPath = path.join(projectDirectory.path, 'build');
await dartPubGet(
context,
workingDirectory: buildDirectoryPath,
runProcess: runProcess,
exit: exit,
);
final relativeBuildPath = path.relative(buildDirectoryPath);
context.logger
..info('')
..success('Created a production build!')
..info('')
..info('Start the production server by running:')
..info('')
..info(
'''${lightCyan.wrap('dart ${path.join(relativeBuildPath, 'bin', 'server.dart')}')}''',
);
}
| dart_frog/bricks/dart_frog_prod_server/hooks/post_gen.dart/0 | {'file_path': 'dart_frog/bricks/dart_frog_prod_server/hooks/post_gen.dart', 'repo_id': 'dart_frog', 'token_count': 396} |
import 'dart:io';
import 'package:path/path.dart' as path;
import 'package:test/test.dart';
import '../../src/get_internal_path_dependencies.dart';
void main() {
group('getPathDependencies', () {
test('returns nothing when there are no path dependencies', () {
final directory = Directory.systemTemp.createTempSync();
File(path.join(directory.path, 'pubspec.lock')).writeAsStringSync(
'''
packages:
test:
dependency: transitive
description:
name: analyzer
sha256: f85566ec7b3d25cbea60f7dd4f157c5025f2f19233ca4feeed33b616c78a26a3
url: "https://pub.dev"
source: hosted
version: "6.1.0"
mason:
dependency: transitive
description:
name: analyzer
sha256: f85566ec7b3d25cbea60f7dd4f157c5025f2f19233ca4feeed33b616c78a26a3
url: "https://pub.dev"
source: hosted
version: "6.1.0"
''',
);
expect(getInternalPathDependencies(directory), completion(isEmpty));
directory.delete(recursive: true).ignore();
});
test('returns correct path dependencies', () {
final directory = Directory.systemTemp.createTempSync();
File(path.join(directory.path, 'pubspec.lock')).writeAsStringSync(
'''
packages:
dart_frog:
dependency: "direct main"
description:
path: "path/to/dart_frog"
relative: true
source: path
version: "0.0.0"
dart_frog_gen:
dependency: "direct main"
description:
path: "path/to/dart_frog_gen"
relative: true
source: path
version: "0.0.0"
''',
);
expect(
getInternalPathDependencies(directory),
completion(
equals(['path/to/dart_frog', 'path/to/dart_frog_gen']),
),
);
directory.delete(recursive: true).ignore();
});
});
}
| dart_frog/bricks/dart_frog_prod_server/hooks/test/src/get_internal_path_dependencies_test.dart/0 | {'file_path': 'dart_frog/bricks/dart_frog_prod_server/hooks/test/src/get_internal_path_dependencies_test.dart', 'repo_id': 'dart_frog', 'token_count': 770} |
import 'dart:io';
import 'package:bearer_authentication/session_repository.dart';
import 'package:bearer_authentication/user_repository.dart';
import 'package:dart_frog/dart_frog.dart';
Future<Response> onRequest(RequestContext context) async {
return switch (context.request.method) {
HttpMethod.post => _authenticationUser(context),
_ => Future.value(Response(statusCode: HttpStatus.methodNotAllowed)),
};
}
Future<Response> _authenticationUser(RequestContext context) async {
final body = await context.request.json() as Map<String, dynamic>;
final username = body['username'] as String?;
final password = body['password'] as String?;
final userRepository = context.read<UserRepository>();
final sessionRepository = context.read<SessionRepository>();
if (username != null && password != null) {
final user = await userRepository.userFromCredentials(
username,
password,
);
if (user == null) {
return Response(statusCode: HttpStatus.unauthorized);
} else {
final session = await sessionRepository.createSession(user.id);
return Response.json(
body: {
'token': session.token,
},
);
}
} else {
return Response(statusCode: HttpStatus.badRequest);
}
}
| dart_frog/examples/bearer_authentication/routes/auth/index.dart/0 | {'file_path': 'dart_frog/examples/bearer_authentication/routes/auth/index.dart', 'repo_id': 'dart_frog', 'token_count': 433} |
dependency_overrides:
dart_frog:
path: ../../packages/dart_frog
| dart_frog/examples/kitchen_sink/pubspec_overrides.yaml/0 | {'file_path': 'dart_frog/examples/kitchen_sink/pubspec_overrides.yaml', 'repo_id': 'dart_frog', 'token_count': 29} |
import 'dart:io';
import 'package:dart_frog/dart_frog.dart';
import 'package:mocktail/mocktail.dart';
import 'package:test/test.dart';
import '../../routes/index.dart' as route;
class _MockRequestContext extends Mock implements RequestContext {}
void main() {
group('GET /', () {
test('responds with a 200 and greeting', () {
const greeting = 'Hello World';
final context = _MockRequestContext();
when(() => context.read<String>()).thenReturn(greeting);
final response = route.onRequest(context);
expect(response.statusCode, equals(HttpStatus.ok));
expect(response.body(), completion(equals(greeting)));
});
});
}
| dart_frog/examples/kitchen_sink/test/routes/index_test.dart/0 | {'file_path': 'dart_frog/examples/kitchen_sink/test/routes/index_test.dart', 'repo_id': 'dart_frog', 'token_count': 239} |
import 'package:todos_data_source/todos_data_source.dart';
import 'package:uuid/uuid.dart';
/// An in-memory implementation of the [TodosDataSource] interface.
class InMemoryTodosDataSource implements TodosDataSource {
/// Map of ID -> `Todo`
final _cache = <String, Todo>{};
@override
Future<Todo> create(Todo todo) async {
final id = const Uuid().v4();
final createdTodo = todo.copyWith(id: id);
_cache[id] = createdTodo;
return createdTodo;
}
@override
Future<List<Todo>> readAll() async => _cache.values.toList();
@override
Future<Todo?> read(String id) async => _cache[id];
@override
Future<Todo> update(String id, Todo todo) async {
return _cache.update(id, (value) => todo);
}
@override
Future<void> delete(String id) async => _cache.remove(id);
}
| dart_frog/examples/todos/packages/in_memory_todos_data_source/lib/src/in_memory_todos_data_source.dart/0 | {'file_path': 'dart_frog/examples/todos/packages/in_memory_todos_data_source/lib/src/in_memory_todos_data_source.dart', 'repo_id': 'dart_frog', 'token_count': 303} |
dependency_overrides:
dart_frog:
path: ../../packages/dart_frog
| dart_frog/examples/todos/pubspec_overrides.yaml/0 | {'file_path': 'dart_frog/examples/todos/pubspec_overrides.yaml', 'repo_id': 'dart_frog', 'token_count': 29} |
import 'package:dart_frog/dart_frog.dart';
import 'package:web_socket_counter/counter/counter.dart';
Handler middleware(Handler handler) => handler.use(counterProvider);
| dart_frog/examples/web_socket_counter/routes/_middleware.dart/0 | {'file_path': 'dart_frog/examples/web_socket_counter/routes/_middleware.dart', 'repo_id': 'dart_frog', 'token_count': 53} |
import 'dart:async';
import 'package:dart_frog/dart_frog.dart';
/// A function which handles a request via the provided [context].
typedef Handler = FutureOr<Response> Function(RequestContext context);
| dart_frog/packages/dart_frog/lib/src/handler.dart/0 | {'file_path': 'dart_frog/packages/dart_frog/lib/src/handler.dart', 'repo_id': 'dart_frog', 'token_count': 60} |
import 'dart:async';
import 'dart:io';
import 'package:dart_frog/dart_frog.dart';
import 'package:test/test.dart';
void main() {
group('hotReload', () {
test('completes', () async {
final completer = Completer<void>();
var invoked = false;
HttpServer? server;
Future<HttpServer> initializer() async {
invoked = true;
server = await serve((_) => Response(), 'localhost', 8080);
completer.complete();
return server!;
}
expect(() => hotReload(initializer), returnsNormally);
await completer.future;
expect(invoked, isTrue);
expect(server, isNotNull);
await server!.close(force: true);
});
});
}
| dart_frog/packages/dart_frog/test/src/hot_reload_test.dart/0 | {'file_path': 'dart_frog/packages/dart_frog/test/src/hot_reload_test.dart', 'repo_id': 'dart_frog', 'token_count': 286} |
import 'dart:io';
import 'dart:isolate';
import 'package:http/http.dart' as http;
import 'package:path/path.dart' as path;
import 'package:test/test.dart';
import 'helpers/helpers.dart';
/// Objectives:
///
/// * Generate a new Dart Frog project via `dart_frog create`
/// * Generate a production build via `dart_frog build`
/// * Ensure the server responds accordingly for built-in endpoints
void main() {
group('dart_frog build', () {
const projectName = 'example';
final tempDirectory = Directory.systemTemp.createTempSync();
final projectDirectory = Directory(
path.join(tempDirectory.path, projectName),
);
late Isolate isolate;
setUpAll(() async {
await dartFrogCreate(projectName: projectName, directory: tempDirectory);
await dartFrogBuild(directory: projectDirectory);
isolate = await Isolate.spawnUri(
Uri.file(
path.join(projectDirectory.path, 'build', 'bin', 'server.dart'),
),
[],
null,
);
});
tearDownAll(() async {
isolate.kill();
await tempDirectory.delete(recursive: true);
});
test('creates the project directory', () {
final entities = tempDirectory.listSync();
expect(entities.length, equals(1));
expect(path.basename(entities.first.path), equals(projectName));
});
testServer('GET / returns 200 with greeting', (host) async {
final response = await http.get(Uri.parse(host));
expect(response.statusCode, equals(HttpStatus.ok));
expect(response.body, equals('Welcome to Dart Frog!'));
expect(response.headers, contains('date'));
expect(
response.headers,
containsPair('content-type', 'text/plain; charset=utf-8'),
);
});
testServer('GET /not_here returns 404', (host) async {
final response = await http.get(Uri.parse('$host/not_here'));
expect(response.statusCode, HttpStatus.notFound);
expect(response.body, 'Route not found');
});
});
}
| dart_frog/packages/dart_frog_cli/e2e/test/build_test.dart/0 | {'file_path': 'dart_frog/packages/dart_frog_cli/e2e/test/build_test.dart', 'repo_id': 'dart_frog', 'token_count': 738} |
import 'dart:io';
Future<ProcessResult> runProcess(
String executable,
List<String> arguments, {
String? workingDirectory,
Map<String, String>? environment,
bool includeParentEnvironment = true,
bool runInShell = false,
}) async {
final result = await Process.run(
executable,
arguments,
workingDirectory: workingDirectory,
environment: environment,
includeParentEnvironment: includeParentEnvironment,
runInShell: runInShell,
);
if (result.exitCode != 0) {
final commandLine = [executable, ...arguments].join(' ');
throw RunProcessException(
'"$commandLine" exited with code ${result.exitCode}',
processResult: result,
);
}
return result;
}
class RunProcessException implements Exception {
RunProcessException(
this.message, {
required this.processResult,
});
final String message;
final ProcessResult processResult;
@override
String toString() {
return '''
$message
- pid: ${processResult.pid}
- stderr: ${processResult.stderr}
- stdout: ${processResult.stdout}
''';
}
}
| dart_frog/packages/dart_frog_cli/e2e/test/helpers/run_process.dart/0 | {'file_path': 'dart_frog/packages/dart_frog_cli/e2e/test/helpers/run_process.dart', 'repo_id': 'dart_frog', 'token_count': 345} |
import 'dart:io';
import 'package:args/args.dart';
import 'package:args/command_runner.dart';
import 'package:dart_frog_cli/src/command.dart';
import 'package:dart_frog_cli/src/commands/commands.dart';
import 'package:dart_frog_cli/src/commands/new/templates/dart_frog_new_bundle.dart';
import 'package:mason/mason.dart';
import 'package:meta/meta.dart';
import 'package:path/path.dart' as path;
/// {@template new_command}
/// `dart_frog new <route|middleware> "path/to/route"`
///
/// Creates a new route or middleware for dart_frog.
/// {@endtemplate}
class NewCommand extends DartFrogCommand {
/// {@macro new_command}
NewCommand({
super.logger,
GeneratorBuilder? generator,
}) : _generator = generator ?? MasonGenerator.fromBundle {
addSubcommand(newRouteCommand = _NewSubCommand('route'));
addSubcommand(newMiddlewareCommand = _NewSubCommand('middleware'));
}
final GeneratorBuilder _generator;
@override
String get description => 'Create a new route or middleware for dart_frog';
@override
String get name => 'new';
@override
final String invocation = 'dart_frog new <route|middleware> "path/to/route"';
/// Subcommand for creating a new route.
@visibleForTesting
late final DartFrogCommand newRouteCommand;
/// Subcommand for creating a new middleware.
@visibleForTesting
late final DartFrogCommand newMiddlewareCommand;
}
class _NewSubCommand extends DartFrogCommand {
_NewSubCommand(this.name);
@override
String get description => 'Create a new $name for dart_frog';
@override
final String name;
@override
NewCommand get parent => super.parent! as NewCommand;
@override
late final String invocation = 'dart_frog new $name "path/to/route"';
@visibleForTesting
@override
// ignore: invalid_use_of_visible_for_testing_member
ArgResults? get testArgResults => parent.testArgResults;
@override
// ignore: invalid_use_of_visible_for_testing_member
String? get testUsage => parent.testUsage;
String get _routePath {
final rest = results.rest;
if (rest.isEmpty) {
throw UsageException(
'Provide a route path for the new $name',
usageString,
);
}
final routeName = rest.first;
if (routeName.isEmpty) {
throw UsageException(
'Route path must not be empty',
usageString,
);
}
final segments =
routeName.split('/').skipWhile((element) => element.isEmpty);
for (final segment in segments) {
if (segment.isEmpty) {
throw UsageException(
'Route path cannot contain empty segments',
'',
);
}
if (segment.contains(r'$')) {
throw UsageException(
'Route path cannot contain dollar signs',
'',
);
}
if (segment.contains(RegExp(r'[^a-zA-Z\d_\[\]]'))) {
throw UsageException(
'Route path segments must be valid Dart identifiers',
'',
);
}
}
return routeName;
}
@override
Future<int> run() async {
final routePath = _routePath;
final generator = await parent._generator(dartFrogNewBundle);
final vars = <String, dynamic>{
'route_path': routePath,
'type': name,
};
final routesDirectory = Directory(path.join(cwd.path, 'routes'));
if (!routesDirectory.existsSync()) {
throw UsageException(
'No "routes" directory found in the current directory. '
'Make sure to run this command on a dart_frog project.',
usageString,
);
}
await generator.hooks.preGen(
vars: vars,
workingDirectory: cwd.path,
onVarsChanged: vars.addAll,
logger: logger,
);
if (!vars.containsKey('dir_path')) {
return ExitCode.software.code;
}
final generateProgress = logger.progress('Creating $name $routePath');
await generator.generate(DirectoryGeneratorTarget(cwd), vars: vars);
await generator.hooks.postGen(
vars: vars,
workingDirectory: cwd.path,
logger: logger,
);
generateProgress.complete();
return ExitCode.success.code;
}
}
| dart_frog/packages/dart_frog_cli/lib/src/commands/new/new.dart/0 | {'file_path': 'dart_frog/packages/dart_frog_cli/lib/src/commands/new/new.dart', 'repo_id': 'dart_frog', 'token_count': 1553} |
import 'dart:io';
import 'package:dart_frog_gen/src/path_to_route.dart';
import 'package:path/path.dart' as path;
/// Build a [RouteConfiguration] based on the provided root project [directory].
RouteConfiguration buildRouteConfiguration(Directory directory) {
final routesDirectory = Directory(path.join(directory.path, 'routes'));
if (!routesDirectory.existsSync()) {
throw Exception('Could not find directory ${routesDirectory.path}');
}
final globalMiddlewareFile = File(
path.join(routesDirectory.path, '_middleware.dart'),
);
final globalMiddleware = globalMiddlewareFile.existsSync()
? MiddlewareFile(
name: 'middleware',
path: path
.join('..', path.relative(globalMiddlewareFile.path))
.replaceAll(r'\', '/'),
)
: null;
final endpoints = <String, List<RouteFile>>{};
final middleware = <MiddlewareFile>[
if (globalMiddleware != null) globalMiddleware,
];
final routes = <RouteFile>[];
final rogueRoutes = <RouteFile>[];
final directories = _getRouteDirectories(
directory: routesDirectory,
routesDirectory: routesDirectory,
onRoute: routes.add,
onMiddleware: middleware.add,
onEndpoint: (endpoint, file) {
if (!endpoints.containsKey(endpoint)) {
endpoints[endpoint] = [file];
} else {
endpoints[endpoint]!.add(file);
}
},
onRogueRoute: rogueRoutes.add,
);
final publicDirectory = Directory(path.join(directory.path, 'public'));
final mainDartFile = File(path.join(directory.path, 'main.dart'));
final customInitRegex = RegExp(
r'^Future(?:Or)?<void>\s*init\(InternetAddress .*?,\s*int .*?\)\s*(?:async)?\s*{',
multiLine: true,
);
final mainDartFileExists = mainDartFile.existsSync();
final hasCustomInit = mainDartFileExists &&
customInitRegex.hasMatch(mainDartFile.readAsStringSync());
return RouteConfiguration(
globalMiddleware: globalMiddleware,
middleware: middleware,
directories: directories,
routes: routes,
rogueRoutes: rogueRoutes,
endpoints: endpoints,
serveStaticFiles: publicDirectory.existsSync(),
invokeCustomEntrypoint: mainDartFileExists,
invokeCustomInit: hasCustomInit,
);
}
List<RouteDirectory> _getRouteDirectories({
required Directory directory,
required Directory routesDirectory,
required void Function(RouteFile route) onRoute,
required void Function(MiddlewareFile route) onMiddleware,
required void Function(String endpoint, RouteFile file) onEndpoint,
required void Function(RouteFile route) onRogueRoute,
List<MiddlewareFile> middleware = const [],
}) {
final directories = <RouteDirectory>[];
final entities = directory.listSync().sorted();
final directorySegment =
directory.path.split('routes').last.replaceAll(r'\', '/');
final directoryPath = directorySegment.startsWith('/')
? directorySegment
: '/$directorySegment';
// Only add nested middleware -- global middleware is added separately.
MiddlewareFile? localMiddleware;
if (directory.path != path.join(Directory.current.path, 'routes')) {
final middlewareFile = File(path.join(directory.path, '_middleware.dart'));
if (middlewareFile.existsSync()) {
final middlewarePath = path
.relative(middlewareFile.path, from: routesDirectory.path)
.replaceAll(r'\', '/');
localMiddleware = MiddlewareFile(
name: middlewarePath.toAlias(),
path: path.join('..', 'routes', middlewarePath).replaceAll(r'\', '/'),
);
onMiddleware(localMiddleware);
}
}
final updatedMiddleware = [
...middleware,
if (localMiddleware != null) localMiddleware,
];
final files = _getRouteFiles(
directory: directory,
routesDirectory: routesDirectory,
onRoute: onRoute,
onRogueRoute: onRogueRoute,
);
if (files.isNotEmpty) {
final baseRoute = directoryPath.toRoute();
for (final file in files) {
var endpoint = (baseRoute + file.route.toRoute()).replaceAll('//', '/');
if (endpoint.endsWith('/')) {
endpoint = endpoint.substring(0, endpoint.length - 1);
}
if (endpoint.isEmpty) endpoint = '/';
onEndpoint(endpoint, file);
}
if (directoryPath.isWildcard()) {
throw ArgumentError('Only files can be named with a wildcard alias.');
}
directories.add(
RouteDirectory(
name: directoryPath.toAlias(),
route: baseRoute,
middleware: updatedMiddleware,
files: files,
params: directoryPath.toParams(),
),
);
}
entities.whereType<Directory>().forEach((directory) {
directories.addAll(
_getRouteDirectories(
directory: directory,
routesDirectory: routesDirectory,
onRoute: onRoute,
onMiddleware: onMiddleware,
onEndpoint: onEndpoint,
onRogueRoute: onRogueRoute,
middleware: updatedMiddleware,
),
);
});
return directories;
}
List<RouteFile> _getRouteFiles({
required Directory directory,
required Directory routesDirectory,
required void Function(RouteFile route) onRoute,
required void Function(RouteFile route) onRogueRoute,
String prefix = '',
}) {
final files = <RouteFile>[];
final directorySegment =
directory.path.split('routes').last.replaceAll(r'\', '/');
final directoryPath = directorySegment.startsWith('/')
? directorySegment
: '/$directorySegment';
final entities = directory.listSync().sorted();
final subDirectories = entities
.whereType<Directory>()
.map((directory) => path.basename(directory.path))
.toSet();
entities.where((e) => e.isRoute).cast<File>().forEach((entity) {
final filePath = path
.relative(entity.path, from: routesDirectory.path)
.replaceAll(r'\', '/');
String getFileRoute() {
final routePath = pathToRoute(path.join('..', 'routes', filePath));
final index = routePath.indexOf(directoryPath);
final fileRoutePath = index == -1
? routePath
: routePath.substring(index + directoryPath.length);
var fileRoute = fileRoutePath.isEmpty ? '/' : fileRoutePath;
fileRoute = prefix + fileRoute;
if (!fileRoute.startsWith('/')) fileRoute = '/$fileRoute';
return fileRoute;
}
final fileRoute = getFileRoute();
final relativeFilePath = path.join('..', 'routes', filePath);
final isWildcard = filePath.isWildcard();
final route = RouteFile(
name: filePath.toAlias(),
path: relativeFilePath.replaceAll(r'\', '/'),
route: fileRoute.toRoute(),
params: fileRoute.toParams(),
wildcard: isWildcard,
);
onRoute(route);
files.add(route);
final fileBasename = path.basenameWithoutExtension(filePath);
final conflictingIndexFile = File(
path.join(directory.path, fileBasename, 'index.dart'),
);
final isRogueRoute = subDirectories.contains(fileBasename) &&
!conflictingIndexFile.existsSync();
if (isRogueRoute) onRogueRoute(route);
});
return files;
}
/// Extension on [String] with helper methods regarding
/// Dart Frog routes.
extension RouteStringX on String {
/// Parses the stirng into a route alias.
String toAlias() {
final alias = path
.withoutExtension(this)
.replaceAll('[', r'$')
.replaceAll(']', '')
.replaceAll('/', '_')
.replaceAll('...', 'wildcard_');
if (alias == '') return 'index';
return alias;
}
/// Returns if this value matches a wildcard route.
bool isWildcard() {
final value = endsWith('.dart')
? path.basenameWithoutExtension(this)
: path.basename(this);
return RegExp(r'\[\.\.\.(.*?)\]').hasMatch(value);
}
/// Parses the string into a route path.
String toRoute() {
if (isWildcard()) return '/';
return replaceAll('[', '<').replaceAll(']', '>').replaceAll(r'\', '/');
}
/// Parses the string into a list of route parameters.
List<String> toParams() {
final regexp = RegExp(r'\[(.*?)\]');
final matches = regexp.allMatches(this);
return matches.map((m) {
final match = m[0]!;
return match.replaceAll(RegExp(r'\[|\]'), '').replaceFirst('...', '');
}).toList();
}
}
extension on List<FileSystemEntity> {
List<FileSystemEntity> sorted() {
return this..sort((a, b) => b.path.compareTo(a.path));
}
}
extension on FileSystemEntity {
bool get isRoute {
return this is File &&
path.basename(this.path).endsWith('.dart') &&
path.basename(this.path) != '_middleware.dart';
}
}
/// {@template route_configuration}
/// An object containing all route configuration metadata
/// required to generate a dart frog server.
/// {@endtemplate}
class RouteConfiguration {
/// {@macro route_configuration}
const RouteConfiguration({
required this.middleware,
required this.directories,
required this.routes,
required this.endpoints,
required this.rogueRoutes,
this.globalMiddleware,
this.serveStaticFiles = false,
this.invokeCustomEntrypoint = false,
this.invokeCustomInit = false,
});
/// Whether to invoke a custom entrypoint script (`main.dart`).
final bool invokeCustomEntrypoint;
/// Whether to invoke a custom init method (`init` in `main.dart`).
final bool invokeCustomInit;
/// Whether to serve static files. Defaults to false.
final bool serveStaticFiles;
/// Optional global middleware.
final MiddlewareFile? globalMiddleware;
/// List of all nested middleware.
/// Top-level middleware is excluded (see [globalMiddleware]).
final List<MiddlewareFile> middleware;
/// List of all route directories.
/// Sorted from leaf nodes to root.
final List<RouteDirectory> directories;
/// List of all route files.
final List<RouteFile> routes;
/// A map of all endpoint paths to resolved route files.
final Map<String, List<RouteFile>> endpoints;
/// List of all rogue routes.
///
/// A route is considered rogue when it is defined outside
/// of an existing subdirectory with the same name.
///
/// For example:
///
/// ```
/// ├── routes
/// │ ├── foo
/// │ │ └── example.dart
/// │ ├── foo.dart
/// ```
///
/// In the above scenario, `foo.dart` is rogue because it is defined
/// outside of the existing `foo` directory.
///
/// Instead, `foo.dart` should be renamed to `index.dart` and placed within
/// the `foo` directory like:
///
/// ```
/// ├── routes
/// │ ├── foo
/// │ │ ├── example.dart
/// │ │ └── index.dart
/// ```
final List<RouteFile> rogueRoutes;
/// Transform into json
Map<String, dynamic> toJson() {
return {
'invokeCustomEntrypoint': invokeCustomEntrypoint,
'invokeCustomInit': invokeCustomInit,
'serveStaticFiles': serveStaticFiles,
'globalMiddleware': globalMiddleware?.toJson(),
'middleware': middleware.map((e) => e.toJson()).toList(),
'directories': directories.map((e) => e.toJson()).toList(),
'routes': routes.map((e) => e.toJson()).toList(),
'endpoints': endpoints.map(
(key, value) => MapEntry(
key,
value.map((e) => e.toJson()).toList(),
),
),
'rogueRoutes': rogueRoutes.map((e) => e.toJson()).toList(),
};
}
}
/// {@template route_directory}
/// A class containing metadata regarding a route directory.
/// {@endtemplate}
class RouteDirectory {
/// {@macro route_directory}
const RouteDirectory({
required this.name,
required this.route,
required this.middleware,
required this.files,
required this.params,
});
/// The alias for the current directory.
final String name;
/// The route which will be used to mount routers.
final String route;
/// The dynamic route params associated with the directory.
final List<String> params;
/// List of middleware for the provided router.
final List<MiddlewareFile> middleware;
/// A list of nested route files within the directory.
final List<RouteFile> files;
/// Create a copy of the current instance and override zero or more values.
RouteDirectory copyWith({
String? name,
String? route,
List<MiddlewareFile>? middleware,
List<RouteFile>? files,
List<String>? params,
}) {
return RouteDirectory(
name: name ?? this.name,
route: route ?? this.route,
middleware: middleware ?? this.middleware,
files: files ?? this.files,
params: params ?? this.params,
);
}
/// Convert the current instance to a `Map<String, dynamic>`.
Map<String, dynamic> toJson() {
return <String, dynamic>{
'name': name,
'route': route,
'middleware': middleware.map((m) => m.toJson()).toList(),
'files': files.map((f) => f.toJson()).toList(),
'directory_params': params,
};
}
}
/// {@template route_file}
/// A class containing metadata regarding a route file.
/// {@endtemplate}
class RouteFile {
/// {@macro route_file}
const RouteFile({
required this.name,
required this.path,
required this.route,
required this.params,
required this.wildcard,
});
/// The alias for the current file.
final String name;
/// The import path for the current instance.
final String path;
/// The route used by router instances.
final String route;
/// The dynamic route params associated with the file.
final List<String> params;
/// Whether the route is a wildcard route.
final bool wildcard;
/// Create a copy of the current instance and override zero or more values.
RouteFile copyWith({
String? name,
String? path,
String? route,
List<String>? params,
bool? wildcard,
}) {
return RouteFile(
name: name ?? this.name,
path: path ?? this.path,
route: route ?? this.route,
params: params ?? this.params,
wildcard: wildcard ?? this.wildcard,
);
}
/// Convert the current instance to a `Map<String, dynamic>`.
Map<String, dynamic> toJson() {
return <String, dynamic>{
'name': name,
'path': path,
'route': route,
'file_params': params,
'wildcard': wildcard,
};
}
}
/// {@template middleware_file}
/// A class containing metadata regarding a route directory.
/// {@endtemplate}
class MiddlewareFile {
/// {@macro middleware_file}
const MiddlewareFile({
required this.name,
required this.path,
});
/// The alias for the current directory.
final String name;
/// The import path for the current instance.
final String path;
/// Create a copy of the current instance and override zero or more values.
MiddlewareFile copyWith({String? name, String? path}) {
return MiddlewareFile(
name: name ?? this.name,
path: path ?? this.path,
);
}
/// Convert the current instance to a `Map<String, dynamic>`.
Map<String, dynamic> toJson() {
return <String, dynamic>{
'name': name,
'path': path,
};
}
}
| dart_frog/packages/dart_frog_gen/lib/src/build_route_configuration.dart/0 | {'file_path': 'dart_frog/packages/dart_frog_gen/lib/src/build_route_configuration.dart', 'repo_id': 'dart_frog', 'token_count': 5327} |
import 'package:sealed_unions/generic/union_7_fifth.dart';
import 'package:sealed_unions/generic/union_7_first.dart';
import 'package:sealed_unions/generic/union_7_fourth.dart';
import 'package:sealed_unions/generic/union_7_second.dart';
import 'package:sealed_unions/generic/union_7_seventh.dart';
import 'package:sealed_unions/generic/union_7_sixth.dart';
import 'package:sealed_unions/generic/union_7_third.dart';
import 'package:sealed_unions/union_7.dart';
// Creator class for Union7
abstract class Factory7<A, B, C, D, E, F, G> {
Union7<A, B, C, D, E, F, G> first(A first);
Union7<A, B, C, D, E, F, G> second(B second);
Union7<A, B, C, D, E, F, G> third(C third);
Union7<A, B, C, D, E, F, G> fourth(D fourth);
Union7<A, B, C, D, E, F, G> fifth(E fifth);
Union7<A, B, C, D, E, F, G> sixth(F sixth);
Union7<A, B, C, D, E, F, G> seventh(G seventh);
}
class Septet<A, B, C, D, E, F, G> implements Factory7<A, B, C, D, E, F, G> {
const Septet();
@override
Union7<A, B, C, D, E, F, G> first(A first) =>
new Union7First<A, B, C, D, E, F, G>(first);
@override
Union7<A, B, C, D, E, F, G> second(B second) =>
new Union7Second<A, B, C, D, E, F, G>(second);
@override
Union7<A, B, C, D, E, F, G> third(C third) =>
new Union7Third<A, B, C, D, E, F, G>(third);
@override
Union7<A, B, C, D, E, F, G> fourth(D fourth) =>
new Union7Fourth<A, B, C, D, E, F, G>(fourth);
@override
Union7<A, B, C, D, E, F, G> fifth(E fifth) =>
new Union7Fifth<A, B, C, D, E, F, G>(fifth);
@override
Union7<A, B, C, D, E, F, G> sixth(F sixth) =>
new Union7Sixth<A, B, C, D, E, F, G>(sixth);
@override
Union7<A, B, C, D, E, F, G> seventh(G seventh) =>
new Union7Seventh<A, B, C, D, E, F, G>(seventh);
}
| dart_sealed_unions/lib/factories/septet_factory.dart/0 | {'file_path': 'dart_sealed_unions/lib/factories/septet_factory.dart', 'repo_id': 'dart_sealed_unions', 'token_count': 825} |
import 'package:sealed_unions/union_5.dart';
class Union5Fifth<A, B, C, D, E> implements Union5<A, B, C, D, E> {
final E _value;
Union5Fifth(this._value);
@override
void continued(
Function(A) continuationFirst,
Function(B) continuationSecond,
Function(C) continuationThird,
Function(D) continuationFourth,
Function(E) continuationFifth,
) {
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,
) {
return mapFifth(_value);
}
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is Union5Fifth &&
runtimeType == other.runtimeType &&
_value == other._value;
@override
int get hashCode => _value.hashCode;
@override
String toString() => _value.toString();
}
| dart_sealed_unions/lib/generic/union_5_fifth.dart/0 | {'file_path': 'dart_sealed_unions/lib/generic/union_5_fifth.dart', 'repo_id': 'dart_sealed_unions', 'token_count': 357} |
abstract class Union2<First, Second> {
void continued(
Function(First) continuationFirst,
Function(Second) continuationSecond,
);
R join<R>(R Function(First) mapFirst, R Function(Second) mapSecond);
}
| dart_sealed_unions/lib/union_2.dart/0 | {'file_path': 'dart_sealed_unions/lib/union_2.dart', 'repo_id': 'dart_sealed_unions', 'token_count': 67} |
include: package:flame_lint/analysis_options.yaml
| dartdoc_json/analysis_options.yaml/0 | {'file_path': 'dartdoc_json/analysis_options.yaml', 'repo_id': 'dartdoc_json', 'token_count': 16} |
import 'package:analyzer/dart/ast/ast.dart';
import 'package:dartdoc_json/src/utils.dart';
/// Converts a FormalParameter into a json-compatible object.
Map<String, dynamic> serializeFormalParameter(FormalParameter parameter) {
var p = parameter;
String? defaultValue;
if (p is DefaultFormalParameter) {
defaultValue = p.defaultValue?.toString();
p = p.parameter;
}
String? type;
var name = p.name?.lexeme;
if (p is FieldFormalParameter) {
name = 'this.$name';
} else if (p is SuperFormalParameter) {
name = 'super.$name';
} else if (p is SimpleFormalParameter) {
type = p.type?.toString();
}
return filterMap(<String, dynamic>{
'name': name,
'type': type,
'covariant': p.covariantKeyword == null ? null : true,
'default': defaultValue,
'required': p.isRequiredNamed ? true : null,
});
}
| dartdoc_json/lib/src/formal_parameter.dart/0 | {'file_path': 'dartdoc_json/lib/src/formal_parameter.dart', 'repo_id': 'dartdoc_json', 'token_count': 313} |
import 'package:analyzer/dart/ast/ast.dart';
/// Converts a WithClause into a json-compatible object.
List<String>? serializeWithClause(WithClause? clause) {
if (clause == null) {
return null;
}
return [for (final type in clause.mixinTypes) type.toString()];
}
| dartdoc_json/lib/src/with_clause.dart/0 | {'file_path': 'dartdoc_json/lib/src/with_clause.dart', 'repo_id': 'dartdoc_json', 'token_count': 96} |
import 'package:analyzer/dart/analysis/features.dart';
import 'package:analyzer/dart/analysis/utilities.dart';
import 'package:dartdoc_json/src/compilation_unit.dart';
dynamic parseAsJson(String content) {
final parsed = parseString(
content: content,
featureSet: FeatureSet.latestLanguageVersion(),
);
final unit = serializeCompilationUnit(parsed.unit);
final declarations = unit['declarations'] as List?;
final directives = unit['directives'] as List?;
if (declarations == null && directives == null) {
return unit;
} else if (declarations == null) {
return directives!.length == 1 ? directives.first : directives;
} else if (directives == null) {
return declarations.length == 1 ? declarations.first : declarations;
} else {
return unit;
}
}
| dartdoc_json/test/utils.dart/0 | {'file_path': 'dartdoc_json/test/utils.dart', 'repo_id': 'dartdoc_json', 'token_count': 245} |
part of dartx;
extension NumX<T extends num> on T {
/// Ensures that this value lies in the specified range
/// [minimumValue]..[maximumValue].
///
/// Return this value if it's in the range, or [minimumValue] if this value
/// is less than [minimumValue], or [maximumValue] if this value is greater
/// than [maximumValue].
///
/// ```dart
/// print(10.coerceIn(1, 100)) // 10
/// print(0.coerceIn(1, 100)) // 1
/// print(500.coerceIn(1, 100)) // 100
/// 10.coerceIn(100, 0) // will fail with ArgumentError
/// ````
T coerceIn(T minimumValue, [T maximumValue]) {
if (maximumValue != null && minimumValue > maximumValue) {
throw ArgumentError('Cannot coerce value to an empty range: '
'maximum $maximumValue is less than minimum $minimumValue.');
}
if (this < minimumValue) return minimumValue;
if (maximumValue != null && this > maximumValue) return maximumValue;
return this;
}
/// Ensures that this value is not less than the specified [minimumValue].
///
/// Return this value if it's greater than or equal to the [minimumValue]
/// or the [minimumValue] otherwise.
///
/// ```dart
/// print(10.coerceAtLeast(5)) // 10
/// print(10.coerceAtLeast(20)) // 20
/// ```
T coerceAtLeast(T minimumValue) =>
this < minimumValue ? minimumValue : this;
/// Ensures that this value is not greater than the specified [maximumValue].
///
/// Return this value if it's less than or equal to the [maximumValue] or the
/// [maximumValue] otherwise.
///
/// ```dart
/// print(10.coerceAtMost(5)) // 5
/// print(10.coerceAtMost(20)) // 10
/// ```
T coerceAtMost(T maximumValue) =>
this > maximumValue ? maximumValue : this;
}
extension IntX<T extends int> on T {
/// Converts this value to binary form.
Uint8List toBytes([Endian endian = Endian.big]) {
final data = ByteData(8);
data.setInt64(0, this, endian);
return data.buffer.asUint8List();
}
}
extension DoubleX<T extends double> on T {
/// Converts this value to binary form.
Uint8List toBytes([Endian endian = Endian.big]) {
final data = ByteData(8);
data.setFloat64(0, this, endian);
return data.buffer.asUint8List();
}
}
| dartx/lib/src/num.dart/0 | {'file_path': 'dartx/lib/src/num.dart', 'repo_id': 'dartx', 'token_count': 767} |
import 'package:dashbook/src/device_size_extension.dart';
import 'package:dashbook/src/widgets/device_preview.dart';
import 'package:dashbook/src/widgets/helpers.dart';
import 'package:dashbook/src/widgets/select_device/device_settings.dart';
import 'package:flutter/material.dart';
class PreviewContainer extends StatelessWidget {
final bool usePreviewSafeArea;
final Widget child;
final bool isIntrusiveSideMenuOpen;
final String? info;
const PreviewContainer({
required Key key,
required this.child,
required this.usePreviewSafeArea,
required this.isIntrusiveSideMenuOpen,
this.info,
}) : super(key: key);
@override
Widget build(BuildContext context) {
final deviceInfo = DeviceSettings.of(context).settings;
final preview = deviceInfo.deviceInfo != null
? DevicePreview(
showDeviceFrame: deviceInfo.showDeviceFrame,
deviceInfo: deviceInfo.deviceInfo!,
deviceOrientation: deviceInfo.orientation,
child: Container(
decoration: BoxDecoration(
border: usePreviewSafeArea
? Border(
left: BorderSide(
color: Theme.of(context).cardColor,
width: iconSize(context) * 2,
),
right: BorderSide(
color: Theme.of(context).cardColor,
width: iconSize(context) * 2,
),
)
: null,
),
child: child,
),
)
: child;
return MediaQuery(
data: MediaQuery.of(context).copyWith(
textScaleFactor: deviceInfo.textScaleFactor,
),
child: Positioned(
top: 0,
bottom: 0,
left: 0,
right: (context.isNotPhoneSize && isIntrusiveSideMenuOpen)
? sideBarSizeProperties(context)
: 0,
child: info == null
? preview
: Stack(
children: [
Positioned.fill(child: preview),
Positioned(
bottom: 6,
left: 6,
right: 6,
child: Center(
child: Card(
child: Padding(
padding: const EdgeInsets.all(8),
child: Text(info!),
),
),
),
),
],
),
),
);
}
}
| dashbook/lib/src/widgets/preview_container.dart/0 | {'file_path': 'dashbook/lib/src/widgets/preview_container.dart', 'repo_id': 'dashbook', 'token_count': 1412} |
import 'package:dashbook/src/widgets/select_device/device_settings.dart';
import 'package:flutter/material.dart';
class TextScaleFactorSlider extends StatelessWidget {
const TextScaleFactorSlider({super.key});
@override
Widget build(BuildContext context) {
final textScaleFactor = DeviceSettings.of(context).settings.textScaleFactor;
return Slider(
value: textScaleFactor,
divisions: 3,
min: 0.85,
max: 1.3,
label: textScaleFactor.toString(),
onChanged:
DeviceSettings.of(context, listen: false).updateTextScaleFactor,
);
}
}
| dashbook/lib/src/widgets/select_device/components/text_scale_factor_slider.dart/0 | {'file_path': 'dashbook/lib/src/widgets/select_device/components/text_scale_factor_slider.dart', 'repo_id': 'dashbook', 'token_count': 215} |
import 'package:dashbook/dashbook.dart';
import 'package:dashbook/src/widgets/keys.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import '../../helpers.dart';
Dashbook _getDashbookTextPropertyAnonymousBuilder() {
final dashbook = Dashbook();
dashbook.storiesOf('List').add('default', (context) {
final number = context.addProperty(CounterButtonProperty('Number'));
return Text('Current: $number');
});
return dashbook;
}
void main() {
group('Custom Properties From Property - Text', () {
testWidgets('shows the property input', (tester) async {
await tester.pumpDashbook(_getDashbookTextPropertyAnonymousBuilder());
expect(find.byKey(kPropertiesIcon), findsOneWidget);
});
testWidgets('returns the default value on first render', (tester) async {
await tester.pumpDashbook(_getDashbookTextPropertyAnonymousBuilder());
expect(find.text('Current: 0'), findsOneWidget);
});
testWidgets('can change the property', (tester) async {
await tester.pumpDashbook(_getDashbookTextPropertyAnonymousBuilder());
await tester.openPropertiesPanel();
await tester.tap(find.byType(OutlinedButton));
await tester.pumpAndSettle();
expect(find.text('Current: 1'), findsOneWidget);
});
});
}
class CounterButtonProperty extends Property<int> {
CounterButtonProperty(super.name, [super.defaultValue = 0]);
@override
Widget createPropertyEditor({required PropertyChanged onChanged, Key? key}) {
return PropertyScaffold(
label: name,
child: OutlinedButton(
onPressed: () {
value = getValue() + 1;
onChanged();
},
child: Text(
getValue().toString(),
),
),
);
}
}
| dashbook/test/properties/custom_propertis/custom_property_test.dart/0 | {'file_path': 'dashbook/test/properties/custom_propertis/custom_property_test.dart', 'repo_id': 'dashbook', 'token_count': 638} |
/// Helper class that handles Duration
class DurationHelper {
/// Return two digits if the number has one
static String twoDigits(int n) => n.toString().padLeft(2, '0');
/// Return formatted time from duration
///
/// For example, Duration of 100 seconds will
/// be displayed as 01:40
static String toFormattedTime(Duration duration) {
final String minutes = twoDigits(duration.inMinutes.remainder(60));
final String seconds = twoDigits(duration.inSeconds.remainder(60));
return '$minutes:$seconds';
}
}
| dashtronaut/lib/helpers/duration_helper.dart/0 | {'file_path': 'dashtronaut/lib/helpers/duration_helper.dart', 'repo_id': 'dashtronaut', 'token_count': 159} |
import 'package:dashtronaut/presentation/common/animations/utils/animations_manager.dart';
import 'package:flutter/material.dart';
class FadeInTransition extends StatefulWidget {
final Widget child;
final Duration? delay;
const FadeInTransition({
Key? key,
required this.child,
this.delay,
}) : super(key: key);
@override
_FadeInTransitionState createState() => _FadeInTransitionState();
}
class _FadeInTransitionState extends State<FadeInTransition>
with SingleTickerProviderStateMixin {
late final AnimationController _animationController;
late final Animation<double> _opacity;
@override
void initState() {
_animationController = AnimationController(
vsync: this,
duration: AnimationsManager.fadeIn.duration,
);
_opacity = AnimationsManager.fadeIn.tween.animate(
CurvedAnimation(
parent: _animationController,
curve: AnimationsManager.fadeIn.curve,
),
);
if (widget.delay == null) {
_animationController.forward();
} else {
Future.delayed(widget.delay!, () {
if (mounted) {
_animationController.forward();
}
});
}
super.initState();
}
@override
void dispose() {
_animationController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return FadeTransition(
opacity: _opacity,
child: widget.child,
);
}
}
| dashtronaut/lib/presentation/common/animations/widgets/fade_in_transition.dart/0 | {'file_path': 'dashtronaut/lib/presentation/common/animations/widgets/fade_in_transition.dart', 'repo_id': 'dashtronaut', 'token_count': 540} |
import 'package:dashtronaut/presentation/layout/screen_type_helper.dart';
import 'package:flutter/cupertino.dart';
abstract class LayoutDelegate {
final BuildContext context;
const LayoutDelegate(this.context);
ScreenTypeHelper get screenTypeHelper;
}
| dashtronaut/lib/presentation/layout/layout_delegate.dart/0 | {'file_path': 'dashtronaut/lib/presentation/layout/layout_delegate.dart', 'repo_id': 'dashtronaut', 'token_count': 79} |
import 'package:dashtronaut/presentation/common/animations/utils/animations_manager.dart';
import 'package:dashtronaut/presentation/common/animations/widgets/fade_in_transition.dart';
import 'package:dashtronaut/presentation/common/dialogs/app_alert_dialog.dart';
import 'package:dashtronaut/presentation/styles/app_text_styles.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 ResetPuzzleButton extends StatelessWidget {
const ResetPuzzleButton({Key? key}) : super(key: key);
void initResetPuzzle(
BuildContext context,
PuzzleProvider puzzleProvider,
StopWatchProvider stopWatchProvider,
) {
if (puzzleProvider.hasStarted && !puzzleProvider.puzzle.isSolved) {
showDialog(
context: context,
builder: (context) {
return AppAlertDialog(
title: 'Are you sure you want to reset your puzzle?',
onConfirm: () {
stopWatchProvider.stop();
puzzleProvider.generate(forceRefresh: true);
},
);
},
);
} else {
stopWatchProvider.stop();
puzzleProvider.generate(forceRefresh: true);
}
}
@override
Widget build(BuildContext context) {
StopWatchProvider stopWatchProvider =
Provider.of<StopWatchProvider>(context, listen: false);
return FadeInTransition(
delay: AnimationsManager.bgLayerAnimationDuration,
child: Consumer<PuzzleProvider>(
builder: (c, puzzleProvider, _) => Padding(
padding: const EdgeInsets.only(top: 20),
child: ElevatedButton(
onPressed: () =>
initResetPuzzle(context, puzzleProvider, stopWatchProvider),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: const [
Icon(Icons.refresh),
SizedBox(width: 7),
Text('Reset', style: AppTextStyles.button),
],
),
),
),
),
);
}
}
| dashtronaut/lib/presentation/puzzle/ui/reset_puzzle_button.dart/0 | {'file_path': 'dashtronaut/lib/presentation/puzzle/ui/reset_puzzle_button.dart', 'repo_id': 'dashtronaut', 'token_count': 940} |
/// Enum representing the seasons
enum Season {
/// Winter
winter,
/// Spring
spring,
/// Summer
summer,
/// Autumn
autumn,
}
/// Extension on [DateTime] to get the season
extension SeasonDate on DateTime {
/// Retrieves the season for the current datetime instance
Season get seasonNorth {
switch (month) {
case DateTime.january || DateTime.february:
return Season.winter;
case DateTime.march:
return day < 21 ? Season.winter : Season.spring;
case DateTime.april || DateTime.may:
return Season.spring;
case DateTime.june:
return day < 21 ? Season.spring : Season.summer;
case DateTime.july || DateTime.august:
return Season.summer;
case DateTime.september:
return day < 22 ? Season.summer : Season.autumn;
case DateTime.october || DateTime.november:
return Season.autumn;
case DateTime.december:
return day < 22 ? Season.autumn : Season.winter;
}
throw Exception('Invalid date');
}
/// Retrieves the season for the current datetime instance
Season get seasonSouth => seasonNorth.inverse;
}
extension on Season {
Season get inverse => Season.values[(index + 2) % 4];
}
| daylight/lib/src/season.dart/0 | {'file_path': 'daylight/lib/src/season.dart', 'repo_id': 'daylight', 'token_count': 442} |
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'gen.dart';
// **************************************************************************
// Generator: FunctionalWidget
// **************************************************************************
class HelloWorld extends HookWidget {
const HelloWorld(this.value, {Key key}) : super(key: key);
final int value;
@override
Widget build(BuildContext _context) => helloWorld(value);
@override
int get hashCode => value.hashCode;
@override
bool operator ==(Object o) =>
identical(o, this) || (o is HelloWorld && value == o.value);
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(IntProperty('value', value));
}
}
| demo_21-01-2019/lib/gen.g.dart/0 | {'file_path': 'demo_21-01-2019/lib/gen.g.dart', 'repo_id': 'demo_21-01-2019', 'token_count': 214} |
import 'package:deposit/deposit.dart';
/// A [DepositAdapter] serves as a data backend for [Deposit] classes.
///
/// It is designed to be generic enough that it can be used against any given
/// data backend.
abstract class DepositAdapter<Id> {
/// Construct a new adapter.
const DepositAdapter();
/// Check if given [id] exists in the [table].
Future<bool> exists(String table, String primaryColumn, Id id);
/// Return list of paginated data.
Future<List<Map<String, dynamic>>> page(
String table, {
required int limit,
required int skip,
OrderBy? orderBy,
});
/// Return data that is referenced by the given [Id] in the [table].
Future<Map<String, dynamic>> getById(
String table,
String primaryColumn,
Id id,
);
/// Return data that is referenced by the given [key] and the [value].
Future<List<Map<String, dynamic>>> by(
String table,
String key,
dynamic value,
);
/// Store data in the backend and return the newly stored data.
Future<Map<String, dynamic>> add(
String table,
String primaryColumn,
Map<String, dynamic> data,
);
/// Store multiple items in the backend and return the newly stored data.
Future<List<Map<String, dynamic>>> addAll(
String table,
String primaryColumn,
List<Map<String, dynamic>> data,
);
/// Update data in the backend and return the newly updated data.
Future<Map<String, dynamic>> update(
String table,
String primaryColumn,
Map<String, dynamic> data,
);
/// Update multiple items in the backend and return the newly updated data.
Future<List<Map<String, dynamic>>> updateAll(
String table,
String primaryColumn,
List<Map<String, dynamic>> data,
);
/// Remove data in the backend.
Future<void> remove(
String table,
String primaryColumn,
Map<String, dynamic> data,
);
/// Remove multiple items in the backend.
Future<void> removeAll(
String table,
String primaryColumn,
List<Map<String, dynamic>> data,
);
// TODO(wolfen): search?
// TODO(wolfen): upsert?
}
| deposit/packages/deposit/lib/src/deposit_adapter.dart/0 | {'file_path': 'deposit/packages/deposit/lib/src/deposit_adapter.dart', 'repo_id': 'deposit', 'token_count': 654} |
export 'src/firestore_deposit_adapter.dart';
| deposit/packages/deposit_firestore/lib/deposit_firestore.dart/0 | {'file_path': 'deposit/packages/deposit_firestore/lib/deposit_firestore.dart', 'repo_id': 'deposit', 'token_count': 17} |
// 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.dart';
class About extends StatefulWidget {
@override
AboutState createState() => AboutState();
}
class AboutState extends State<About> {
static const String heading = '$aboutMenu\n\n';
static const String helpText = '''
This application makes Restful HTTP GET
requests to three different Restful servers.
Selecting a request e.g., Weather will
display the results of the received data on
another page. Navigating back to the main
page to select another Restful request.
The menu, on the main page, has options:
''';
static const String logOption = '\n $logMenu';
static const String aboutOption = '\n $aboutMenu';
static const String logDescr = ' display all messages.';
static const String aboutDescr = ' display this page.';
final TextStyle defaultStyle = const TextStyle(
fontSize: 20,
color: Colors.blueGrey,
);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
// Title
title: const Text(aboutMenu),
),
body: Container(
padding: const EdgeInsets.all(16.0),
child: RichText(
text: TextSpan(
style: defaultStyle,
children: const [
TextSpan(
text: heading,
style: TextStyle(
color: Colors.blueGrey,
fontSize: 38,
fontWeight: FontWeight.w700,
)),
TextSpan(
text: helpText,
),
TextSpan(
text: logOption,
style: TextStyle(
fontWeight: FontWeight.w700,
)),
TextSpan(
text: logDescr,
),
TextSpan(
text: aboutOption,
style: TextStyle(
fontWeight: FontWeight.w700,
)),
TextSpan(
text: aboutDescr,
),
],
),
)),
);
}
}
| devtools/case_study/memory_leak/lib/about.dart/0 | {'file_path': 'devtools/case_study/memory_leak/lib/about.dart', 'repo_id': 'devtools', 'token_count': 1131} |
targets:
$default:
builders:
build_web_compilers|entrypoint:
options:
dart2js_args:
- -O1
| devtools/packages/devtools_app/build.yaml/0 | {'file_path': 'devtools/packages/devtools_app/build.yaml', 'repo_id': 'devtools', 'token_count': 72} |
// 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 '../analytics/analytics_stub.dart'
if (dart.library.html) '../analytics/analytics.dart' as ga;
import '../auto_dispose_mixin.dart';
import '../charts/treemap.dart';
import '../common_widgets.dart';
import '../config_specific/drag_and_drop/drag_and_drop.dart';
import '../config_specific/server/server.dart' as server;
import '../config_specific/url/url.dart';
import '../file_import.dart';
import '../globals.dart';
import '../notifications.dart';
import '../screen.dart';
import '../split.dart';
import '../theme.dart';
import '../ui/icons.dart';
import '../utils.dart';
import 'app_size_controller.dart';
import 'app_size_table.dart';
import 'code_size_attribution.dart';
const initialFractionForTreemap = 0.67;
const initialFractionForTreeTable = 0.33;
class AppSizeScreen extends Screen {
const AppSizeScreen()
: super.conditional(
id: id,
requiresDartVm: true,
title: 'App Size',
icon: Octicons.fileZip,
);
static const analysisTabKey = Key('Analysis Tab');
static const diffTabKey = Key('Diff Tab');
/// The ID (used in routing) for the tabbed app-size page.
///
/// This must be different to the top-level appSizePageId which is also used
/// in routing when to ensure they have unique URLs.
static const id = 'app-size';
@visibleForTesting
static const dropdownKey = Key('Diff Tree Type Dropdown');
@visibleForTesting
static const analysisViewTreemapKey = Key('Analysis View Treemap');
@visibleForTesting
static const diffViewTreemapKey = Key('Diff View Treemap');
static const loadingMessage =
'Loading data...\nPlease do not refresh or leave this page.';
@override
String get docPageId => id;
@override
Widget build(BuildContext context) {
// Since `handleDrop` is not specified for this [DragAndDrop] widget, drag
// and drop events will be absorbed by it, meaning drag and drop actions
// will be a no-op if they occur over this area. [DragAndDrop] widgets
// lower in the tree will have priority over this one.
return const DragAndDrop(child: AppSizeBody());
}
}
class AppSizeBody extends StatefulWidget {
const AppSizeBody();
@override
_AppSizeBodyState createState() => _AppSizeBodyState();
}
class _AppSizeBodyState extends State<AppSizeBody>
with AutoDisposeMixin, SingleTickerProviderStateMixin {
static const diffTab = Tab(text: 'Diff', key: AppSizeScreen.diffTabKey);
static const analysisTab =
Tab(text: 'Analysis', key: AppSizeScreen.analysisTabKey);
static const tabs = [analysisTab, diffTab];
AppSizeController controller;
TabController _tabController;
bool preLoadingData = false;
@override
void initState() {
super.initState();
ga.screen(AppSizeScreen.id);
_tabController = TabController(length: tabs.length, vsync: this);
addAutoDisposeListener(_tabController);
}
Future<void> maybeLoadAppSizeFiles() async {
final queryParams = loadQueryParams();
if (queryParams.containsKey(baseAppSizeFilePropertyName)) {
// TODO(kenz): does this have to be in a setState()?
preLoadingData = true;
final baseAppSizeFile = await server
.requestBaseAppSizeFile(queryParams[baseAppSizeFilePropertyName]);
DevToolsJsonFile testAppSizeFile;
if (queryParams.containsKey(testAppSizeFilePropertyName)) {
testAppSizeFile = await server
.requestTestAppSizeFile(queryParams[testAppSizeFilePropertyName]);
}
// TODO(kenz): add error handling if the files are null
if (baseAppSizeFile != null) {
if (testAppSizeFile != null) {
controller.loadDiffTreeFromJsonFiles(
oldFile: baseAppSizeFile,
newFile: testAppSizeFile,
onError: _pushErrorMessage,
);
_tabController.animateTo(tabs.indexOf(diffTab));
} else {
controller.loadTreeFromJsonFile(
jsonFile: baseAppSizeFile,
onError: _pushErrorMessage,
);
_tabController.animateTo(tabs.indexOf(analysisTab));
}
}
}
if (preLoadingData) {
setState(() {
preLoadingData = false;
});
}
}
@override
void dispose() {
super.dispose();
_tabController.dispose();
}
void _pushErrorMessage(String error) {
if (mounted) Notifications.of(context).push(error);
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
final newController = Provider.of<AppSizeController>(context);
if (newController == controller) return;
controller = newController;
maybeLoadAppSizeFiles();
addAutoDisposeListener(controller.activeDiffTreeType);
}
@override
Widget build(BuildContext context) {
if (preLoadingData) {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
devToolsExtensionPoints.loadingAppSizeDataMessage(),
textAlign: TextAlign.center,
),
const SizedBox(height: defaultSpacing),
const CircularProgressIndicator(),
],
),
);
}
final currentTab = tabs[_tabController.index];
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
height: defaultButtonHeight,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
TabBar(
labelColor: Theme.of(context).textTheme.bodyText1.color,
isScrollable: true,
controller: _tabController,
tabs: tabs,
),
Row(
children: [
if (currentTab.key == AppSizeScreen.diffTabKey)
_buildDiffTreeTypeDropdown(),
const SizedBox(width: defaultSpacing),
_buildClearButton(currentTab.key),
],
),
],
),
),
Expanded(
child: TabBarView(
physics: defaultTabBarViewPhysics,
children: const [
AnalysisView(),
DiffView(),
],
controller: _tabController,
),
),
],
);
}
DropdownButtonHideUnderline _buildDiffTreeTypeDropdown() {
return DropdownButtonHideUnderline(
key: AppSizeScreen.dropdownKey,
child: DropdownButton<DiffTreeType>(
value: controller.activeDiffTreeType.value,
items: [
_buildMenuItem(DiffTreeType.combined),
_buildMenuItem(DiffTreeType.increaseOnly),
_buildMenuItem(DiffTreeType.decreaseOnly),
],
onChanged: (newDiffTreeType) {
controller.changeActiveDiffTreeType(newDiffTreeType);
},
),
);
}
DropdownMenuItem _buildMenuItem(DiffTreeType diffTreeType) {
return DropdownMenuItem<DiffTreeType>(
value: diffTreeType,
child: Text(diffTreeType.display),
);
}
Widget _buildClearButton(Key activeTabKey) {
return ClearButton(
onPressed: () => controller.clear(activeTabKey),
);
}
}
class AnalysisView extends StatefulWidget {
const AnalysisView();
// TODO(kenz): add links to documentation on how to generate these files, and
// mention the import file button once it is hooked up to a file picker.
static const importInstructions = 'Drag and drop an AOT snapshot or'
' size analysis file for debugging';
@override
_AnalysisViewState createState() => _AnalysisViewState();
}
class _AnalysisViewState extends State<AnalysisView> with AutoDisposeMixin {
AppSizeController controller;
TreemapNode analysisRoot;
@override
void didChangeDependencies() {
super.didChangeDependencies();
final newController = Provider.of<AppSizeController>(context);
if (newController == controller) return;
controller = newController;
analysisRoot = controller.analysisRoot.value;
addAutoDisposeListener(controller.analysisRoot, () {
setState(() {
analysisRoot = controller.analysisRoot.value;
});
});
addAutoDisposeListener(controller.analysisJsonFile);
}
@override
Widget build(BuildContext context) {
return Column(
children: [
Expanded(
child: analysisRoot != null
? _buildTreemapAndTableSplitView()
: _buildImportFileView(),
),
],
);
}
Widget _buildTreemapAndTableSplitView() {
return OutlineDecoration(
child: Column(
children: [
AreaPaneHeader(
title: Text(_generateSingleFileHeaderText()),
maxLines: 2,
needsTopBorder: false,
),
Expanded(
child: Split(
axis: Axis.vertical,
children: [
_buildTreemap(),
Row(
children: [
Flexible(
child: AppSizeAnalysisTable(rootNode: analysisRoot),
),
if (controller.analysisCallGraphRoot.value != null)
Flexible(
child: CallGraphWithDominators(
callGraphRoot: controller.analysisCallGraphRoot.value,
),
),
],
),
],
initialFractions: const [
initialFractionForTreemap,
initialFractionForTreeTable,
],
),
),
],
),
);
}
String _generateSingleFileHeaderText() {
String output = controller.analysisJsonFile.value.isAnalyzeSizeFile
? 'Total size analysis: '
: 'Dart AOT snapshot: ';
output += controller.analysisJsonFile.value.displayText;
return output;
}
Widget _buildTreemap() {
return LayoutBuilder(
key: AppSizeScreen.analysisViewTreemapKey,
builder: (context, constraints) {
return Treemap.fromRoot(
rootNode: analysisRoot,
levelsVisible: 2,
isOutermostLevel: true,
width: constraints.maxWidth,
height: constraints.maxHeight,
onRootChangedCallback: controller.changeAnalysisRoot,
);
},
);
}
Widget _buildImportFileView() {
return ValueListenableBuilder(
valueListenable: controller.processingNotifier,
builder: (context, processing, _) {
if (processing) {
return Center(
child: Text(
AppSizeScreen.loadingMessage,
textAlign: TextAlign.center,
style: TextStyle(
color: Theme.of(context).textTheme.headline1.color,
),
),
);
} else {
return Column(
children: [
Flexible(
child: FileImportContainer(
title: 'Size analysis',
instructions: AnalysisView.importInstructions,
actionText: 'Analyze Size',
onAction: (jsonFile) {
controller.loadTreeFromJsonFile(
jsonFile: jsonFile,
onError: (error) {
if (mounted) Notifications.of(context).push(error);
},
);
},
),
),
],
);
}
});
}
}
class DiffView extends StatefulWidget {
const DiffView();
// TODO(kenz): add links to documentation on how to generate these files, and
// mention the import file button once it is hooked up to a file picker.
static const importOldInstructions = 'Drag and drop an original (old) AOT '
'snapshot or size analysis file for debugging';
static const importNewInstructions = 'Drag and drop a modified (new) AOT '
'snapshot or size analysis file for debugging';
@override
_DiffViewState createState() => _DiffViewState();
}
class _DiffViewState extends State<DiffView> with AutoDisposeMixin {
AppSizeController controller;
TreemapNode diffRoot;
@override
void didChangeDependencies() {
super.didChangeDependencies();
final newController = Provider.of<AppSizeController>(context);
if (newController == controller) return;
controller = newController;
diffRoot = controller.diffRoot.value;
addAutoDisposeListener(controller.diffRoot, () {
setState(() {
diffRoot = controller.diffRoot.value;
});
});
addAutoDisposeListener(controller.activeDiffTreeType);
addAutoDisposeListener(controller.oldDiffJsonFile);
addAutoDisposeListener(controller.newDiffJsonFile);
}
@override
Widget build(BuildContext context) {
return Column(
children: [
Expanded(
child: diffRoot != null
? _buildTreemapAndTableSplitView()
: _buildImportDiffView(),
),
],
);
}
Widget _buildTreemapAndTableSplitView() {
return OutlineDecoration(
child: Column(
children: [
AreaPaneHeader(
title: Text(_generateDualFileHeaderText()),
maxLines: 2,
needsTopBorder: false,
),
Expanded(
child: Split(
axis: Axis.vertical,
children: [
_buildTreemap(),
Row(
children: [
Flexible(
child: AppSizeDiffTable(rootNode: diffRoot),
),
if (controller.diffCallGraphRoot.value != null)
Flexible(
child: CallGraphWithDominators(
callGraphRoot: controller.diffCallGraphRoot.value,
),
),
],
),
],
initialFractions: const [
initialFractionForTreemap,
initialFractionForTreeTable,
],
),
),
],
),
);
}
String _generateDualFileHeaderText() {
String output = 'Diffing ';
output += controller.oldDiffJsonFile.value.isAnalyzeSizeFile
? 'total size analyses: '
: 'Dart AOT snapshots: ';
output += controller.oldDiffJsonFile.value.displayText;
output += ' (OLD) vs (NEW) ';
output += controller.newDiffJsonFile.value.displayText;
return output;
}
Widget _buildImportDiffView() {
return ValueListenableBuilder(
valueListenable: controller.processingNotifier,
builder: (context, processing, _) {
if (processing) {
return _buildLoadingMessage();
} else {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
child: DualFileImportContainer(
firstFileTitle: 'Old',
secondFileTitle: 'New',
// TODO(kenz): perhaps bold "original" and "modified".
firstInstructions: DiffView.importOldInstructions,
secondInstructions: DiffView.importNewInstructions,
actionText: 'Analyze Diff',
onAction: (oldFile, newFile, onError) =>
controller.loadDiffTreeFromJsonFiles(
oldFile: oldFile,
newFile: newFile,
onError: onError,
),
),
),
],
);
}
},
);
}
Widget _buildLoadingMessage() {
return Center(
child: Text(
AppSizeScreen.loadingMessage,
textAlign: TextAlign.center,
style: TextStyle(
color: Theme.of(context).textTheme.headline1.color,
),
),
);
}
Widget _buildTreemap() {
return LayoutBuilder(
key: AppSizeScreen.diffViewTreemapKey,
builder: (context, constraints) {
return Treemap.fromRoot(
rootNode: diffRoot,
levelsVisible: 2,
isOutermostLevel: true,
width: constraints.maxWidth,
height: constraints.maxHeight,
onRootChangedCallback: controller.changeDiffRoot,
);
},
);
}
}
extension DiffTreeTypeExtension on DiffTreeType {
String get display {
switch (this) {
case DiffTreeType.increaseOnly:
return 'Increase Only';
case DiffTreeType.decreaseOnly:
return 'Decrease Only';
case DiffTreeType.combined:
default:
return 'Combined';
}
}
}
| devtools/packages/devtools_app/lib/src/app_size/app_size_screen.dart/0 | {'file_path': 'devtools/packages/devtools_app/lib/src/app_size/app_size_screen.dart', 'repo_id': 'devtools', 'token_count': 7615} |
// 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';
/// An event type for use with [MessageBus].
class BusEvent {
BusEvent(this.type, {this.data});
final String type;
final Object data;
@override
String toString() => type;
}
/// A message bus class. Clients can listen for classes of events, optionally
/// filtered by a string type. This can be used to decouple events sources and
/// event listeners.
class MessageBus {
MessageBus() {
_controller = StreamController.broadcast();
}
StreamController<BusEvent> _controller;
/// Listen for events on the event bus. Clients can pass in an optional [type],
/// which filters the events to only those specific ones.
Stream<BusEvent> onEvent({String type}) {
if (type == null) {
return _controller.stream;
} else {
return _controller.stream.where((BusEvent event) => event.type == type);
}
}
/// Add an event to the event bus.
void addEvent(BusEvent event) {
_controller.add(event);
}
/// Close (destroy) this [MessageBus]. This is generally not used outside of a
/// testing context. All stream listeners will be closed and the bus will not
/// fire any more events.
void close() {
_controller.close();
}
}
| devtools/packages/devtools_app/lib/src/core/message_bus.dart/0 | {'file_path': 'devtools/packages/devtools_app/lib/src/core/message_bus.dart', 'repo_id': 'devtools', 'token_count': 402} |
// 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/foundation.dart';
import 'package:flutter/material.dart' hide Stack;
import 'package:provider/provider.dart';
import '../common_widgets.dart';
import '../theme.dart';
import '../tree.dart';
import '../utils.dart';
import 'debugger_controller.dart';
import 'debugger_model.dart';
class Variables extends StatelessWidget {
const Variables({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
final controller = Provider.of<DebuggerController>(context);
return ValueListenableBuilder<List<Variable>>(
valueListenable: controller.variables,
builder: (context, variables, _) {
if (variables.isEmpty) return const SizedBox();
// TODO(kenz): preserve expanded state of tree on switching frames and
// on stepping.
return TreeView<Variable>(
dataRoots: variables,
dataDisplayProvider: (variable, onPressed) =>
displayProvider(context, variable, onPressed),
onItemPressed: (variable) => onItemPressed(variable, controller),
);
},
);
}
void onItemPressed(Variable v, DebuggerController controller) {
// On expansion, lazily build the variables tree for performance reasons.
if (v.isExpanded) {
v.children.forEach(controller.buildVariablesTree);
}
}
}
class VariablesList extends StatelessWidget {
const VariablesList({Key key, this.lines}) : super(key: key);
final List<Variable> lines;
@override
Widget build(BuildContext context) {
final controller = Provider.of<DebuggerController>(context);
if (lines.isEmpty) return const SizedBox();
// TODO(kenz): preserve expanded state of tree on switching frames and
// on stepping.
return TreeView<Variable>(
dataRoots: lines,
dataDisplayProvider: (variable, onPressed) =>
displayProvider(context, variable, onPressed),
onItemPressed: (variable) => onItemPressed(variable, controller),
);
}
void onItemPressed(Variable v, DebuggerController controller) {
// On expansion, lazily build the variables tree for performance reasons.
if (v.isExpanded) {
v.children.forEach(controller.buildVariablesTree);
}
}
}
class ExpandableVariable extends StatelessWidget {
const ExpandableVariable({Key key, this.variable, this.debuggerController})
: super(key: key);
final ValueListenable<Variable> variable;
final DebuggerController debuggerController;
@override
Widget build(BuildContext context) {
return ValueListenableBuilder<Variable>(
valueListenable: variable,
builder: (context, variable, _) {
final controller =
debuggerController ?? Provider.of<DebuggerController>(context);
if (variable == null) return const SizedBox();
// TODO(kenz): preserve expanded state of tree on switching frames and
// on stepping.
return TreeView<Variable>(
dataRoots: [variable],
shrinkWrap: true,
dataDisplayProvider: (variable, onPressed) =>
displayProvider(context, variable, onPressed),
onItemPressed: (variable) => onItemPressed(variable, controller),
);
},
);
}
void onItemPressed(Variable v, DebuggerController controller) {
// On expansion, lazily build the variables tree for performance reasons.
if (v.isExpanded) {
v.children.forEach(controller.buildVariablesTree);
}
}
}
Widget displayProvider(
BuildContext context,
Variable variable,
VoidCallback onTap,
) {
final theme = Theme.of(context);
// TODO(devoncarew): Here, we want to wait until the tooltip wants to show,
// then call toString() on variable and render the result in a tooltip. We
// should also include the type of the value in the tooltip if the variable
// is not null.
if (variable.text != null) {
return SelectableText.rich(
TextSpan(
children: processAnsiTerminalCodes(
variable.text,
theme.fixedFontStyle,
),
),
onTap: onTap,
);
}
return Tooltip(
message: variable.displayValue,
waitDuration: tooltipWaitLong,
child: SelectableText.rich(
TextSpan(
text: variable.boundVar.name.isNotEmpty ?? false
? '${variable.boundVar.name}: '
: null,
style: theme.fixedFontStyle,
children: [
TextSpan(
text: variable.displayValue,
style: theme.subtleFixedFontStyle,
),
],
),
onTap: onTap,
),
);
}
| devtools/packages/devtools_app/lib/src/debugger/variables.dart/0 | {'file_path': 'devtools/packages/devtools_app/lib/src/debugger/variables.dart', 'repo_id': 'devtools', 'token_count': 1705} |
// Copyright 2018 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 'config_specific/ide_theme/ide_theme.dart';
import 'core/message_bus.dart';
import 'extension_points/extensions_base.dart';
import 'framework_controller.dart';
import 'preferences.dart';
import 'service_manager.dart';
import 'storage.dart';
import 'survey.dart';
/// Snapshot mode is an offline mode where DevTools can operate on an imported
/// data file.
bool offlineMode = false;
// TODO(kenz): store this data in an inherited widget.
Map<String, dynamic> offlineDataJson = {};
final Map<Type, dynamic> globals = <Type, dynamic>{};
ServiceConnectionManager get serviceManager =>
globals[ServiceConnectionManager];
MessageBus get messageBus => globals[MessageBus];
FrameworkController get frameworkController => globals[FrameworkController];
Storage get storage => globals[Storage];
SurveyService get surveyService => globals[SurveyService];
PreferencesController get preferences => globals[PreferencesController];
DevToolsExtensionPoints get devToolsExtensionPoints =>
globals[DevToolsExtensionPoints];
IdeTheme get ideTheme => globals[IdeTheme];
void setGlobal(Type clazz, dynamic instance) {
globals[clazz] = instance;
}
| devtools/packages/devtools_app/lib/src/globals.dart/0 | {'file_path': 'devtools/packages/devtools_app/lib/src/globals.dart', 'repo_id': 'devtools', 'token_count': 375} |
// 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:collection';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:vm_service/vm_service.dart' hide Stack;
import '../analytics/analytics_stub.dart'
if (dart.library.html) '../analytics/analytics.dart' as ga;
import '../analytics/constants.dart' as analytics_constants;
import '../auto_dispose_mixin.dart';
import '../blocking_action_mixin.dart';
import '../common_widgets.dart';
import '../connected_app.dart';
import '../error_badge_manager.dart';
import '../globals.dart';
import '../screen.dart';
import '../service_extensions.dart' as extensions;
import '../split.dart';
import '../theme.dart';
import '../ui/icons.dart';
import '../ui/service_extension_widgets.dart';
import 'inspector_controller.dart';
import 'inspector_screen_details_tab.dart';
import 'inspector_service.dart';
import 'inspector_tree_flutter.dart';
class InspectorScreen extends Screen {
const InspectorScreen()
: super.conditional(
id: id,
requiresLibrary: flutterLibraryUri,
requiresDebugBuild: true,
title: 'Flutter Inspector',
icon: Octicons.deviceMobile,
);
static const id = 'inspector';
@override
String get docPageId => screenId;
@override
Widget build(BuildContext context) => const InspectorScreenBody();
}
class InspectorScreenBody extends StatefulWidget {
const InspectorScreenBody();
@override
InspectorScreenBodyState createState() => InspectorScreenBodyState();
}
class InspectorScreenBodyState extends State<InspectorScreenBody>
with BlockingActionMixin, AutoDisposeMixin {
bool _expandCollapseSupported = false;
bool _layoutExplorerSupported = false;
bool connectionInProgress = false;
InspectorService inspectorService;
InspectorController inspectorController;
InspectorTreeControllerFlutter summaryTreeController;
InspectorTreeControllerFlutter detailsTreeController;
bool displayedWidgetTrackingNotice = false;
bool get enableButtons =>
actionInProgress == false && connectionInProgress == false;
static const summaryTreeKey = Key('Summary Tree');
static const detailsTreeKey = Key('Details Tree');
static const includeTextWidth = 900.0;
@override
void initState() {
super.initState();
ga.screen(InspectorScreen.id);
autoDispose(
serviceManager.onConnectionAvailable.listen(_handleConnectionStart));
if (serviceManager.connectedAppInitialized) {
_handleConnectionStart(serviceManager.service);
}
autoDispose(
serviceManager.onConnectionClosed.listen(_handleConnectionStop));
}
@override
void dispose() {
inspectorService?.dispose();
inspectorController?.dispose();
super.dispose();
}
void _onExpandClick() {
blockWhileInProgress(inspectorController.expandAllNodesInDetailsTree);
}
void _onResetClick() {
blockWhileInProgress(inspectorController.collapseDetailsToSelected);
}
@override
Widget build(BuildContext context) {
final summaryTree = _buildSummaryTreeColumn();
final detailsTree = InspectorTree(
key: detailsTreeKey,
controller: detailsTreeController,
);
final splitAxis = Split.axisFor(context, 0.85);
return Column(
children: <Widget>[
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ValueListenableBuilder(
valueListenable: serviceManager.serviceExtensionManager
.hasServiceExtension(
extensions.toggleSelectWidgetMode.extension),
builder: (_, selectModeSupported, __) {
return ServiceExtensionButtonGroup(
extensions: [
selectModeSupported
? extensions.toggleSelectWidgetMode
: extensions.toggleOnDeviceWidgetInspector
],
minIncludeTextWidth: includeTextWidth,
);
},
),
const SizedBox(width: denseSpacing),
IconLabelButton(
onPressed: _refreshInspector,
icon: Icons.refresh,
label: 'Refresh Tree',
includeTextWidth: includeTextWidth,
),
const Spacer(),
Row(children: getServiceExtensionWidgets()),
],
),
const SizedBox(height: denseRowSpacing),
Expanded(
child: Split(
axis: splitAxis,
initialFractions: const [0.33, 0.67],
children: [
summaryTree,
InspectorDetailsTabController(
detailsTree: detailsTree,
controller: inspectorController,
actionButtons: _expandCollapseButtons(),
layoutExplorerSupported: _layoutExplorerSupported,
),
],
),
),
],
);
}
Widget _buildSummaryTreeColumn() => OutlineDecoration(
child: ValueListenableBuilder(
valueListenable: serviceManager.errorBadgeManager
.erroredItemsForPage(InspectorScreen.id),
builder: (_, LinkedHashMap<String, DevToolsError> errors, __) {
final inspectableErrors = errors.map(
(key, value) => MapEntry(key, value as InspectableWidgetError));
return Stack(
children: [
InspectorTree(
key: summaryTreeKey,
controller: summaryTreeController,
isSummaryTree: true,
widgetErrors: inspectableErrors,
),
if (errors.isNotEmpty && inspectorController != null)
ValueListenableBuilder(
valueListenable: inspectorController.selectedErrorIndex,
builder: (_, selectedErrorIndex, __) => Positioned(
top: 0,
right: 0,
child: ErrorNavigator(
errors: inspectableErrors,
errorIndex: selectedErrorIndex,
onSelectError: inspectorController.selectErrorByIndex,
),
),
)
],
);
},
),
);
List<Widget> getServiceExtensionWidgets() {
return [
ServiceExtensionButtonGroup(
minIncludeTextWidth: 1050,
extensions: [extensions.slowAnimations],
),
const SizedBox(width: denseSpacing),
ServiceExtensionButtonGroup(
minIncludeTextWidth: 1050,
extensions: [extensions.debugPaint, extensions.debugPaintBaselines],
),
const SizedBox(width: denseSpacing),
ServiceExtensionButtonGroup(
minIncludeTextWidth: 1250,
extensions: [
extensions.repaintRainbow,
extensions.invertOversizedImages,
],
),
// TODO(jacobr): implement TogglePlatformSelector.
// TogglePlatformSelector().selector
];
}
Widget _expandCollapseButtons() {
if (!_expandCollapseSupported) return null;
return Align(
alignment: Alignment.centerRight,
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
mainAxisSize: MainAxisSize.min,
children: [
SizedBox(
child: IconLabelButton(
icon: Icons.unfold_more,
onPressed: enableButtons ? _onExpandClick : null,
label: 'Expand all',
includeTextWidth: includeTextWidth,
),
),
const SizedBox(width: denseSpacing),
SizedBox(
child: IconLabelButton(
icon: Icons.unfold_less,
onPressed: enableButtons ? _onResetClick : null,
label: 'Collapse to selected',
includeTextWidth: includeTextWidth,
),
)
],
),
);
}
void _onExpandCollapseSupported() {
setState(() {
_expandCollapseSupported = true;
});
}
void _onLayoutExplorerSupported() {
setState(() {
_layoutExplorerSupported = true;
});
}
void _handleConnectionStart(VmService service) async {
setState(() {
connectionInProgress = true;
});
try {
// Init the inspector service, or return null.
inspectorService =
await InspectorService.create(service).catchError((e) => null);
} finally {
setState(() {
connectionInProgress = false;
});
}
if (inspectorService == null) {
return;
}
setState(() {
inspectorController?.dispose();
summaryTreeController = InspectorTreeControllerFlutter();
detailsTreeController = InspectorTreeControllerFlutter();
inspectorController = InspectorController(
inspectorTree: summaryTreeController,
detailsTree: detailsTreeController,
inspectorService: inspectorService,
treeType: FlutterTreeType.widget,
onExpandCollapseSupported: _onExpandCollapseSupported,
onLayoutExplorerSupported: _onLayoutExplorerSupported,
);
// Clear any existing badge/errors for older errors that were collected.
serviceManager.errorBadgeManager.clearErrors(InspectorScreen.id);
inspectorController.filterErrors();
// TODO(jacobr): move this notice display to once a day.
if (!displayedWidgetTrackingNotice) {
// ignore: unawaited_futures
inspectorService.isWidgetCreationTracked().then((bool value) {
if (value) {
return;
}
displayedWidgetTrackingNotice = true;
// TODO(jacobr): implement showMessage.
// framework.showMessage(
// message: trackWidgetCreationWarning,
// screenId: inspectorScreenId,
//);
});
}
});
}
void _handleConnectionStop(dynamic event) {
inspectorController?.setActivate(false);
inspectorController?.dispose();
setState(() {
inspectorController = null;
});
}
void _refreshInspector() {
ga.select(analytics_constants.inspector, analytics_constants.refresh);
blockWhileInProgress(() async {
await inspectorController?.onForceRefresh();
});
}
}
class ErrorNavigator extends StatelessWidget {
const ErrorNavigator({
Key key,
@required this.errors,
@required this.errorIndex,
@required this.onSelectError,
}) : super(key: key);
final LinkedHashMap<String, InspectableWidgetError> errors;
final int errorIndex;
final Function(int) onSelectError;
@override
Widget build(BuildContext context) {
final label = errorIndex != null
? 'Error ${errorIndex + 1}/${errors.length}'
: 'Errors: ${errors.length}';
return Container(
color: devtoolsError,
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: defaultSpacing,
vertical: denseSpacing,
),
child: Row(
children: [
Padding(
padding: const EdgeInsets.only(right: denseSpacing),
child: Text(label),
),
IconButton(
padding: EdgeInsets.zero,
constraints: const BoxConstraints(),
splashRadius: defaultIconSize,
icon: const Icon(Icons.keyboard_arrow_up),
onPressed: _previousError,
),
IconButton(
padding: EdgeInsets.zero,
constraints: const BoxConstraints(),
splashRadius: defaultIconSize,
icon: const Icon(Icons.keyboard_arrow_down),
onPressed: _nextError,
),
],
),
),
);
}
void _previousError() {
var newIndex = errorIndex == null ? errors.length - 1 : errorIndex - 1;
while (newIndex < 0) {
newIndex += errors.length;
}
onSelectError(newIndex);
}
void _nextError() {
final newIndex = errorIndex == null ? 0 : (errorIndex + 1) % errors.length;
onSelectError(newIndex);
}
}
| devtools/packages/devtools_app/lib/src/inspector/inspector_screen.dart/0 | {'file_path': 'devtools/packages/devtools_app/lib/src/inspector/inspector_screen.dart', 'repo_id': 'devtools', 'token_count': 5220} |
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:vm_service/vm_service.dart';
import '../auto_dispose_mixin.dart';
import '../common_widgets.dart';
import '../dialogs.dart';
import '../flutter_widgets/linked_scroll_controller.dart';
import '../theme.dart';
import '../ui/utils.dart';
import 'memory_controller.dart';
import 'memory_screen.dart';
import 'memory_snapshot_models.dart';
/// First two libraries are special e.g., dart:* and package:flutter*
const _dartLibraryUriPrefix = 'dart:';
const _flutterLibraryUriPrefix = 'package:flutter';
const _collectionLibraryUri = 'package:collection';
const _intlLibraryUri = 'package:intl';
const _vectorMathLibraryUri = 'package:vector_math';
/// Name displayed in filter dialog, for wildcard groups.
const _prettyPrintDartAbbreviation = '$_dartLibraryUriPrefix*';
const _prettyPrintFlutterAbbreviation = '$_flutterLibraryUriPrefix*';
/// State of the libraries, wildcard included, filtered (shown or hidden).
/// groupBy uses this class to determine is the library should be filtered.
class FilteredLibraries {
final List<String> _filteredLibraries = [
_dartLibraryUriPrefix,
_collectionLibraryUri,
_flutterLibraryUriPrefix,
_intlLibraryUri,
_vectorMathLibraryUri,
];
static String normalizeLibraryUri(Library library) {
final uriParts = library.uri.split('/');
final firstPart = uriParts.first;
if (firstPart.startsWith(_dartLibraryUriPrefix)) {
return _dartLibraryUriPrefix;
} else if (firstPart.startsWith(_flutterLibraryUriPrefix)) {
return _flutterLibraryUriPrefix;
} else {
return firstPart;
}
}
List<String> get librariesFiltered =>
_filteredLibraries.toList(growable: false);
bool get isDartLibraryFiltered =>
_filteredLibraries.contains(_dartLibraryUriPrefix);
bool get isFlutterLibraryFiltered =>
_filteredLibraries.contains(_flutterLibraryUriPrefix);
void clearFilters() {
_filteredLibraries.clear();
}
void addFilter(String libraryUri) {
_filteredLibraries.add(libraryUri);
}
void removeFilter(String libraryUri) {
_filteredLibraries.remove(libraryUri);
}
// Keys in the libraries map is a normalized library name.
List<String> sort() => _filteredLibraries..sort();
bool isDartLibrary(Library library) =>
library.uri.startsWith(_dartLibraryUriPrefix);
bool isFlutterLibrary(Library library) =>
library.uri.startsWith(_flutterLibraryUriPrefix);
bool isDartLibraryName(String libraryName) =>
libraryName.startsWith(_dartLibraryUriPrefix);
bool isFlutterLibraryName(String libraryName) =>
libraryName.startsWith(_flutterLibraryUriPrefix);
bool isLibraryFiltered(String libraryName) =>
// Are dart:* libraries filtered and its a Dart library?
(_filteredLibraries.contains(_dartLibraryUriPrefix) &&
isDartLibraryName(libraryName)) ||
// Are package:flutter* filtered and its a Flutter package?
(_filteredLibraries.contains(_flutterLibraryUriPrefix) &&
isFlutterLibraryName(libraryName)) ||
// Is this library filtered?
_filteredLibraries.contains(libraryName);
}
/// State of the libraries and packages (hidden or not) for the filter dialog.
class LibraryFilter {
LibraryFilter(this.displayName, this.hide);
/// Displayed library name.
final String displayName;
/// Whether classes in this library hidden (filtered).
bool hide;
}
class SnapshotFilterDialog extends StatefulWidget {
const SnapshotFilterDialog(this.controller);
final MemoryController controller;
@override
SnapshotFilterState createState() => SnapshotFilterState();
}
class SnapshotFilterState extends State<SnapshotFilterDialog>
with AutoDisposeMixin {
MemoryController controller;
LinkedScrollControllerGroup _controllers;
ScrollController _letters;
bool oldFilterPrivateClassesValue;
bool oldFilterZeroInstancesValue;
bool oldFilterLibraryNoInstancesValue;
final oldFilteredLibraries = <String, bool>{};
@visibleForTesting
static const snapshotFilterDialogKey = Key('SnapshotFilterDialog');
// Define here because exportButtonKey is @visibleForTesting and
// and can't be ref'd outside of file.
static void gaActionForSnapshotFilterDialog() {
MemoryScreen.gaAction(key: snapshotFilterDialogKey);
}
@override
void initState() {
super.initState();
_controllers = LinkedScrollControllerGroup();
_letters = _controllers.addAndGet();
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
if (controller == widget.controller) return;
controller = widget.controller;
buildFilters();
oldFilterPrivateClassesValue = controller.filterPrivateClasses.value;
oldFilterZeroInstancesValue = controller.filterZeroInstances.value;
oldFilterLibraryNoInstancesValue =
controller.filterLibraryNoInstances.value;
final oldFiltered = controller.filteredLibrariesByGroupName;
for (var key in oldFiltered.keys) {
oldFilteredLibraries[key] = oldFiltered[key].first.hide;
}
cancel();
}
void addLibrary(String libraryName, {bool hideState = false}) {
final filteredGroup = controller.filteredLibrariesByGroupName;
final filters = controller.libraryFilters;
final isFiltered = filters.isLibraryFiltered(libraryName);
String groupedName = libraryName;
bool hide = hideState;
if (isFiltered) {
if (filters.isDartLibraryName(libraryName)) {
groupedName = _prettyPrintDartAbbreviation;
} else if (filters.isFlutterLibraryName(libraryName)) {
groupedName = _prettyPrintFlutterAbbreviation;
}
}
hide = isFiltered;
// Used by checkboxes in dialog.
filteredGroup[groupedName] ??= [];
filteredGroup[groupedName].add(LibraryFilter(libraryName, hide));
}
void buildFilters() {
if (controller == null) return;
// First time filters created, populate with the default list of libraries
// to filters
if (controller.filteredLibrariesByGroupName.isEmpty) {
for (final library in controller.libraryFilters.librariesFiltered) {
addLibrary(library, hideState: true);
}
// If not snapshots, return no libraries to process.
if (controller.snapshots.isEmpty) return;
}
// No libraries to compute until a snapshot exist.
if (controller.snapshots.isEmpty) return;
final libraries = controller.libraryRoot == null
? controller.activeSnapshot.children
: controller.libraryRoot.children;
libraries..sort((a, b) => a.name.compareTo(b.name));
for (final library in libraries) {
// Don't include external and filtered these are a composite and can't be filtered out.
if (library.name != externalLibraryName &&
library.name != filteredLibrariesName) {
addLibrary(library.name);
}
}
}
/// Process wildcard groups dart:* and package:flutter*. If a wildcard group is
/// toggled from on to off then all the dart: packages will appear if the group
/// dart:* is toggled back on then all the dart: packages must be removed.
void cleanupFilteredLibrariesByGroupName() {
final filteredGroup = controller.filteredLibrariesByGroupName;
final dartGlobal = filteredGroup[_prettyPrintDartAbbreviation].first.hide;
final flutterGlobal =
filteredGroup[_prettyPrintFlutterAbbreviation].first.hide;
filteredGroup.removeWhere((groupName, libraryFilter) {
if (dartGlobal &&
groupName != _prettyPrintDartAbbreviation &&
groupName.startsWith(_dartLibraryUriPrefix)) {
return true;
} else if (flutterGlobal &&
groupName != _prettyPrintFlutterAbbreviation &&
groupName.startsWith(_flutterLibraryUriPrefix)) {
return true;
}
return false;
});
}
Widget createLibraryListBox(BoxConstraints constraints) {
final allLibraries =
controller.filteredLibrariesByGroupName.keys.map((String key) {
return CheckboxListTile(
title: Text(key),
dense: true,
value: controller.filteredLibrariesByGroupName[key].first?.hide,
onChanged: (bool value) {
setState(() {
for (var filter in controller.filteredLibrariesByGroupName[key]) {
filter.hide = value;
}
});
},
);
}).toList();
// TODO(terry): Need to change all of this to use flex, not the below computation.
return SizedBox(
height: constraints.maxHeight / 4,
child: ListView(controller: _letters, children: allLibraries),
);
}
Widget applyAndCancelButton() {
return Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
DialogApplyButton(
onPressed: () {
// Re-generate librariesFiltered
controller.libraryFilters.clearFilters();
controller.filteredLibrariesByGroupName.forEach((groupName, value) {
if (value.first.hide) {
var filteredName = groupName;
if (filteredName.endsWith('*')) {
filteredName = filteredName.substring(
0,
filteredName.length - 1,
);
}
controller.libraryFilters.addFilter(filteredName);
}
});
// Re-filter the groups.
controller.libraryRoot = null;
if (controller.lastSnapshot != null) {
controller.heapGraph.computeFilteredGroups();
controller.computeAllLibraries(
graph: controller.lastSnapshot.snapshotGraph,
);
}
cleanupFilteredLibrariesByGroupName();
controller.updateFilter();
},
),
const SizedBox(width: defaultSpacing),
DialogCancelButton(
cancelAction: () {
controller.filterPrivateClasses.value =
oldFilterPrivateClassesValue;
controller.filterZeroInstances.value = oldFilterZeroInstancesValue;
controller.filterLibraryNoInstances.value =
oldFilterLibraryNoInstancesValue;
// Restore hide state.
controller.filteredLibrariesByGroupName.forEach((key, values) {
final oldHide = oldFilteredLibraries[key];
for (var value in values) {
value.hide = oldHide;
}
});
},
),
],
);
}
@override
Widget build(BuildContext context) {
// Dialog has three main vertical sections:
// - three checkboxes
// - one list of libraries with at least 5 entries
// - one row of buttons Ok/Cancel
// For very tall app keep the dialog at a reasonable height w/o too much vertical whitespace.
// The listbox area is the area that grows to accommodate the list of known libraries.
final constraints = BoxConstraints(
maxWidth: defaultDialogWidth,
maxHeight: MediaQuery.of(context).size.height,
);
final theme = Theme.of(context);
return DevToolsDialog(
title: dialogTitleText(theme, 'Memory Filter Libraries and Classes'),
includeDivider: false,
content: Container(
width: defaultDialogWidth,
child: Padding(
padding: const EdgeInsets.only(left: 15),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
...dialogSubHeader(theme, 'Snapshot Filters'),
Row(
children: [
NotifierCheckbox(
notifier: controller.filterPrivateClasses,
),
const DevToolsTooltip(
tooltip: 'Hide class names beginning with '
'an underscore e.g., _className',
child: Text('Hide Private Classes'),
),
],
),
Row(
children: [
NotifierCheckbox(
notifier: controller.filterZeroInstances,
),
const Text('Hide Classes with No Instances'),
],
),
Row(
children: [
NotifierCheckbox(
notifier: controller.filterLibraryNoInstances,
),
const Text('Hide Library with No Instances'),
],
),
const SizedBox(height: defaultSpacing),
...dialogSubHeader(
theme,
'Hide Libraries or Packages '
'(${controller.filteredLibrariesByGroupName.length})',
),
createLibraryListBox(constraints),
applyAndCancelButton(),
],
),
],
),
),
),
);
}
}
| devtools/packages/devtools_app/lib/src/memory/memory_filter.dart/0 | {'file_path': 'devtools/packages/devtools_app/lib/src/memory/memory_filter.dart', 'repo_id': 'devtools', 'token_count': 5385} |
// 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 'package:image/image.dart' as image;
import '../common_widgets.dart';
import '../http/http.dart';
import '../http/http_request_data.dart';
import '../table.dart';
import '../theme.dart';
import '../ui/colors.dart';
import '../utils.dart';
import 'network_model.dart';
// Approximately double the indent of the expandable tile's title.
const double _rowIndentPadding = 30;
// No padding between the last element and the divider of a expandable tile.
const double _rowSpacingPadding = 15;
const EdgeInsets _rowPadding =
EdgeInsets.only(left: _rowIndentPadding, bottom: _rowSpacingPadding);
/// Helper to build ExpansionTile widgets for inspector views.
ExpansionTile _buildTile(
String title,
List<Widget> children, {
Key key,
}) {
return ExpansionTile(
key: key,
title: Text(
title,
),
children: children,
initiallyExpanded: true,
);
}
/// This widget displays general HTTP request / response information that is
/// contained in the headers, in addition to the standard connection information.
class HttpRequestHeadersView extends StatelessWidget {
const HttpRequestHeadersView(this.data);
@visibleForTesting
static const generalKey = Key('General');
@visibleForTesting
static const requestHeadersKey = Key('Request Headers');
@visibleForTesting
static const responseHeadersKey = Key('Response Headers');
final HttpRequestData data;
Widget _buildRow(
BuildContext context,
String key,
dynamic value,
BoxConstraints constraints,
) {
return Container(
width: constraints.minWidth,
padding: _rowPadding,
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SelectableText(
'$key: ',
style: Theme.of(context).textTheme.subtitle2,
),
Expanded(
child: SelectableText(
value,
minLines: 1,
),
),
],
),
);
}
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) {
return ListView(
children: [
_buildTile(
'General',
[
for (final entry in data.general.entries)
_buildRow(
context,
// TODO(kenz): ensure the default case of `entry.key` looks
// fine.
entry.key,
entry.value.toString(),
constraints,
),
],
key: generalKey,
),
_buildTile(
'Response Headers',
[
if (data.responseHeaders != null)
for (final entry in data.responseHeaders.entries)
_buildRow(
context,
entry.key,
entry.value.toString(),
constraints,
),
],
key: responseHeadersKey,
),
_buildTile(
'Request Headers',
[
if (data.requestHeaders != null)
for (final entry in data.requestHeaders.entries)
_buildRow(
context,
entry.key,
entry.value.toString(),
constraints,
),
],
key: requestHeadersKey,
)
],
);
},
);
}
}
class HttpResponseView extends StatelessWidget {
const HttpResponseView(this.data);
final HttpRequestData data;
@override
Widget build(BuildContext context) {
Widget child;
// We shouldn't try and display an image response view when using the
// timeline profiler since it's possible for response body data to get
// dropped.
if (data is DartIOHttpRequestData && data.contentType.contains('image')) {
child = ImageResponseView(data);
} else {
child = FormattedJson(
formattedString: data.responseBody,
);
}
// TODO(kenz): use a collapsible json tree for the response
// https://github.com/flutter/devtools/issues/2952.
// TODO(bkonyi): add syntax highlighting to these responses
// https://github.com/flutter/devtools/issues/2604. We may be able to use
// the new tree widget used in the Provider page.
return Padding(
padding: const EdgeInsets.all(denseSpacing),
child: SingleChildScrollView(child: child),
);
}
}
class ImageResponseView extends StatelessWidget {
const ImageResponseView(this.data);
final DartIOHttpRequestData data;
@override
Widget build(BuildContext context) {
final img = image.decodeImage(data.encodedResponse);
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_buildTile(
'Image Preview',
[
Padding(
padding: const EdgeInsets.all(
denseSpacing,
),
child: Image.memory(
data.encodedResponse,
),
),
],
),
_buildTile(
'Metadata',
[
_buildRow(
context,
'Format',
data.type,
),
_buildRow(
context,
'Size',
prettyPrintBytes(
data.encodedResponse.lengthInBytes,
includeUnit: true,
),
),
_buildRow(
context,
'Dimensions',
'${img.width} x ${img.height}',
),
],
),
],
);
}
Widget _buildRow(
BuildContext context,
String key,
String value,
) {
return Padding(
padding: _rowPadding,
child: Row(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SelectableText(
'$key: ',
style: Theme.of(context).textTheme.subtitle2,
),
Expanded(
child: SelectableText(
value,
// TODO(kenz): use top level overflow parameter if
// https://github.com/flutter/flutter/issues/82722 is fixed.
// TODO(kenz): add overflow after flutter 2.3.0 is stable. It was
// added in commit 65388ee2eeaf0d2cf087eaa4a325e3689020c46a.
// style: const TextStyle(overflow: TextOverflow.ellipsis),
),
),
],
),
);
}
}
/// A [Widget] which displays [Cookie] information in a tab.
class HttpRequestCookiesView extends StatelessWidget {
const HttpRequestCookiesView(this.data);
@visibleForTesting
static const requestCookiesKey = Key('Request Cookies');
@visibleForTesting
static const responseCookiesKey = Key('Response Cookies');
final HttpRequestData data;
DataRow _buildRow(int index, Cookie cookie, {bool requestCookies = false}) {
return DataRow.byIndex(
index: index,
// NOTE: if this list of cells change, the columns of the DataTable
// below will need to be updated.
cells: [
_buildCell(cookie.name),
_buildCell(cookie.value),
if (!requestCookies) ...[
_buildCell(cookie.domain),
_buildCell(cookie.path),
_buildCell(cookie.expires?.toString()),
_buildCell(cookie.value.length.toString()),
_buildIconCell(!cookie.httpOnly ? Icons.check : Icons.close),
_buildIconCell(!cookie.secure ? Icons.check : Icons.close),
],
],
);
}
DataCell _buildCell(String value) => DataCell(SelectableText(value ?? '--'));
DataCell _buildIconCell(IconData icon) =>
DataCell(Icon(icon, size: defaultIconSize));
Widget _buildCookiesTable(
BuildContext context,
String title,
List<Cookie> cookies,
BoxConstraints constraints,
Key key, {
bool requestCookies = false,
}) {
final theme = Theme.of(context);
DataColumn _buildColumn(
String title, {
bool numeric = false,
}) {
return DataColumn(
label: Expanded(
child: SelectableText(
title ?? '--',
// TODO(kenz): use top level overflow parameter if
// https://github.com/flutter/flutter/issues/82722 is fixed.
// TODO(kenz): add overflow after flutter 2.3.0 is stable. It was
// added in commit 65388ee2eeaf0d2cf087eaa4a325e3689020c46a.
// style: theme.textTheme.subtitle1.copyWith(
// overflow: TextOverflow.fade,
// ),
style: theme.textTheme.subtitle1,
),
),
numeric: numeric,
);
}
return _buildTile(
title,
[
// Add a divider between the tile's title and the cookie table headers for
// symmetry.
const Divider(
// Remove extra padding at the top of the divider; the tile's title
// already has bottom padding.
height: 0,
),
Align(
alignment: Alignment.centerLeft,
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: ConstrainedBox(
constraints: requestCookies
? const BoxConstraints()
: BoxConstraints(
minWidth: constraints.minWidth,
),
child: DataTable(
key: key,
dataRowHeight: defaultRowHeight,
// NOTE: if this list of columns change, _buildRow will need
// to be updated to match.
columns: [
_buildColumn('Name'),
_buildColumn('Value'),
if (!requestCookies) ...[
_buildColumn('Domain'),
_buildColumn('Path'),
_buildColumn('Expires / Max Age'),
_buildColumn('Size', numeric: true),
_buildColumn('HttpOnly'),
_buildColumn('Secure'),
]
],
rows: [
for (int i = 0; i < cookies.length; ++i)
_buildRow(
i,
cookies[i],
requestCookies: requestCookies,
),
],
),
),
),
),
],
);
}
@override
Widget build(BuildContext context) {
final requestCookies = data.requestCookies;
final responseCookies = data.responseCookies;
return LayoutBuilder(
builder: (context, constraints) {
return ListView(
children: [
if (responseCookies.isNotEmpty)
_buildCookiesTable(
context,
'Response Cookies',
responseCookies,
constraints,
responseCookiesKey,
),
// Add padding between the cookie tables if displaying both
// response and request cookies.
if (responseCookies.isNotEmpty && requestCookies.isNotEmpty)
const Padding(
padding: EdgeInsets.only(bottom: 24.0),
),
if (requestCookies.isNotEmpty)
_buildCookiesTable(
context,
'Request Cookies',
requestCookies,
constraints,
requestCookiesKey,
requestCookies: true,
),
],
);
},
);
}
}
class NetworkRequestOverviewView extends StatelessWidget {
const NetworkRequestOverviewView(this.data);
static const _keyWidth = 110.0;
static const _timingGraphHeight = 18.0;
@visibleForTesting
static const httpTimingGraphKey = Key('Http Timing Graph Key');
@visibleForTesting
static const socketTimingGraphKey = Key('Socket Timing Graph Key');
final NetworkRequest data;
@override
Widget build(BuildContext context) {
return ListView(
padding: const EdgeInsets.all(defaultSpacing),
children: [
..._buildGeneralRows(context),
if (data is WebSocket) ..._buildSocketOverviewRows(context),
const PaddedDivider(
padding: EdgeInsets.only(bottom: denseRowSpacing),
),
..._buildTimingOverview(context),
],
);
}
List<Widget> _buildGeneralRows(BuildContext context) {
return [
// TODO(kenz): show preview for requests (png, response body, proto)
_buildRow(
context: context,
title: 'Request uri',
child: _valueText(data.uri),
),
const SizedBox(height: defaultSpacing),
_buildRow(
context: context,
title: 'Method',
child: _valueText(data.method),
),
const SizedBox(height: defaultSpacing),
_buildRow(
context: context,
title: 'Status',
child: _valueText(data.status ?? '--'),
),
const SizedBox(height: defaultSpacing),
if (data.port != null) ...[
_buildRow(
context: context,
title: 'Port',
child: _valueText('${data.port}'),
),
const SizedBox(height: defaultSpacing),
],
if (data.contentType != null) ...[
_buildRow(
context: context,
title: 'Content type',
child: _valueText(data.contentType ?? 'null'),
),
const SizedBox(height: defaultSpacing),
],
];
}
List<Widget> _buildTimingOverview(BuildContext context) {
return [
_buildRow(
context: context,
title: 'Timing',
child: data is WebSocket
? _buildSocketTimeGraph(context)
: _buildHttpTimeGraph(context),
),
const SizedBox(height: denseSpacing),
_buildRow(
context: context,
title: null,
child: _valueText(data.durationDisplay),
),
const SizedBox(height: defaultSpacing),
...data is WebSocket
? _buildSocketTimingRows(context)
: _buildHttpTimingRows(context),
const SizedBox(height: defaultSpacing),
_buildRow(
context: context,
title: 'Start time',
child: _valueText(formatDateTime(data.startTimestamp)),
),
const SizedBox(height: defaultSpacing),
_buildRow(
context: context,
title: 'End time',
child: _valueText(data.endTimestamp != null
? formatDateTime(data.endTimestamp)
: 'Pending'),
),
];
}
Widget _buildTimingRow(
Color color,
String label,
Duration duration,
) {
final flex =
(duration.inMicroseconds / data.duration.inMicroseconds * 100).round();
return Flexible(
flex: flex,
child: Tooltip(
waitDuration: tooltipWait,
message: '$label - ${msText(duration)}',
child: Container(
height: _timingGraphHeight,
color: color,
),
),
);
}
Widget _buildHttpTimeGraph(BuildContext context) {
final data = this.data as HttpRequestData;
if (data.duration == null || data.instantEvents.isEmpty) {
return Container(
key: httpTimingGraphKey,
height: 18.0,
color: mainRasterColor,
);
}
const _colors = [
searchMatchColor,
mainRasterColor,
mainAsyncColor,
];
var _colorIndex = 0;
Color _nextColor() {
final color = _colors[_colorIndex % _colors.length];
_colorIndex++;
return color;
}
// TODO(kenz): consider calculating these sizes by hand instead of using
// flex so that we can set a minimum width for small timing chunks.
final timingWidgets = <Widget>[];
for (final instant in data.instantEvents) {
final duration = instant.timeRange.duration;
timingWidgets.add(
_buildTimingRow(_nextColor(), instant.name, duration),
);
}
final duration = Duration(
microseconds: data.endTimestamp.microsecondsSinceEpoch -
data.instantEvents.last.timestampMicros -
data.timelineMicrosecondsSinceEpoch(0),
);
timingWidgets.add(
_buildTimingRow(_nextColor(), 'Response', duration),
);
return Row(
key: httpTimingGraphKey,
children: timingWidgets,
);
}
// TODO(kenz): add a "waterfall" like visualization with the same colors that
// are used in the timing graph.
List<Widget> _buildHttpTimingRows(BuildContext context) {
final data = this.data as HttpRequestData;
return [
for (final instant in data.instantEvents) ...[
_buildRow(
context: context,
title: instant.name,
child: _valueText(
'[${msText(instant.timeRange.start - data.instantEvents.first.timeRange.start)} - '
'${msText(instant.timeRange.end - data.instantEvents.first.timeRange.start)}]'
' → ${msText(instant.timeRange.duration)} total'),
),
if (instant != data.instantEvents.last)
const SizedBox(height: defaultSpacing),
]
];
}
List<Widget> _buildSocketOverviewRows(BuildContext context) {
final socket = data as WebSocket;
return [
_buildRow(
context: context,
title: 'Socket id',
child: _valueText('${socket.id}'),
),
const SizedBox(height: defaultSpacing),
_buildRow(
context: context,
title: 'Socket type',
child: _valueText(socket.socketType),
),
const SizedBox(height: defaultSpacing),
_buildRow(
context: context,
title: 'Read bytes',
child: _valueText('${socket.readBytes}'),
),
const SizedBox(height: defaultSpacing),
_buildRow(
context: context,
title: 'Write bytes',
child: _valueText('${socket.writeBytes}'),
),
const SizedBox(height: defaultSpacing),
];
}
Widget _buildSocketTimeGraph(BuildContext context) {
return Container(
key: socketTimingGraphKey,
height: _timingGraphHeight,
color: mainUiColor,
);
}
List<Widget> _buildSocketTimingRows(BuildContext context) {
final data = this.data as WebSocket;
return [
_buildRow(
context: context,
title: 'Last read time',
child: data.lastReadTimestamp != null
? _valueText(formatDateTime(data.lastReadTimestamp))
: '--',
),
const SizedBox(height: defaultSpacing),
_buildRow(
context: context,
title: 'Last write time',
child: _valueText(formatDateTime(data.lastWriteTimestamp)),
),
];
}
Widget _buildRow({
@required BuildContext context,
@required String title,
@required Widget child,
}) {
return Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
width: _keyWidth,
child: SelectableText(
title != null ? '$title: ' : '',
style: Theme.of(context).textTheme.subtitle2,
),
),
Expanded(
child: child,
),
],
);
}
Widget _valueText(String value) {
return SelectableText(
value,
minLines: 1,
);
}
}
| devtools/packages/devtools_app/lib/src/network/network_request_inspector_views.dart/0 | {'file_path': 'devtools/packages/devtools_app/lib/src/network/network_request_inspector_views.dart', 'repo_id': 'devtools', 'token_count': 9111} |
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math' as math;
import 'package:flutter/foundation.dart';
import 'package:meta/meta.dart';
import '../utils.dart';
import 'cpu_profile_model.dart';
/// Process for composing [CpuProfileData] into a structured tree of
/// [CpuStackFrame]'s.
class CpuProfileTransformer {
/// Number of stack frames we will process in each batch.
static const _defaultBatchSize = 100;
/// Notifies with the current progress value of transforming CPU profile data.
///
/// This value should sit between 0.0 and 1.0.
ValueListenable get progressNotifier => _progressNotifier;
final _progressNotifier = ValueNotifier<double>(0.0);
int _stackFramesCount;
List<dynamic> _stackFrameKeys;
List<dynamic> _stackFrameValues;
int _stackFramesProcessed = 0;
String _activeProcessId;
Future<void> processData(
CpuProfileData cpuProfileData, {
String processId,
}) async {
// Do not process this data if it has already been processed.
if (cpuProfileData.processed) return;
// Reset the transformer before processing.
reset();
_activeProcessId = processId;
_stackFramesCount = cpuProfileData?.stackFramesJson?.length ?? 0;
_stackFrameKeys = cpuProfileData?.stackFramesJson?.keys?.toList() ?? [];
_stackFrameValues = cpuProfileData?.stackFramesJson?.values?.toList() ?? [];
// Initialize all stack frames before we start to for the tree.
for (int i = 0; i < _stackFramesCount; i++) {
if (processId != _activeProcessId) {
throw ProcessCancelledException();
}
final k = _stackFrameKeys[i];
final v = _stackFrameValues[i];
final stackFrame = CpuStackFrame(
id: k,
name: getSimpleStackFrameName(v[CpuProfileData.nameKey]),
category: v[CpuProfileData.categoryKey],
// If the user is on a version of Flutter where resolvedUrl is not
// included in the response, this will be null. If the frame is a native
// frame, the this will be the empty string.
url: v[CpuProfileData.resolvedUrlKey] ?? '',
profileMetaData: cpuProfileData.profileMetaData,
);
cpuProfileData.stackFrames[stackFrame.id] = stackFrame;
}
// At minimum, process the data in 4 batches to smooth the appearance of
// the progress indicator.
final quarterBatchSize = (_stackFramesCount / 4).round();
final batchSize = math.min(
_defaultBatchSize,
quarterBatchSize == 0 ? 1 : quarterBatchSize,
);
// Use batch processing to maintain a responsive UI.
while (_stackFramesProcessed < _stackFramesCount) {
_processBatch(batchSize, cpuProfileData, processId);
_progressNotifier.value = _stackFramesProcessed / _stackFramesCount;
// Await a small delay to give the UI thread a chance to update the
// progress indicator. Use a longer delay than the default (0) so that the
// progress indicator will look smoother.
await delayForBatchProcessing(micros: 5000);
if (processId != _activeProcessId) {
throw ProcessCancelledException();
}
}
_setExclusiveSampleCountsAndTags(cpuProfileData);
cpuProfileData.processed = true;
// TODO(kenz): investigate why this assert is firing again.
// https://github.com/flutter/devtools/issues/1529.
// assert(
// cpuProfileData.profileMetaData.sampleCount ==
// cpuProfileData.cpuProfileRoot.inclusiveSampleCount,
// 'SampleCount from response (${cpuProfileData.profileMetaData.sampleCount})'
// ' != sample count from root '
// '(${cpuProfileData.cpuProfileRoot.inclusiveSampleCount})',
// );
// Reset the transformer after processing.
reset();
}
void _processBatch(
int batchSize,
CpuProfileData cpuProfileData,
String processId,
) {
final batchEnd =
math.min(_stackFramesProcessed + batchSize, _stackFramesCount);
for (int i = _stackFramesProcessed; i < batchEnd; i++) {
if (processId != _activeProcessId) {
throw ProcessCancelledException();
}
final key = _stackFrameKeys[i];
final value = _stackFrameValues[i];
final stackFrame = cpuProfileData.stackFrames[key];
final parent =
cpuProfileData.stackFrames[value[CpuProfileData.parentIdKey]];
_processStackFrame(stackFrame, parent, cpuProfileData);
_stackFramesProcessed++;
}
}
void _processStackFrame(
CpuStackFrame stackFrame,
CpuStackFrame parent,
CpuProfileData cpuProfileData,
) {
if (parent == null) {
// [stackFrame] is the root of a new cpu sample. Add it as a child of
// [cpuProfile].
cpuProfileData.cpuProfileRoot.addChild(stackFrame);
} else {
parent.addChild(stackFrame);
}
}
void _setExclusiveSampleCountsAndTags(CpuProfileData cpuProfileData) {
for (Map<String, dynamic> traceEvent in cpuProfileData.stackTraceEvents) {
final leafId = traceEvent[CpuProfileData.stackFrameIdKey];
assert(
cpuProfileData.stackFrames[leafId] != null,
'No StackFrame found for id $leafId. If you see this assertion, please '
'export the timeline trace and send to kenzieschmoll@google.com. Note: '
'you must export the timeline immediately after the AssertionError is '
'thrown.',
);
final stackFrame = cpuProfileData.stackFrames[leafId];
stackFrame?.exclusiveSampleCount++;
final userTag = (traceEvent['args'] ?? {})['userTag'];
if (userTag != null) {
stackFrame.incrementTagSampleCount(userTag);
}
}
}
void reset() {
_activeProcessId = null;
_stackFramesProcessed = 0;
_stackFrameKeys = null;
_stackFrameValues = null;
_progressNotifier.value = 0.0;
}
void dispose() {
_progressNotifier.dispose();
}
}
/// Process for converting a [CpuStackFrame] into a bottom-up representation of
/// the CPU profile.
class BottomUpProfileTransformer {
static List<CpuStackFrame> processData(CpuStackFrame stackFrame) {
final List<CpuStackFrame> bottomUpRoots = getRoots(stackFrame, null, []);
// Set the bottom up sample counts for each sample.
bottomUpRoots.forEach(cascadeSampleCounts);
// Merge samples when possible starting at the root (the leaf node of the
// original CPU sample).
mergeProfileRoots(bottomUpRoots);
return bottomUpRoots;
}
/// Returns the roots for a bottom up representation of a CpuStackFrame node.
///
/// Each root is a leaf from the original CpuStackFrame tree, and its children
/// will be the reverse call stack of the original sample. The stack frames
/// returned will not be merged to combine common roots, and the sample counts
/// will not reflect the bottom up sample counts. These steps will occur later
/// in the bottom-up conversion process.
@visibleForTesting
static List<CpuStackFrame> getRoots(
CpuStackFrame node,
CpuStackFrame currentBottomUpRoot,
List<CpuStackFrame> bottomUpRoots,
) {
final copy = node.shallowCopy(resetInclusiveSampleCount: true);
if (currentBottomUpRoot != null) {
copy.addChild(currentBottomUpRoot.deepCopy());
}
// [copy] is the new root of the bottom up call stack.
currentBottomUpRoot = copy;
if (node.exclusiveSampleCount > 0) {
// This node is a leaf node, meaning it is a bottom up root.
bottomUpRoots.add(currentBottomUpRoot);
}
for (CpuStackFrame child in node.children) {
getRoots(child, currentBottomUpRoot, bottomUpRoots);
}
return bottomUpRoots;
}
/// Sets sample counts of [stackFrame] and all children to
/// [exclusiveSampleCount].
///
/// This is necessary for the transformation of a [CpuStackFrame] to its
/// bottom-up representation. This is an intermediate step between
/// [getRoots] and [mergeProfileRoots].
@visibleForTesting
static void cascadeSampleCounts(CpuStackFrame stackFrame) {
stackFrame.inclusiveSampleCount = stackFrame.exclusiveSampleCount;
for (CpuStackFrame child in stackFrame.children) {
child.exclusiveSampleCount = stackFrame.exclusiveSampleCount;
cascadeSampleCounts(child);
}
}
}
/// Merges CPU profile roots that share a common call stack (starting at the
/// root).
///
/// Ex. C C C
/// -> B -> B --> -> B
/// -> A -> D -> A
/// -> D
///
/// At the time this method is called, we assume we have a list of roots with
/// accurate inclusive/exclusive sample counts.
void mergeProfileRoots(List<CpuStackFrame> roots) {
// Loop through a copy of [roots] so that we can remove nodes from [roots]
// once we have merged them.
final List<CpuStackFrame> rootsCopy = List.from(roots);
for (CpuStackFrame root in rootsCopy) {
if (!roots.contains(root)) {
// We have already merged [root] and removed it from [roots]. Do not
// attempt to merge again.
continue;
}
final matchingRoots =
roots.where((other) => other.matches(root) && other != root).toList();
if (matchingRoots.isEmpty) {
continue;
}
for (CpuStackFrame match in matchingRoots) {
match.children.forEach(root.addChild);
root.exclusiveSampleCount += match.exclusiveSampleCount;
root.inclusiveSampleCount += match.inclusiveSampleCount;
roots.remove(match);
mergeProfileRoots(root.children);
}
}
for (CpuStackFrame root in roots) {
root.index = roots.indexOf(root);
}
}
/// Exception thrown when a request to process data has been cancelled in
/// favor of a new request.
class ProcessCancelledException implements Exception {}
| devtools/packages/devtools_app/lib/src/profiler/cpu_profile_transformer.dart/0 | {'file_path': 'devtools/packages/devtools_app/lib/src/profiler/cpu_profile_transformer.dart', 'repo_id': 'devtools', 'token_count': 3427} |
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:provider/provider.dart' as provider show Provider;
import '../banner_messages.dart';
import '../common_widgets.dart';
import '../dialogs.dart';
import '../screen.dart';
import '../split.dart';
import 'instance_viewer/instance_details.dart';
import 'instance_viewer/instance_providers.dart';
import 'instance_viewer/instance_viewer.dart';
import 'provider_list.dart';
import 'provider_nodes.dart';
final _hasErrorProvider = Provider.autoDispose<bool>((ref) {
if (ref.watch(sortedProviderNodesProvider) is AsyncError) return true;
final selectedProviderId = ref.watch(selectedProviderIdProvider);
if (selectedProviderId == null) return false;
final instance = ref.watch(
rawInstanceProvider(InstancePath.fromProviderId(selectedProviderId)),
);
return instance is AsyncError;
});
final _selectedProviderNode = AutoDisposeProvider<ProviderNode>((ref) {
final selectedId = ref.watch(selectedProviderIdProvider);
return ref.watch(sortedProviderNodesProvider).data?.value?.firstWhere(
(node) => node.id == selectedId,
orElse: () => null,
);
});
final _showInternals = StateProvider<bool>((ref) => false);
class ProviderScreen extends Screen {
const ProviderScreen()
: super.conditional(
id: id,
requiresLibrary: 'package:provider/',
title: 'Provider',
requiresDebugBuild: true,
icon: Icons.attach_file,
);
static const id = 'provider';
@override
Widget build(BuildContext context) {
return const ProviderScreenBody();
}
}
class ProviderScreenBody extends ConsumerWidget {
const ProviderScreenBody({Key key}) : super(key: key);
@override
Widget build(BuildContext context, ScopedReader watch) {
final splitAxis = Split.axisFor(context, 0.85);
// A provider will automatically be selected as soon as one is detected
final selectedProviderId = watch(selectedProviderIdProvider);
final detailsTitleText = selectedProviderId != null
? watch(_selectedProviderNode)?.type ?? ''
: '[No provider selected]';
return ProviderListener<bool>(
provider: _hasErrorProvider,
onChange: (context, hasError) {
if (hasError) showProviderErrorBanner(context);
},
child: Split(
axis: splitAxis,
initialFractions: const [0.33, 0.67],
children: [
OutlineDecoration(
child: Column(
children: const [
AreaPaneHeader(
needsTopBorder: false,
title: Text('Providers'),
),
Expanded(
child: ProviderList(),
),
],
),
),
OutlineDecoration(
child: Column(
children: [
AreaPaneHeader(
needsTopBorder: false,
title: Text(detailsTitleText),
actions: [
SettingsOutlinedButton(
onPressed: () {
showDialog(
context: context,
builder: (_) => _StateInspectorSettingsDialog(),
);
},
label: _StateInspectorSettingsDialog.title,
),
],
),
if (selectedProviderId != null)
Expanded(
child: InstanceViewer(
rootPath: InstancePath.fromProviderId(selectedProviderId),
showInternalProperties: watch(_showInternals).state,
),
)
],
),
)
],
),
);
}
}
void showProviderErrorBanner(BuildContext context) {
provider.Provider.of<BannerMessagesController>(
context,
listen: false,
).addMessage(
const ProviderUnknownErrorBanner(screenId: ProviderScreen.id)
.build(context),
);
}
class _StateInspectorSettingsDialog extends ConsumerWidget {
static const title = 'State inspector configurations';
@override
Widget build(BuildContext context, ScopedReader watch) {
final theme = Theme.of(context);
return DevToolsDialog(
title: dialogTitleText(theme, title),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
InkWell(
onTap: () => _toggleShowInternals(context),
child: Row(
children: [
Checkbox(
value: watch(_showInternals).state,
onChanged: (_) => _toggleShowInternals(context),
),
const Text(
'Show private properties inherited from SDKs/packages',
),
],
),
)
],
),
actions: [
DialogCloseButton(),
],
);
}
void _toggleShowInternals(BuildContext context) {
final showInternals = context.read(_showInternals);
showInternals.state = !showInternals.state;
}
}
| devtools/packages/devtools_app/lib/src/provider/provider_screen.dart/0 | {'file_path': 'devtools/packages/devtools_app/lib/src/provider/provider_screen.dart', 'repo_id': 'devtools', 'token_count': 2405} |
// 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';
//Future<String> loadPolyfillScript() {
// return asset.loadString('assets/scripts/inspector_polyfill_script.dart');
//}
// https://macromates.com/manual/en/language_grammars
void main() {
final String source = File('assets/syntax/dart.json').readAsStringSync();
final TextmateGrammar dartGrammar = TextmateGrammar(source);
print(dartGrammar);
}
// todo: test basic parsing
class TextmateGrammar {
TextmateGrammar(String syntaxDefinition) {
_definition = jsonDecode(syntaxDefinition);
_parseFileRules();
_parseRules();
}
final List<Rule> _fileRules = [];
final Map<String, Rule> _ruleMap = {};
Map _definition;
/// The name of the grammar.
String get name => _definition['name'];
/// The file type extensions that the grammar should be used with.
List<String> get fileTypes =>
(_definition['fileTypes'] as List).cast<String>();
/// A unique name for the grammar.
String get scopeName => _definition['scopeName'];
void _parseRules() {
final Map repository = _definition['repository'];
for (String name in repository.keys) {
_ruleMap[name] = Rule(name);
}
for (String name in _ruleMap.keys) {
_ruleMap[name]._parse(repository[name]);
}
print('rules: ${_ruleMap.keys.toList()}');
}
void _parseFileRules() {
final List<dynamic> patterns = _definition['patterns'];
for (Map info in patterns) {
_fileRules.add(Rule(info['name']).._parse(info));
}
print('fileRules: $_fileRules');
}
@override
String toString() => '$name: $fileTypes';
}
// todo: make abstract
// todo: have a forwarding rule
// todo: have a match rule, and a begin / end rule
class Rule {
Rule(this.name);
final String name;
void _parse(Map info) {
// todo:
}
@override
String toString() => '$name';
}
| devtools/packages/devtools_app/lib/src/syntax_highlighting.dart/0 | {'file_path': 'devtools/packages/devtools_app/lib/src/syntax_highlighting.dart', 'repo_id': 'devtools', 'token_count': 698} |
/*
* 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/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import '../auto_dispose_mixin.dart';
/// Stateful Checkbox Widget class using a [ValueNotifier].
///
/// Used to create a Checkbox widget who's boolean value is attached
/// to a [ValueNotifier<bool>]. This allows for the pattern:
///
/// Create the [NotifierCheckbox] widget in build e.g.,
///
/// myCheckboxWidget = NotifierCheckbox(notifier: controller.myCheckbox);
///
/// The checkbox and the value notifier are now linked with clicks updating the
/// [ValueNotifier] and changes to the [ValueNotifier] updating the checkbox.
class NotifierCheckbox extends StatefulWidget {
const NotifierCheckbox({
Key key,
@required this.notifier,
}) : super(key: key);
final ValueNotifier<bool> notifier;
@override
_NotifierCheckboxState createState() => _NotifierCheckboxState();
}
class _NotifierCheckboxState extends State<NotifierCheckbox>
with AutoDisposeMixin {
bool currentValue;
@override
void initState() {
super.initState();
_trackValue();
}
@override
void didUpdateWidget(NotifierCheckbox oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.notifier == widget.notifier) return;
cancel();
_trackValue();
}
void _trackValue() {
_updateValue();
addAutoDisposeListener(widget.notifier, _updateValue);
}
void _updateValue() {
if (currentValue == widget.notifier.value) return;
setState(() {
currentValue = widget.notifier.value;
});
}
@override
Widget build(BuildContext context) {
return Checkbox(
value: currentValue,
onChanged: (value) {
widget.notifier.value = value;
},
);
}
}
/// Returns a [TextSpan] that only includes the first [length] characters of
/// [span].
TextSpan truncateTextSpan(TextSpan span, int length) {
int available = length;
TextSpan truncateHelper(TextSpan span) {
var text = span.text;
List<TextSpan> children;
if (text != null) {
if (text.length > available) {
text = text.substring(0, available);
}
available -= text.length;
}
if (span.children != null) {
children = <TextSpan>[];
for (var child in span.children) {
if (available <= 0) break;
children.add(truncateHelper(child));
}
if (children.isEmpty) {
children = null;
}
}
return TextSpan(
text: text,
children: children,
style: span.style,
recognizer: span.recognizer,
semanticsLabel: span.semanticsLabel,
);
}
return truncateHelper(span);
}
/// Scrollbar that is offset by the amount specified by an [offsetController].
///
/// This makes it possible to create a [ListView] with both vertical and
/// horizontal scrollbars by wrapping the [ListView] in a
/// [SingleChildScrollView] that handles horizontal scrolling. The
/// [offsetController] is the offset of the parent [SingleChildScrollView] in
/// this example.
///
/// This class could be optimized if performance was a concern using a
/// [CustomPainter] instead of an [AnimatedBuilder] so that the
/// [OffsetScrollbar] widget does not need to build on each change to the
/// [offsetController].
class OffsetScrollbar extends StatefulWidget {
const OffsetScrollbar({
Key key,
this.isAlwaysShown = false,
@required this.axis,
@required this.controller,
@required this.offsetController,
@required this.child,
@required this.offsetControllerViewportDimension,
}) : super(key: key);
final bool isAlwaysShown;
final Axis axis;
final ScrollController controller;
final ScrollController offsetController;
final Widget child;
/// The current viewport dimension of the offsetController may not be
/// available at build time as it is not updated until later so we require
/// that the known correct viewport dimension is passed into this class.
///
/// This is a workaround because we use an AnimatedBuilder to listen for
/// changes to the offsetController rather than displaying the scrollbar at
/// paint time which would be more difficult.
final double offsetControllerViewportDimension;
@override
_OffsetScrollbarState createState() => _OffsetScrollbarState();
}
class _OffsetScrollbarState extends State<OffsetScrollbar> {
@override
Widget build(BuildContext context) {
if (!widget.offsetController.position.hasContentDimensions) {
SchedulerBinding.instance.addPostFrameCallback((timeStamp) {
if (widget.offsetController.position.hasViewportDimension && mounted) {
// TODO(jacobr): find a cleaner way to be notified that the
// offsetController now has a valid dimension. We would probably
// have to implement our own ScrollbarPainter instead of being able
// to use the existing Scrollbar widget.
setState(() {});
}
});
}
return AnimatedBuilder(
animation: widget.offsetController,
builder: (context, child) {
// Compute a delta to move the scrollbar from where it is by default to
// where it should be given the viewport dimension of the
// offsetController not the viewport that is the entire scroll extent
// of the offsetController because this controller is nested within the
// offset controller.
double delta = 0.0;
if (widget.offsetController.position.hasContentDimensions) {
delta = widget.offsetController.offset -
widget.offsetController.position.maxScrollExtent +
widget.offsetController.position.minScrollExtent;
if (widget.offsetController.position.hasViewportDimension) {
// TODO(jacobr): this is a bit of a hack.
// The viewport dimension from the offsetController may be one frame
// behind the true viewport dimension. We add this delta so the
// scrollbar always appears stuck to the side of the viewport.
delta += widget.offsetControllerViewportDimension -
widget.offsetController.position.viewportDimension;
}
}
final offset = widget.axis == Axis.vertical
? Offset(delta, 0.0)
: Offset(0.0, delta);
return Transform.translate(
offset: offset,
child: Scrollbar(
isAlwaysShown: widget.isAlwaysShown,
controller: widget.controller,
child: Transform.translate(
offset: -offset,
child: child,
),
),
);
},
child: widget.child,
);
}
}
| devtools/packages/devtools_app/lib/src/ui/utils.dart/0 | {'file_path': 'devtools/packages/devtools_app/lib/src/ui/utils.dart', 'repo_id': 'devtools', 'token_count': 2366} |
// 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/debugger/debugger_controller.dart';
import 'package:devtools_app/src/debugger/debugger_model.dart';
import 'package:devtools_app/src/globals.dart';
import 'package:devtools_app/src/service_manager.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meta/meta.dart';
import 'package:mockito/mockito.dart';
import 'package:vm_service/vm_service.dart';
import 'support/mocks.dart';
final libraryRef = LibraryRef(
name: 'some library',
uri: 'package:foo/foo.dart',
id: 'lib-id-1',
);
void main() {
ServiceConnectionManager manager;
DebuggerController debuggerController;
setUp(() {
final service = MockVmService();
when(service.onDebugEvent).thenAnswer((_) {
return const Stream.empty();
});
when(service.onVMEvent).thenAnswer((_) {
return const Stream.empty();
});
when(service.onIsolateEvent).thenAnswer((_) {
return const Stream.empty();
});
when(service.onStdoutEvent).thenAnswer((_) {
return const Stream.empty();
});
when(service.onStderrEvent).thenAnswer((_) {
return const Stream.empty();
});
manager = FakeServiceManager(service: service);
setGlobal(ServiceConnectionManager, manager);
debuggerController = DebuggerController(initialSwitchToIsolate: false)
..isolateRef = IsolateRef(
id: '1',
number: '2',
name: 'main',
isSystemIsolate: false,
);
});
test('Creates bound variables for Map with String key and Double value',
() async {
final instance = Instance(
kind: InstanceKind.kMap,
id: '123',
classRef: null,
associations: [
MapAssociation(
key: InstanceRef(
classRef: null,
id: '4',
kind: InstanceKind.kString,
valueAsString: 'Hey',
identityHashCode: null,
),
value: InstanceRef(
classRef: null,
id: '5',
kind: InstanceKind.kDouble,
valueAsString: '12.34',
identityHashCode: null,
),
),
],
identityHashCode: null,
);
final variable = Variable.create(BoundVariable(
name: 'test',
value: instance,
declarationTokenPos: null,
scopeEndTokenPos: null,
scopeStartTokenPos: null,
));
when(manager.service.getObject(any, any)).thenAnswer((_) async {
return instance;
});
await debuggerController.buildVariablesTree(variable);
expect(variable.children, [
matchesVariable(name: '[Entry 0]', value: ''),
]);
expect(variable.children.first.children, [
matchesVariable(name: '[key]', value: '\'Hey\''),
matchesVariable(name: '[value]', value: '12.34'),
]);
});
test('Creates bound variables for Map with Int key and Double value',
() async {
final instance = Instance(
kind: InstanceKind.kMap,
id: '123',
classRef: null,
associations: [
MapAssociation(
key: InstanceRef(
classRef: null,
id: '4',
kind: InstanceKind.kInt,
valueAsString: '1',
identityHashCode: null,
),
value: InstanceRef(
classRef: null,
id: '5',
kind: InstanceKind.kDouble,
valueAsString: '12.34',
identityHashCode: null,
),
),
],
identityHashCode: null,
);
final variable = Variable.create(BoundVariable(
name: 'test',
value: instance,
declarationTokenPos: null,
scopeEndTokenPos: null,
scopeStartTokenPos: null,
));
when(manager.service.getObject(any, any)).thenAnswer((_) async {
return instance;
});
await debuggerController.buildVariablesTree(variable);
expect(variable.children, [
matchesVariable(name: '[Entry 0]', value: ''),
]);
expect(variable.children.first.children, [
matchesVariable(name: '[key]', value: '1'),
matchesVariable(name: '[value]', value: '12.34'),
]);
});
test('Creates bound variables for Map with Object key and Double value',
() async {
final instance = Instance(
kind: InstanceKind.kMap,
id: '123',
classRef: null,
associations: [
MapAssociation(
key: InstanceRef(
classRef: ClassRef(id: 'a', name: 'Foo', library: libraryRef),
id: '4',
kind: InstanceKind.kPlainInstance,
identityHashCode: null,
),
value: InstanceRef(
classRef: null,
id: '5',
kind: InstanceKind.kDouble,
valueAsString: '12.34',
identityHashCode: null,
),
),
],
identityHashCode: null,
);
final variable = Variable.create(BoundVariable(
name: 'test',
value: instance,
declarationTokenPos: null,
scopeEndTokenPos: null,
scopeStartTokenPos: null,
));
when(manager.service.getObject(any, any)).thenAnswer((_) async {
return instance;
});
await debuggerController.buildVariablesTree(variable);
expect(variable.children, [
matchesVariable(name: '[Entry 0]', value: ''),
]);
expect(variable.children.first.children, [
matchesVariable(name: '[key]', value: 'Foo'),
matchesVariable(name: '[value]', value: '12.34'),
]);
});
}
Matcher matchesVariable({
@required String name,
@required Object value,
}) {
return const TypeMatcher<Variable>()
.having(
(v) => v.displayValue,
'displayValue',
equals(value),
)
.having(
(v) => v.boundVar,
'boundVar',
const TypeMatcher<BoundVariable>()
.having((bv) => bv.name, 'name', equals(name)));
}
| devtools/packages/devtools_app/test/association_variable_test.dart/0 | {'file_path': 'devtools/packages/devtools_app/test/association_variable_test.dart', 'repo_id': 'devtools', 'token_count': 2588} |
// 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:ansicolor/ansicolor.dart';
import 'package:devtools_app/src/common_widgets.dart';
import 'package:devtools_app/src/debugger/console.dart';
import 'package:devtools_app/src/debugger/controls.dart';
import 'package:devtools_app/src/debugger/debugger_controller.dart';
import 'package:devtools_app/src/debugger/debugger_model.dart';
import 'package:devtools_app/src/debugger/debugger_screen.dart';
import 'package:devtools_app/src/globals.dart';
import 'package:devtools_app/src/service_manager.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import 'package:vm_service/vm_service.dart';
import 'support/mocks.dart';
import 'support/utils.dart';
import 'support/wrappers.dart';
void main() {
DebuggerScreen screen;
FakeServiceManager fakeServiceManager;
MockDebuggerController debuggerController;
group('DebuggerScreen', () {
Future<void> pumpDebuggerScreen(
WidgetTester tester, DebuggerController controller) async {
await tester.pumpWidget(wrapWithControllers(
const DebuggerScreenBody(),
debugger: controller,
));
}
setUp(() async {
fakeServiceManager = FakeServiceManager();
when(fakeServiceManager.connectedApp.isProfileBuildNow).thenReturn(false);
setGlobal(ServiceConnectionManager, fakeServiceManager);
when(fakeServiceManager.errorBadgeManager.errorCountNotifier(any))
.thenReturn(ValueNotifier<int>(0));
screen = const DebuggerScreen();
debuggerController = MockDebuggerController();
when(debuggerController.isPaused).thenReturn(ValueNotifier(false));
when(debuggerController.resuming).thenReturn(ValueNotifier(false));
when(debuggerController.breakpoints).thenReturn(ValueNotifier([]));
when(debuggerController.isSystemIsolate).thenReturn(false);
when(debuggerController.breakpointsWithLocation)
.thenReturn(ValueNotifier([]));
when(debuggerController.librariesVisible)
.thenReturn(ValueNotifier(false));
when(debuggerController.currentScriptRef).thenReturn(ValueNotifier(null));
when(debuggerController.sortedScripts).thenReturn(ValueNotifier([]));
when(debuggerController.selectedBreakpoint)
.thenReturn(ValueNotifier(null));
when(debuggerController.stackFramesWithLocation)
.thenReturn(ValueNotifier([]));
when(debuggerController.selectedStackFrame)
.thenReturn(ValueNotifier(null));
when(debuggerController.hasTruncatedFrames)
.thenReturn(ValueNotifier(false));
when(debuggerController.stdio)
.thenReturn(ValueNotifier([ConsoleLine.text('')]));
when(debuggerController.scriptLocation).thenReturn(ValueNotifier(null));
when(debuggerController.exceptionPauseMode)
.thenReturn(ValueNotifier('Unhandled'));
when(debuggerController.variables).thenReturn(ValueNotifier([]));
when(debuggerController.currentParsedScript)
.thenReturn(ValueNotifier<ParsedScript>(null));
});
testWidgets('builds its tab', (WidgetTester tester) async {
await tester.pumpWidget(wrap(Builder(builder: screen.buildTab)));
expect(find.text('Debugger'), findsOneWidget);
});
testWidgets('has Console / stdio area', (WidgetTester tester) async {
when(debuggerController.stdio)
.thenReturn(ValueNotifier([ConsoleLine.text('test stdio')]));
await pumpDebuggerScreen(tester, debuggerController);
expect(find.text('Console'), findsOneWidget);
// test for stdio output.
expect(find.selectableText('test stdio'), findsOneWidget);
});
testWidgets('Console area shows processed ansi text',
(WidgetTester tester) async {
when(debuggerController.stdio)
.thenReturn(ValueNotifier([ConsoleLine.text(_ansiCodesOutput())]));
await pumpDebuggerScreen(tester, debuggerController);
final finder =
find.selectableText('Ansi color codes processed for console');
expect(finder, findsOneWidget);
finder.evaluate().forEach((element) {
final selectableText = element.widget as SelectableText;
final textSpan = selectableText.textSpan;
final secondSpan = textSpan.children[1] as TextSpan;
expect(
secondSpan.text,
'console',
reason: 'Text with ansi code should be in separate span',
);
expect(
secondSpan.style.backgroundColor,
const Color.fromRGBO(215, 95, 135, 1),
);
});
});
group('ConsoleControls', () {
testWidgets('Console Controls are rendered disabled when stdio is empty',
(WidgetTester tester) async {
when(debuggerController.stdio).thenReturn(ValueNotifier([]));
await pumpDebuggerScreen(tester, debuggerController);
expect(find.byKey(DebuggerConsole.clearStdioButtonKey), findsOneWidget);
expect(find.byKey(DebuggerConsole.copyToClipboardButtonKey),
findsOneWidget);
final clearStdioElement =
find.byKey(DebuggerConsole.clearStdioButtonKey).evaluate().first;
final clearStdioButton = clearStdioElement.widget as ToolbarAction;
expect(clearStdioButton.onPressed, isNull);
});
testWidgets('Tapping the Console Clear button clears stdio.',
(WidgetTester tester) async {
when(debuggerController.stdio)
.thenReturn(ValueNotifier([ConsoleLine.text(_ansiCodesOutput())]));
await pumpDebuggerScreen(tester, debuggerController);
final clearButton = find.byKey(DebuggerConsole.clearStdioButtonKey);
expect(clearButton, findsOneWidget);
await tester.tap(clearButton);
verify(debuggerController.clearStdio());
});
group('Clipboard', () {
var _clipboardContents = '';
final _stdio = ['First line', _ansiCodesOutput(), 'Third line']
.map((text) => ConsoleLine.text(text))
.toList();
final _expected = _stdio.join('\n');
setUp(() {
// This intercepts the Clipboard.setData SystemChannel message,
// and stores the contents that were (attempted) to be copied.
SystemChannels.platform.setMockMethodCallHandler((MethodCall call) {
switch (call.method) {
case 'Clipboard.setData':
_clipboardContents = call.arguments['text'];
return Future.value(true);
break;
case 'Clipboard.getData':
return Future.value(<String, dynamic>{});
break;
default:
break;
}
return Future.value(true);
});
});
tearDown(() {
// Cleanup the SystemChannel
SystemChannels.platform.setMockMethodCallHandler(null);
});
testWidgets(
'Tapping the Copy to Clipboard button attempts to copy stdio to clipboard.',
(WidgetTester tester) async {
when(debuggerController.stdio).thenReturn(ValueNotifier(_stdio));
await pumpDebuggerScreen(tester, debuggerController);
final copyButton =
find.byKey(DebuggerConsole.copyToClipboardButtonKey);
expect(copyButton, findsOneWidget);
expect(_clipboardContents, isEmpty);
await tester.tap(copyButton);
expect(_clipboardContents, equals(_expected));
});
});
});
testWidgets('Libraries hidden', (WidgetTester tester) async {
final scripts = [
ScriptRef(uri: 'package:/test/script.dart', id: 'test-script')
];
when(debuggerController.sortedScripts).thenReturn(ValueNotifier(scripts));
// Libraries view is hidden
when(debuggerController.librariesVisible)
.thenReturn(ValueNotifier(false));
await pumpDebuggerScreen(tester, debuggerController);
expect(find.text('Libraries'), findsNothing);
});
testWidgets('Libraries visible', (WidgetTester tester) async {
final scripts = [
ScriptRef(uri: 'package:test/script.dart', id: 'test-script')
];
when(debuggerController.sortedScripts).thenReturn(ValueNotifier(scripts));
// Libraries view is shown
when(debuggerController.librariesVisible).thenReturn(ValueNotifier(true));
await pumpDebuggerScreen(tester, debuggerController);
expect(find.text('Libraries'), findsOneWidget);
// test for items in the libraries tree
expect(find.text(scripts.first.uri.split('/').first), findsOneWidget);
});
testWidgets('Breakpoints show items', (WidgetTester tester) async {
final breakpoints = [
Breakpoint(
breakpointNumber: 1,
id: 'bp1',
resolved: false,
location: UnresolvedSourceLocation(
scriptUri: 'package:test/script.dart',
line: 10,
),
enabled: true,
)
];
final breakpointsWithLocation = [
BreakpointAndSourcePosition.create(
breakpoints.first,
SourcePosition(line: 10, column: 1),
)
];
when(debuggerController.breakpoints)
.thenReturn(ValueNotifier(breakpoints));
when(debuggerController.breakpointsWithLocation)
.thenReturn(ValueNotifier(breakpointsWithLocation));
when(debuggerController.sortedScripts).thenReturn(ValueNotifier([]));
when(debuggerController.stdio).thenReturn(ValueNotifier([]));
when(debuggerController.scriptLocation).thenReturn(ValueNotifier(null));
await pumpDebuggerScreen(tester, debuggerController);
expect(find.text('Breakpoints'), findsOneWidget);
// test for items in the breakpoint list
expect(
find.byWidgetPredicate((Widget widget) =>
widget is RichText &&
widget.text.toPlainText().contains('script.dart:10')),
findsOneWidget,
);
});
testWidgetsWithWindowSize(
'Call Stack shows items', const Size(1000.0, 4000.0),
(WidgetTester tester) async {
final stackFrames = [
Frame(
index: 0,
code: CodeRef(
name: 'testCodeRef', id: 'testCodeRef', kind: CodeKind.kDart),
location: SourceLocation(
script:
ScriptRef(uri: 'package:test/script.dart', id: 'script.dart'),
tokenPos: 10,
),
kind: FrameKind.kRegular,
),
Frame(
index: 1,
location: SourceLocation(
script:
ScriptRef(uri: 'package:test/script1.dart', id: 'script1.dart'),
tokenPos: 10,
),
kind: FrameKind.kRegular,
),
Frame(
index: 2,
code: CodeRef(
name: '[Unoptimized] testCodeRef2',
id: 'testCodeRef2',
kind: CodeKind.kDart,
),
location: SourceLocation(
script:
ScriptRef(uri: 'package:test/script2.dart', id: 'script2.dart'),
tokenPos: 10,
),
kind: FrameKind.kRegular,
),
Frame(
index: 3,
code: CodeRef(
name: 'testCodeRef3.<anonymous closure>',
id: 'testCodeRef3.closure',
kind: CodeKind.kDart,
),
location: SourceLocation(
script:
ScriptRef(uri: 'package:test/script3.dart', id: 'script3.dart'),
tokenPos: 10,
),
kind: FrameKind.kRegular,
),
Frame(
index: 4,
location: SourceLocation(
script:
ScriptRef(uri: 'package:test/script4.dart', id: 'script4.dart'),
tokenPos: 10,
),
kind: FrameKind.kAsyncSuspensionMarker,
),
];
final stackFramesWithLocation =
stackFrames.map<StackFrameAndSourcePosition>((frame) {
return StackFrameAndSourcePosition(
frame,
position: SourcePosition(
line: stackFrames.indexOf(frame),
column: 10,
),
);
}).toList();
when(debuggerController.stackFramesWithLocation)
.thenReturn(ValueNotifier(stackFramesWithLocation));
when(debuggerController.isPaused).thenReturn(ValueNotifier(true));
await pumpDebuggerScreen(tester, debuggerController);
expect(find.text('Call Stack'), findsOneWidget);
// Stack frame 0
expect(
find.byWidgetPredicate((Widget widget) =>
widget is RichText &&
widget.text.toPlainText().contains('testCodeRef() script.dart 0')),
findsOneWidget,
);
// verify that the frame has a tooltip
expect(
find.byTooltip('testCodeRef() script.dart 0'),
findsOneWidget,
);
// Stack frame 1
expect(
find.byWidgetPredicate((Widget widget) =>
widget is RichText &&
widget.text.toPlainText().contains('<none> script1.dart 1')),
findsOneWidget,
);
// Stack frame 2
expect(
find.byWidgetPredicate((Widget widget) =>
widget is RichText &&
widget.text
.toPlainText()
.contains('testCodeRef2() script2.dart 2')),
findsOneWidget,
);
// Stack frame 3
expect(
find.byWidgetPredicate((Widget widget) =>
widget is RichText &&
widget.text
.toPlainText()
.contains('testCodeRef3.<closure>() script3.dart 3')),
findsOneWidget,
);
// Stack frame 4
expect(find.text('<async break>'), findsOneWidget);
});
testWidgetsWithWindowSize(
'Variables shows items', const Size(1000.0, 4000.0),
(WidgetTester tester) async {
when(debuggerController.variables)
.thenReturn(ValueNotifier(testVariables));
await pumpDebuggerScreen(tester, debuggerController);
expect(find.text('Variables'), findsOneWidget);
final listFinder = find.selectableText('Root 1: _GrowableList (2 items)');
// expect a tooltip for the list value
expect(
find.byTooltip('_GrowableList (2 items)'),
findsOneWidget,
);
final mapFinder = find
.selectableTextContaining('Root 2: _InternalLinkedHashmap (2 items)');
final mapElement1Finder = find.selectableTextContaining("['key1']: 1.0");
final mapElement2Finder = find.selectableTextContaining("['key2']: 1.1");
expect(listFinder, findsOneWidget);
expect(mapFinder, findsOneWidget);
expect(
find.selectableTextContaining("Root 3: 'test str...'"),
findsOneWidget,
);
expect(
find.selectableTextContaining('Root 4: true'),
findsOneWidget,
);
// Expand list.
expect(find.selectableTextContaining('0: 3'), findsNothing);
expect(find.selectableTextContaining('1: 4'), findsNothing);
await tester.tap(listFinder);
await tester.pumpAndSettle();
expect(find.selectableTextContaining('0: 3'), findsOneWidget);
expect(find.selectableTextContaining('1: 4'), findsOneWidget);
// Expand map.
expect(mapElement1Finder, findsNothing);
expect(mapElement2Finder, findsNothing);
await tester.tap(mapFinder);
await tester.pumpAndSettle();
expect(mapElement1Finder, findsOneWidget);
expect(mapElement2Finder, findsOneWidget);
});
WidgetPredicate createDebuggerButtonPredicate(String title) {
return (Widget widget) {
if (widget is DebuggerButton && widget.title == title) {
return true;
}
return false;
};
}
testWidgets('debugger controls running', (WidgetTester tester) async {
await tester.pumpWidget(wrapWithControllers(
Builder(builder: screen.build),
debugger: debuggerController,
));
expect(find.byWidgetPredicate(createDebuggerButtonPredicate('Pause')),
findsOneWidget);
final DebuggerButton pause = getWidgetFromFinder(
find.byWidgetPredicate(createDebuggerButtonPredicate('Pause')));
expect(pause.onPressed, isNotNull);
expect(find.byWidgetPredicate(createDebuggerButtonPredicate('Resume')),
findsOneWidget);
final DebuggerButton resume = getWidgetFromFinder(
find.byWidgetPredicate(createDebuggerButtonPredicate('Resume')));
expect(resume.onPressed, isNull);
});
testWidgets('debugger controls paused', (WidgetTester tester) async {
when(debuggerController.isPaused).thenReturn(ValueNotifier(true));
when(debuggerController.stackFramesWithLocation)
.thenReturn(ValueNotifier([
StackFrameAndSourcePosition(
Frame(
index: 0,
code: CodeRef(
name: 'testCodeRef', id: 'testCodeRef', kind: CodeKind.kDart),
location: SourceLocation(
script:
ScriptRef(uri: 'package:test/script.dart', id: 'script.dart'),
tokenPos: 10,
),
kind: FrameKind.kRegular,
),
position: SourcePosition(
line: 1,
column: 10,
),
)
]));
await tester.pumpWidget(wrapWithControllers(
Builder(builder: screen.build),
debugger: debuggerController,
));
expect(find.byWidgetPredicate(createDebuggerButtonPredicate('Pause')),
findsOneWidget);
final DebuggerButton pause = getWidgetFromFinder(
find.byWidgetPredicate(createDebuggerButtonPredicate('Pause')));
expect(pause.onPressed, isNull);
expect(find.byWidgetPredicate(createDebuggerButtonPredicate('Resume')),
findsOneWidget);
final DebuggerButton resume = getWidgetFromFinder(
find.byWidgetPredicate(createDebuggerButtonPredicate('Resume')));
expect(resume.onPressed, isNotNull);
});
testWidgets('debugger controls break on exceptions',
(WidgetTester tester) async {
await tester.pumpWidget(wrapWithControllers(
Builder(builder: screen.build),
debugger: debuggerController,
));
expect(find.text('Ignore'), findsOneWidget);
});
});
group('FloatingDebuggerControls', () {
setUp(() {
debuggerController = MockDebuggerController();
when(debuggerController.isPaused).thenReturn(ValueNotifier<bool>(true));
});
Future<void> pumpControls(WidgetTester tester) async {
await tester.pumpWidget(wrapWithControllers(
FloatingDebuggerControls(),
debugger: debuggerController,
));
await tester.pumpAndSettle();
}
testWidgets('display as expected', (WidgetTester tester) async {
await pumpControls(tester);
final animatedOpacityFinder = find.byType(AnimatedOpacity);
expect(animatedOpacityFinder, findsOneWidget);
final AnimatedOpacity animatedOpacity =
animatedOpacityFinder.evaluate().first.widget;
expect(animatedOpacity.opacity, equals(1.0));
expect(
find.text('Main isolate is paused in the debugger'), findsOneWidget);
expect(find.byTooltip('Resume'), findsOneWidget);
expect(find.byTooltip('Step over'), findsOneWidget);
});
testWidgets('can resume', (WidgetTester tester) async {
bool didResume = false;
Future<Success> resume() {
didResume = true;
return Future.value(Success());
}
when(debuggerController.resume()).thenAnswer((_) => resume());
await pumpControls(tester);
expect(didResume, isFalse);
await tester.tap(find.byTooltip('Resume'));
await tester.pumpAndSettle();
expect(didResume, isTrue);
});
testWidgets('can step over', (WidgetTester tester) async {
bool didStep = false;
Future<Success> stepOver() {
didStep = true;
return Future.value(Success());
}
when(debuggerController.stepOver()).thenAnswer((_) => stepOver());
await pumpControls(tester);
expect(didStep, isFalse);
await tester.tap(find.byTooltip('Step over'));
await tester.pumpAndSettle();
expect(didStep, isTrue);
});
testWidgets('are hidden when app is not paused',
(WidgetTester tester) async {
when(debuggerController.isPaused).thenReturn(ValueNotifier<bool>(false));
await pumpControls(tester);
final animatedOpacityFinder = find.byType(AnimatedOpacity);
expect(animatedOpacityFinder, findsOneWidget);
final AnimatedOpacity animatedOpacity =
animatedOpacityFinder.evaluate().first.widget;
expect(animatedOpacity.opacity, equals(0.0));
});
});
}
Widget getWidgetFromFinder(Finder finder) {
return finder.first.evaluate().first.widget;
}
String _ansiCodesOutput() {
final sb = StringBuffer();
sb.write('Ansi color codes processed for ');
final pen = AnsiPen()..rgb(r: 0.8, g: 0.3, b: 0.4, bg: true);
sb.write(pen('console'));
return sb.toString();
}
final libraryRef = LibraryRef(
name: 'some library',
uri: 'package:foo/foo.dart',
id: 'lib-id-1',
);
final testVariables = [
Variable.create(BoundVariable(
name: 'Root 1',
value: InstanceRef(
id: 'ref1',
kind: InstanceKind.kList,
classRef: ClassRef(
name: '_GrowableList',
id: 'ref2',
library: libraryRef,
),
length: 2,
identityHashCode: null,
),
declarationTokenPos: null,
scopeEndTokenPos: null,
scopeStartTokenPos: null,
))
..addAllChildren([
Variable.create(BoundVariable(
name: '0',
value: InstanceRef(
id: 'ref3',
kind: InstanceKind.kInt,
classRef: ClassRef(name: 'Integer', id: 'ref4', library: libraryRef),
valueAsString: '3',
valueAsStringIsTruncated: false,
identityHashCode: null,
),
declarationTokenPos: null,
scopeEndTokenPos: null,
scopeStartTokenPos: null,
)),
Variable.create(BoundVariable(
name: '1',
value: InstanceRef(
id: 'ref5',
kind: InstanceKind.kInt,
classRef: ClassRef(name: 'Integer', id: 'ref6', library: libraryRef),
valueAsString: '4',
valueAsStringIsTruncated: false,
identityHashCode: null,
),
declarationTokenPos: null,
scopeEndTokenPos: null,
scopeStartTokenPos: null,
)),
]),
Variable.create(BoundVariable(
name: 'Root 2',
value: InstanceRef(
id: 'ref7',
kind: InstanceKind.kMap,
classRef: ClassRef(
name: '_InternalLinkedHashmap', id: 'ref8', library: libraryRef),
length: 2,
identityHashCode: null,
),
declarationTokenPos: null,
scopeEndTokenPos: null,
scopeStartTokenPos: null,
))
..addAllChildren([
Variable.create(BoundVariable(
name: "['key1']",
value: InstanceRef(
id: 'ref9',
kind: InstanceKind.kDouble,
classRef: ClassRef(name: 'Double', id: 'ref10', library: libraryRef),
valueAsString: '1.0',
valueAsStringIsTruncated: false,
identityHashCode: null,
),
declarationTokenPos: null,
scopeEndTokenPos: null,
scopeStartTokenPos: null,
)),
Variable.create(BoundVariable(
name: "['key2']",
value: InstanceRef(
id: 'ref11',
kind: InstanceKind.kDouble,
classRef: ClassRef(name: 'Double', id: 'ref12', library: libraryRef),
valueAsString: '1.1',
valueAsStringIsTruncated: false,
identityHashCode: null,
),
declarationTokenPos: null,
scopeEndTokenPos: null,
scopeStartTokenPos: null,
)),
]),
Variable.create(BoundVariable(
name: 'Root 3',
value: InstanceRef(
id: 'ref13',
kind: InstanceKind.kString,
classRef: ClassRef(name: 'String', id: 'ref14', library: libraryRef),
valueAsString: 'test str',
valueAsStringIsTruncated: true,
identityHashCode: null,
),
declarationTokenPos: null,
scopeEndTokenPos: null,
scopeStartTokenPos: null,
)),
Variable.create(BoundVariable(
name: 'Root 4',
value: InstanceRef(
id: 'ref15',
kind: InstanceKind.kBool,
classRef: ClassRef(name: 'Boolean', id: 'ref16', library: libraryRef),
valueAsString: 'true',
valueAsStringIsTruncated: false,
identityHashCode: null,
),
declarationTokenPos: null,
scopeEndTokenPos: null,
scopeStartTokenPos: null,
)),
];
| devtools/packages/devtools_app/test/debugger_screen_test.dart/0 | {'file_path': 'devtools/packages/devtools_app/test/debugger_screen_test.dart', 'repo_id': 'devtools', 'token_count': 10518} |
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
@TestOn('vm')
import 'package:devtools_app/src/globals.dart';
import 'package:devtools_app/src/performance/flutter_frames_chart.dart';
import 'package:devtools_app/src/performance/performance_controller.dart';
import 'package:devtools_app/src/performance/performance_model.dart';
import 'package:devtools_app/src/service_manager.dart';
import 'package:devtools_app/src/ui/colors.dart';
import 'package:devtools_testing/support/performance_test_data.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'support/mocks.dart';
import 'support/wrappers.dart';
void main() {
Future<void> pumpChart(
WidgetTester tester, {
@required List<FlutterFrame> frames,
}) async {
await tester.pumpWidget(wrapWithControllers(
FlutterFramesChart(frames, defaultRefreshRate),
performance: PerformanceController(),
));
await tester.pumpAndSettle();
expect(find.byType(FlutterFramesChart), findsOneWidget);
}
group('FlutterFramesChart', () {
setUp(() async {
setGlobal(ServiceConnectionManager, FakeServiceManager());
});
testWidgets('builds with no frames', (WidgetTester tester) async {
await pumpChart(tester, frames: []);
expect(find.byKey(FlutterFramesChart.chartLegendKey), findsOneWidget);
expect(find.byType(FlutterFramesChartItem), findsNothing);
});
testWidgets('builds with frames', (WidgetTester tester) async {
await pumpChart(tester, frames: [testFrame0, testFrame1]);
expect(find.byKey(FlutterFramesChart.chartLegendKey), findsOneWidget);
expect(find.byType(FlutterFramesChartItem), findsNWidgets(2));
});
testWidgets('builds with janky frame', (WidgetTester tester) async {
await pumpChart(tester, frames: [jankyFrame]);
expect(find.byKey(FlutterFramesChart.chartLegendKey), findsOneWidget);
expect(find.byType(FlutterFramesChartItem), findsOneWidget);
final ui = tester.widget(find.byKey(const Key('frame jankyFrame - ui')))
as Container;
expect(ui.color, equals(uiJankColor));
final raster =
tester.widget(find.byKey(const Key('frame jankyFrame - raster')))
as Container;
expect(raster.color, equals(rasterJankColor));
});
testWidgets('builds with janky frame ui only', (WidgetTester tester) async {
await pumpChart(tester, frames: [jankyFrameUiOnly]);
expect(find.byKey(FlutterFramesChart.chartLegendKey), findsOneWidget);
expect(find.byType(FlutterFramesChartItem), findsOneWidget);
final ui =
tester.widget(find.byKey(const Key('frame jankyFrameUiOnly - ui')))
as Container;
expect(ui.color, equals(uiJankColor));
final raster = tester
.widget(find.byKey(const Key('frame jankyFrameUiOnly - raster')))
as Container;
expect(raster.color, equals(mainRasterColor));
});
testWidgets('builds with janky frame raster only',
(WidgetTester tester) async {
await pumpChart(tester, frames: [jankyFrameRasterOnly]);
expect(find.byKey(FlutterFramesChart.chartLegendKey), findsOneWidget);
expect(find.byType(FlutterFramesChartItem), findsOneWidget);
final ui = tester
.widget(find.byKey(const Key('frame jankyFrameRasterOnly - ui')))
as Container;
expect(ui.color, equals(mainUiColor));
final raster = tester.widget(
find.byKey(const Key('frame jankyFrameRasterOnly - raster')))
as Container;
expect(raster.color, equals(rasterJankColor));
});
});
group('FlutterFramesChartItem', () {
testWidgets('builds for selected frame', (WidgetTester tester) async {
await tester.pumpWidget(
// FlutterFramesChartItem needs to be wrapped in Material,
// Directionality, and Overlay in order to pump the widget and test.
Material(
child: Directionality(
textDirection: TextDirection.ltr,
child: Overlay(
initialEntries: [
OverlayEntry(
builder: (context) {
return FlutterFramesChartItem(
frame: testFrame0,
selected: true,
msPerPx: 1,
availableChartHeight: 100.0,
displayRefreshRate: defaultRefreshRate,
);
},
),
],
),
),
),
);
expect(find.byKey(FlutterFramesChartItem.selectedFrameIndicatorKey),
findsOneWidget);
});
});
}
| devtools/packages/devtools_app/test/flutter_frames_chart_test.dart/0 | {'file_path': 'devtools/packages/devtools_app/test/flutter_frames_chart_test.dart', 'repo_id': 'devtools', 'token_count': 1970} |
// 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:convert';
import 'package:devtools_app/src/globals.dart';
import 'package:devtools_app/src/inspector/diagnostics_node.dart';
import 'package:devtools_app/src/inspector/inspector_controller.dart';
import 'package:devtools_app/src/inspector/inspector_screen.dart';
import 'package:devtools_app/src/inspector/inspector_service.dart';
import 'package:devtools_app/src/inspector/inspector_tree.dart';
import 'package:devtools_app/src/inspector/layout_explorer/flex/flex.dart';
import 'package:devtools_app/src/inspector/layout_explorer/layout_explorer.dart';
import 'package:devtools_app/src/service_extensions.dart' as extensions;
import 'package:devtools_app/src/service_manager.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart' hide Fake;
import 'package:mockito/mockito.dart';
import 'support/mocks.dart';
import 'support/wrappers.dart';
void main() {
const screen = InspectorScreen();
FakeServiceManager fakeServiceManager;
FakeServiceExtensionManager fakeExtensionManager;
const windowSize = Size(2600.0, 1200.0);
group('Inspector Screen', () {
setUp(() {
fakeServiceManager = FakeServiceManager();
fakeExtensionManager = fakeServiceManager.serviceExtensionManager;
when(fakeServiceManager.connectedApp.isFlutterAppNow).thenReturn(true);
when(fakeServiceManager.connectedApp.isProfileBuildNow).thenReturn(false);
when(fakeServiceManager.errorBadgeManager.errorCountNotifier(any))
.thenReturn(ValueNotifier<int>(0));
setGlobal(ServiceConnectionManager, fakeServiceManager);
mockIsFlutterApp(serviceManager.connectedApp);
});
void mockExtensions() {
fakeExtensionManager.extensionValueOnDevice = {
extensions.toggleSelectWidgetMode.extension: true,
extensions.enableOnDeviceInspector.extension: true,
extensions.toggleOnDeviceWidgetInspector.extension: true,
extensions.debugPaint.extension: false,
};
fakeExtensionManager
..fakeAddServiceExtension(
extensions.toggleOnDeviceWidgetInspector.extension)
..fakeAddServiceExtension(extensions.toggleSelectWidgetMode.extension)
..fakeAddServiceExtension(extensions.enableOnDeviceInspector.extension)
..fakeAddServiceExtension(extensions.debugPaint.extension)
..fakeFrame();
}
void mockNoExtensionsAvailable() {
fakeExtensionManager.extensionValueOnDevice = {
extensions.toggleOnDeviceWidgetInspector.extension: true,
extensions.toggleSelectWidgetMode.extension: false,
extensions.debugPaint.extension: false,
};
// Don't actually send any events to the client indicating that service
// extensions are avaiable.
fakeExtensionManager.fakeFrame();
}
testWidgets('builds its tab', (WidgetTester tester) async {
await tester.pumpWidget(wrap(Builder(builder: screen.buildTab)));
expect(find.text('Flutter Inspector'), findsOneWidget);
});
group('Widget Errors', () {
// Display of error navigator/indicators is tested by a golden in
// inspector_integration_test.dart
testWidgetsWithWindowSize(
'does not render error navigator if no errors', windowSize,
(WidgetTester tester) async {
await tester.pumpWidget(wrap(Builder(builder: screen.build)));
expect(find.byType(ErrorNavigator), findsNothing);
});
});
testWidgetsWithWindowSize('builds with no data', windowSize,
(WidgetTester tester) async {
// Make sure the window is wide enough to display description text.
await tester.pumpWidget(wrap(Builder(builder: screen.build)));
expect(find.byType(InspectorScreenBody), findsOneWidget);
expect(find.text('Refresh Tree'), findsOneWidget);
expect(find.text(extensions.debugPaint.description), findsOneWidget);
// Make sure there is not an overflow if the window is narrow.
// TODO(jacobr): determine why there are overflows in the test environment
// but not on the actual device for this cae.
// await setWindowSize(const Size(1000.0, 1200.0));
// Verify that description text is no-longer shown.
// expect(find.text(extensions.debugPaint.description), findsOneWidget);
});
testWidgetsWithWindowSize(
'Test toggling service extension buttons', windowSize,
(WidgetTester tester) async {
mockExtensions();
expect(
fakeExtensionManager
.extensionValueOnDevice[extensions.debugPaint.extension],
isFalse,
);
expect(
fakeExtensionManager.extensionValueOnDevice[
extensions.toggleOnDeviceWidgetInspector.extension],
isTrue,
);
await tester.pumpWidget(wrap(Builder(builder: screen.build)));
expect(
fakeExtensionManager.extensionValueOnDevice[
extensions.toggleSelectWidgetMode.extension],
isTrue,
);
// We need a frame to find out that the service extension state has changed.
expect(find.byType(InspectorScreenBody), findsOneWidget);
expect(
find.text(extensions.toggleSelectWidgetMode.description),
findsOneWidget,
);
expect(find.text(extensions.debugPaint.description), findsOneWidget);
await tester.pump();
await tester
.tap(find.text(extensions.toggleSelectWidgetMode.description));
expect(
fakeExtensionManager.extensionValueOnDevice[
extensions.toggleSelectWidgetMode.extension],
isFalse,
);
// Verify the the other service extension's state hasn't changed.
expect(
fakeExtensionManager
.extensionValueOnDevice[extensions.debugPaint.extension],
isFalse,
);
await tester
.tap(find.text(extensions.toggleSelectWidgetMode.description));
expect(
fakeExtensionManager.extensionValueOnDevice[
extensions.toggleSelectWidgetMode.extension],
isTrue,
);
await tester.tap(find.text(extensions.debugPaint.description));
expect(
fakeExtensionManager
.extensionValueOnDevice[extensions.debugPaint.extension],
isTrue,
);
});
testWidgetsWithWindowSize(
'Test toggling service extension buttons with no extensions available',
windowSize, (WidgetTester tester) async {
mockNoExtensionsAvailable();
expect(
fakeExtensionManager
.extensionValueOnDevice[extensions.debugPaint.extension],
isFalse,
);
expect(
fakeExtensionManager.extensionValueOnDevice[
extensions.toggleOnDeviceWidgetInspector.extension],
isTrue,
);
await tester.pumpWidget(wrap(Builder(builder: screen.build)));
await tester.pump();
expect(find.byType(InspectorScreenBody), findsOneWidget);
expect(find.text(extensions.toggleOnDeviceWidgetInspector.description),
findsOneWidget);
expect(find.text(extensions.debugPaint.description), findsOneWidget);
await tester.pump();
await tester
.tap(find.text(extensions.toggleOnDeviceWidgetInspector.description));
// Verify the service extension state has not changed.
expect(
fakeExtensionManager.extensionValueOnDevice[
extensions.toggleOnDeviceWidgetInspector.extension],
isTrue);
await tester
.tap(find.text(extensions.toggleOnDeviceWidgetInspector.description));
// Verify the service extension state has not changed.
expect(
fakeExtensionManager.extensionValueOnDevice[
extensions.toggleOnDeviceWidgetInspector.extension],
isTrue);
// TODO(jacobr): also verify that the service extension buttons look
// visually disabled.
});
group('LayoutDetailsTab', () {
final renderObjectJson = jsonDecode('''
{
"properties": [
{
"description": "horizontal",
"name": "direction"
},
{
"description": "start",
"name": "mainAxisAlignment"
},
{
"description": "max",
"name": "mainAxisSize"
},
{
"description": "center",
"name": "crossAxisAlignment"
},
{
"description": "ltr",
"name": "textDirection"
},
{
"description": "down",
"name": "verticalDirection"
}
]
}
''');
final diagnostic = RemoteDiagnosticsNode(
<String, Object>{
'widgetRuntimeType': 'Row',
'renderObject': renderObjectJson,
'hasChildren': false,
'children': [],
},
null,
false,
null,
);
final treeNode = InspectorTreeNode()..diagnostic = diagnostic;
testWidgetsWithWindowSize(
'should render StoryOfYourFlexWidget', windowSize,
(WidgetTester tester) async {
final controller = TestInspectorController()..setSelectedNode(treeNode);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: LayoutExplorerTab(
controller: controller,
),
),
),
);
expect(find.byType(FlexLayoutExplorerWidget), findsOneWidget);
});
testWidgetsWithWindowSize(
'should listen to controller selection event', windowSize,
(WidgetTester tester) async {
final controller = TestInspectorController();
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: LayoutExplorerTab(
controller: controller,
),
),
),
);
expect(find.byType(FlexLayoutExplorerWidget), findsNothing);
controller.setSelectedNode(treeNode);
await tester.pumpAndSettle();
expect(find.byType(FlexLayoutExplorerWidget), findsOneWidget);
});
});
// TODO(jacobr): add screenshot tests that connect to a test application
// in the same way the inspector_controller test does today and take golden
// images. Alternately: support an offline inspector mode and add tests of
// that mode which would enable faster tests that run as unittests.
});
}
class MockInspectorService extends Mock implements InspectorService {}
class MockInspectorTreeController extends Mock
implements InspectorTreeController {}
class TestInspectorController extends Fake implements InspectorController {
InspectorService service = MockInspectorService();
@override
ValueListenable<InspectorTreeNode> get selectedNode => _selectedNode;
final ValueNotifier<InspectorTreeNode> _selectedNode = ValueNotifier(null);
@override
void setSelectedNode(InspectorTreeNode newSelection) {
_selectedNode.value = newSelection;
}
@override
InspectorService get inspectorService => service;
}
| devtools/packages/devtools_app/test/inspector_screen_test.dart/0 | {'file_path': 'devtools/packages/devtools_app/test/inspector_screen_test.dart', 'repo_id': 'devtools', 'token_count': 4460} |
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:devtools_app/src/banner_messages.dart';
import 'package:devtools_app/src/globals.dart';
import 'package:devtools_app/src/provider/instance_viewer/instance_details.dart';
import 'package:devtools_app/src/provider/instance_viewer/instance_providers.dart';
import 'package:devtools_app/src/provider/provider_list.dart';
import 'package:devtools_app/src/provider/provider_nodes.dart';
@TestOn('vm')
import 'package:devtools_app/src/provider/provider_screen.dart';
import 'package:devtools_app/src/service_manager.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import '../support/mocks.dart';
import '../support/utils.dart';
import '../support/wrappers.dart';
void main() {
// Set a wide enough screen width that we do not run into overflow.
const windowSize = Size(2225.0, 1000.0);
Widget providerScreen;
BannerMessagesController bannerMessagesController;
setUpAll(() => loadFonts());
setUp(() {
setGlobal(ServiceConnectionManager, FakeServiceManager());
});
setUp(() {
bannerMessagesController = BannerMessagesController();
providerScreen = Container(
color: Colors.grey,
child: Directionality(
textDirection: TextDirection.ltr,
child: wrapWithControllers(
const BannerMessages(screen: ProviderScreen()),
bannerMessages: bannerMessagesController,
),
),
);
});
group('ProviderScreen', () {
testWidgetsWithWindowSize(
'shows ProviderUnknownErrorBanner if the devtool failed to fetch the list of providers',
windowSize, (tester) async {
final container = ProviderContainer(overrides: [
rawSortedProviderNodesProvider.overrideWithValue(
const AsyncValue.loading(),
),
]);
addTearDown(container.dispose);
await tester.pumpWidget(
UncontrolledProviderScope(
container: container,
child: providerScreen,
),
);
container.updateOverrides([
rawSortedProviderNodesProvider.overrideWithValue(
AsyncValue.error(StateError('')),
),
]);
// wait for the Banner to appear as it is mounted asynchronously
await tester.pumpAndSettle();
await expectLater(
find.byType(ProviderScreenBody),
matchesGoldenFile('../goldens/provider_screen/list_error_banner.png'),
);
});
});
group('selectedProviderIdProvider', () {
test('selects the first provider available', () async {
final container = ProviderContainer(overrides: [
rawSortedProviderNodesProvider.overrideWithValue(
const AsyncValue.loading(),
),
]);
addTearDown(container.dispose);
final sub = container.listen(selectedProviderIdProvider);
expect(sub.read(), isNull);
container.updateOverrides([
rawSortedProviderNodesProvider.overrideWithValue(
const AsyncValue.data([
ProviderNode(id: '0', type: 'Provider<A>'),
ProviderNode(id: '1', type: 'Provider<B>'),
]),
),
]);
await container.pumpAndSettle();
expect(sub.read(), '0');
});
test('selects the first provider available after an error', () async {
final container = ProviderContainer(overrides: [
rawSortedProviderNodesProvider.overrideWithValue(
AsyncValue.error(Error()),
),
]);
addTearDown(container.dispose);
final sub = container.listen(selectedProviderIdProvider);
// wait for the error to be handled
await container.pumpAndSettle();
expect(sub.read(), isNull);
container.updateOverrides([
rawSortedProviderNodesProvider.overrideWithValue(
const AsyncValue.data([
ProviderNode(id: '0', type: 'Provider<A>'),
ProviderNode(id: '1', type: 'Provider<B>'),
]),
),
]);
// wait for the ids update to be handled
await container.pumpAndSettle(exclude: [selectedProviderIdProvider]);
expect(sub.read(), '0');
});
test(
'When the currently selected provider is removed, selects the next first provider',
() async {
final container = ProviderContainer(overrides: [
rawSortedProviderNodesProvider.overrideWithValue(
const AsyncValue.data([
ProviderNode(id: '0', type: 'Provider<A>'),
]),
),
]);
addTearDown(container.dispose);
final sub = container.listen(selectedProviderIdProvider);
await container.pumpAndSettle();
expect(sub.read(), '0');
container.updateOverrides([
rawSortedProviderNodesProvider.overrideWithValue(
const AsyncValue.data([
ProviderNode(id: '1', type: 'Provider<B>'),
]),
),
]);
await container.pumpAndSettle();
expect(sub.read(), '1');
});
test('Once a provider is selected, further updates are no-op', () async {
final container = ProviderContainer(overrides: [
rawSortedProviderNodesProvider.overrideWithValue(
const AsyncValue.data([
ProviderNode(id: '0', type: 'Provider<A>'),
]),
),
]);
addTearDown(container.dispose);
final sub = container.listen(selectedProviderIdProvider);
await container.pumpAndSettle();
expect(sub.read(), '0');
container.updateOverrides([
rawSortedProviderNodesProvider.overrideWithValue(
// '0' is no-longer the first provider on purpose
const AsyncValue.data([
ProviderNode(id: '1', type: 'Provider<B>'),
ProviderNode(id: '0', type: 'Provider<A>'),
]),
),
]);
await container.pumpAndSettle();
expect(sub.read(), '0');
});
test(
'when the list of providers becomes empty, the current provider is unselected '
', then, the first provider will be selected when the list becomes non-empty again.',
() async {
final container = ProviderContainer(overrides: [
rawSortedProviderNodesProvider.overrideWithValue(
const AsyncValue.data([
ProviderNode(id: '0', type: 'Provider<A>'),
]),
),
]);
addTearDown(container.dispose);
final sub = container.listen(selectedProviderIdProvider);
await container.pumpAndSettle();
expect(sub.read(), '0');
container.updateOverrides([
rawSortedProviderNodesProvider.overrideWithValue(
const AsyncValue.data([]),
),
]);
await container.pumpAndSettle();
expect(sub.read(), isNull);
container.updateOverrides([
rawSortedProviderNodesProvider.overrideWithValue(
const AsyncValue.data([
ProviderNode(id: '1', type: 'Provider<B>'),
]),
),
]);
await container.pumpAndSettle();
expect(sub.read(), '1');
});
});
group('ProviderList', () {
List<Override> getOverrides() {
return [
rawInstanceProvider(const InstancePath.fromProviderId('0'))
.overrideWithValue(AsyncValue.data(
InstanceDetails.string(
'Value0',
instanceRefId: 'string/0',
setter: null,
),
))
];
}
testWidgetsWithWindowSize(
'selects the first provider the first time a provider is received',
windowSize, (tester) async {
final container = ProviderContainer(overrides: [
rawSortedProviderNodesProvider
.overrideWithValue(const AsyncValue.loading()),
...getOverrides(),
]);
await tester.pumpWidget(
UncontrolledProviderScope(
container: container,
child: providerScreen,
),
);
final context = tester.element(find.byType(ProviderScreenBody));
expect(context.read(selectedProviderIdProvider), isNull);
expect(find.byType(ProviderNodeItem), findsNothing);
await expectLater(
find.byType(ProviderScreenBody),
matchesGoldenFile(
'../goldens/provider_screen/no_selected_provider.png'),
);
container.updateOverrides([
rawSortedProviderNodesProvider.overrideWithValue(
const AsyncValue.data([
ProviderNode(id: '0', type: 'Provider<A>'),
ProviderNode(id: '1', type: 'Provider<B>'),
]),
),
...getOverrides(),
]);
await tester.pumpAndSettle();
expect(context.read(selectedProviderIdProvider), '0');
expect(find.byType(ProviderNodeItem), findsNWidgets(2));
expect(
find.descendant(
of: find.byKey(const Key('provider-0')),
matching: find.text('Provider<A>()'),
),
findsOneWidget,
);
expect(
find.descendant(
of: find.byKey(const Key('provider-1')),
matching: find.text('Provider<B>()'),
),
findsOneWidget,
);
await expectLater(
find.byType(ProviderScreenBody),
matchesGoldenFile('../goldens/provider_screen/selected_provider.png'),
);
});
testWidgetsWithWindowSize(
'shows ProviderUnknownErrorBanner if the devtool failed to fetch the selected provider',
windowSize, (tester) async {
final overrides = [
rawSortedProviderNodesProvider.overrideWithValue(
const AsyncValue.data([
ProviderNode(id: '0', type: 'Provider<A>'),
ProviderNode(id: '1', type: 'Provider<B>'),
]),
),
...getOverrides(),
];
final container = ProviderContainer(
overrides: [
...overrides,
rawInstanceProvider(const InstancePath.fromProviderId('0'))
.overrideWithValue(const AsyncValue.loading())
],
);
addTearDown(container.dispose);
await tester.pumpWidget(
UncontrolledProviderScope(
container: container,
child: providerScreen,
),
);
container.updateOverrides([
...overrides,
rawInstanceProvider(const InstancePath.fromProviderId('0'))
.overrideWithValue(AsyncValue.error(Error()))
]);
await tester.pumpAndSettle();
expect(
find.byKey(
const Key('ProviderUnknownErrorBanner - ${ProviderScreen.id}'),
),
findsOneWidget,
);
await expectLater(
find.byType(ProviderScreenBody),
matchesGoldenFile(
'../goldens/provider_screen/selected_provider_error_banner.png'),
);
});
});
}
extension on ProviderContainer {
// TODO(rrousselGit) remove this utility when riverpod v0.15.0 is released
Future<void> pumpAndSettle({
List<ProviderBase> exclude = const [],
}) async {
bool hasDirtyProvider() {
return debugProviderElements
// ignore: invalid_use_of_protected_member
.any((e) => e.dirty && !exclude.contains(e.provider));
}
while (hasDirtyProvider()) {
for (final element in debugProviderElements) {
element.flush();
}
await Future(() {});
}
}
}
| devtools/packages/devtools_app/test/provider/provider_screen_test.dart/0 | {'file_path': 'devtools/packages/devtools_app/test/provider/provider_screen_test.dart', 'repo_id': 'devtools', 'token_count': 4786} |
// 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:convert';
import 'dart:io';
import 'chrome.dart';
const verbose = true;
class DevToolsServerDriver {
DevToolsServerDriver._(
this._process,
this._stdin,
Stream<String> _stdout,
Stream<String> _stderr,
) : stdout = _convertToMapStream(_stdout),
stderr = _stderr.map((line) {
_trace('<== STDERR $line');
return line;
});
final Process _process;
final Stream<Map<String, dynamic>> stdout;
final Stream<String> stderr;
final StringSink _stdin;
void write(Map<String, dynamic> request) {
final line = jsonEncode(request);
_trace('==> $line');
_stdin.writeln(line);
}
static Stream<Map<String, dynamic>> _convertToMapStream(
Stream<String> stream,
) {
return stream.map((line) {
_trace('<== $line');
return line;
}).map((line) {
try {
return jsonDecode(line) as Map<String, dynamic>;
} catch (e) {
return null;
}
}).where((item) => item != null);
}
static void _trace(String message) {
if (verbose) {
print(message);
}
}
bool kill() => _process.kill();
static Future<DevToolsServerDriver> create({
int port = 0,
int tryPorts,
List<String> additionalArgs = const [],
}) async {
// These tests assume that the devtools package is present in a sibling
// directory of the devtools_app package.
final args = [
'../devtools/bin/devtools.dart',
'--machine',
'--port',
'$port',
...additionalArgs
];
if (tryPorts != null) {
args.addAll(['--try-ports', '$tryPorts']);
}
if (useChromeHeadless && headlessModeIsSupported) {
args.add('--headless');
}
final Process process = await Process.start('dart', args);
return DevToolsServerDriver._(
process,
process.stdin,
process.stdout.transform(utf8.decoder).transform(const LineSplitter()),
process.stderr.transform(utf8.decoder).transform(const LineSplitter()),
);
}
}
| devtools/packages/devtools_app/test/support/devtools_server_driver.dart/0 | {'file_path': 'devtools/packages/devtools_app/test/support/devtools_server_driver.dart', 'repo_id': 'devtools', 'token_count': 876} |
// 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/url_utils.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
group('url utils', () {
test('getSimplePackageUrl', () {
expect(getSimplePackageUrl(''), equals(''));
expect(getSimplePackageUrl(dartSdkUrl), equals(dartSdkUrl));
expect(
getSimplePackageUrl(flutterUrl),
equals('package:flutter/lib/src/widgets/binding.dart'),
);
expect(
getSimplePackageUrl(flutterUrlFromNonFlutterDir),
equals('package:flutter/lib/src/widgets/binding.dart'),
);
expect(
getSimplePackageUrl(flutterWebUrl),
equals('package:flutter_web/lib/src/widgets/binding.dart'),
);
});
group('normalizeVmServiceUri', () {
test('normalizes simple URIs', () {
expect(
normalizeVmServiceUri('http://127.0.0.1:60667/72K34Xmq0X0=')
.toString(),
equals('http://127.0.0.1:60667/72K34Xmq0X0='),
);
expect(
normalizeVmServiceUri('http://127.0.0.1:60667/72K34Xmq0X0=/ ')
.toString(),
equals('http://127.0.0.1:60667/72K34Xmq0X0=/'),
);
expect(
normalizeVmServiceUri('http://127.0.0.1:60667').toString(),
equals('http://127.0.0.1:60667'),
);
expect(
normalizeVmServiceUri('http://127.0.0.1:60667/').toString(),
equals('http://127.0.0.1:60667/'),
);
});
test('properly strips leading whitespace and trailing URI fragments', () {
expect(
normalizeVmServiceUri(' http://127.0.0.1:60667/72K34Xmq0X0=/#/vm')
.toString(),
equals('http://127.0.0.1:60667/72K34Xmq0X0=/'),
);
expect(
normalizeVmServiceUri(' http://127.0.0.1:60667/72K34Xmq0X0=/#/vm ')
.toString(),
equals('http://127.0.0.1:60667/72K34Xmq0X0=/'),
);
});
test('properly handles encoded urls', () {
expect(
normalizeVmServiceUri(
'http%3A%2F%2F127.0.0.1%3A58824%2FCnvgRrQJG7w%3D')
.toString(),
equals('http://127.0.0.1:58824/CnvgRrQJG7w='),
);
expect(
normalizeVmServiceUri(
'http%3A%2F%2F127.0.0.1%3A58824%2FCnvgRrQJG7w%3D ',
).toString(),
equals('http://127.0.0.1:58824/CnvgRrQJG7w='),
);
expect(
normalizeVmServiceUri(
' http%3A%2F%2F127.0.0.1%3A58824%2FCnvgRrQJG7w%3D ',
).toString(),
equals('http://127.0.0.1:58824/CnvgRrQJG7w='),
);
});
test('handles prefixed devtools server uris', () {
expect(
normalizeVmServiceUri(
'http://127.0.0.1:9101?uri=http%3A%2F%2F127.0.0.1%3A56142%2FHOwgrxalK00%3D%2F',
).toString(),
equals('http://127.0.0.1:56142/HOwgrxalK00=/'),
);
});
test('Returns null when given a non-absolute url', () {
expect(normalizeVmServiceUri('my/page'), null);
});
});
});
}
const dartSdkUrl =
'org-dartlang-sdk:///third_party/dart/sdk/lib/async/zone.dart';
const flutterUrl =
'file:///path/to/flutter/packages/flutter/lib/src/widgets/binding.dart';
const flutterUrlFromNonFlutterDir =
'file:///path/to/non-flutter/packages/flutter/lib/src/widgets/binding.dart';
const flutterWebUrl =
'file:///path/to/flutter/packages/flutter_web/lib/src/widgets/binding.dart';
| devtools/packages/devtools_app/test/url_utils_test.dart/0 | {'file_path': 'devtools/packages/devtools_app/test/url_utils_test.dart', 'repo_id': 'devtools', 'token_count': 1906} |
// 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' as io;
import 'package:args/command_runner.dart';
import '../model.dart';
class RollbackCommand extends Command {
RollbackCommand() : super() {
argParser.addOption('to-version');
}
@override
String get name => 'rollback';
@override
String get description => 'Rolls back to a specific DevTools version.';
@override
Future run() async {
final repo = DevToolsRepo.getInstance()!;
print('DevTools repo at ${repo.repoPath}.');
final tempDir =
(await io.Directory.systemTemp.createTemp('devtools-rollback'))
.absolute;
print('file://${tempDir.path}');
final tarball = io.File(
'${tempDir.path}/devtools.tar.gz',
);
final extractDir =
await io.Directory('${tempDir.path}/extract/').absolute.create();
final client = io.HttpClient();
final version = argResults!['to-version'];
print('downloading tarball to ${tarball.path}');
final tarballRequest = await client.getUrl(Uri.http(
'storage.googleapis.com',
'pub-packages/packages/devtools-$version.tar.gz'));
final tarballResponse = await tarballRequest.close();
await tarballResponse.pipe(tarball.openWrite());
print('Tarball written; unzipping.');
await io.Process.run(
'tar',
['-x', '-z', '-f', tarball.path.split('/').last, '-C', extractDir.path],
workingDirectory: tempDir.path,
);
print('file://${tempDir.path}');
final buildDir = io.Directory('${repo.repoPath}/packages/devtools/build/');
await buildDir.delete(recursive: true);
await io.Directory('${extractDir.path}build/')
.rename('${repo.repoPath}/packages/devtools/build/');
print('Build outputs from Devtools version $version checked out and moved '
'to ${buildDir.path}');
print('To complete the rollback, go to ${repo.repoPath}/packages/devtools, '
'rev pubspec.yaml, update the changelog, unhide build/ from the '
'packages/devtools/.gitignore file, then run pub publish.');
// TODO(djshuckerow): automatically rev pubspec.yaml and update the
// changelog so that the user can just run pub publish from
// packages/devtools.
}
}
| devtools/tool/lib/commands/rollback.dart/0 | {'file_path': 'devtools/tool/lib/commands/rollback.dart', 'repo_id': 'devtools', 'token_count': 864} |
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dio_error.dart';
import 'options.dart';
import 'adapter.dart';
/// [Transformer] allows changes to the request/response data before
/// it is sent/received to/from the server.
/// This is only applicable for request methods 'PUT', 'POST', and 'PATCH'.
///
/// Dio has already implemented a [DefaultTransformer], and as the default
/// [Transformer]. If you want to custom the transformation of
/// request/response data, you can provide a [Transformer] by your self, and
/// replace the [DefaultTransformer] by setting the [dio.Transformer].
abstract class Transformer {
/// `transformRequest` allows changes to the request data before it is
/// sent to the server, but **after** the [RequestInterceptor].
///
/// This is only applicable for request methods 'PUT', 'POST', and 'PATCH'
Future<String> transformRequest(RequestOptions options);
/// `transformResponse` allows changes to the response data before
/// it is passed to [ResponseInterceptor].
///
/// **Note**: As an agreement, you must return the [response]
/// when the Options.responseType is [ResponseType.stream].
Future transformResponse(RequestOptions options, ResponseBody response);
/// Deep encode the [Map<String, dynamic>] to percent-encoding.
/// It is mostly used with the "application/x-www-form-urlencoded" content-type.
static String urlEncodeMap(data) {
StringBuffer urlData = new StringBuffer("");
bool first = true;
void urlEncode(dynamic sub, String path) {
if (sub is List) {
for (int i = 0; i < sub.length; i++) {
urlEncode(sub[i],
"$path%5B${(sub[i] is Map || sub[i] is List) ? i : ''}%5D");
}
} else if (sub is Map) {
sub.forEach((k, v) {
if (path == "") {
urlEncode(v, "${Uri.encodeQueryComponent(k)}");
} else {
urlEncode(v, "$path%5B${Uri.encodeQueryComponent(k)}%5D");
}
});
} else {
if (!first) {
urlData.write("&");
}
first = false;
urlData.write("$path=${Uri.encodeQueryComponent(sub.toString())}");
}
}
urlEncode(data, "");
return urlData.toString();
}
}
/// The default [Transformer] for [Dio]. If you want to custom the transformation of
/// request/response data, you can provide a [Transformer] by your self, and
/// replace the [DefaultTransformer] by setting the [dio.Transformer].
typedef JsonDecodeCallback = dynamic Function(String);
class DefaultTransformer extends Transformer {
DefaultTransformer({this.jsonDecodeCallback});
JsonDecodeCallback jsonDecodeCallback;
Future<String> transformRequest(RequestOptions options) async {
var data = options.data ?? "";
if (data is! String) {
if (options.contentType.mimeType == ContentType.json.mimeType) {
return json.encode(options.data);
} else if (data is Map) {
return Transformer.urlEncodeMap(data);
}
}
return data.toString();
}
/// As an agreement, you must return the [response]
/// when the Options.responseType is [ResponseType.stream].
Future transformResponse(
RequestOptions options, ResponseBody response) async {
if (options.responseType == ResponseType.stream) {
return response;
}
int length = 0;
int received = 0;
bool showDownloadProgress = options.onReceiveProgress != null;
if (showDownloadProgress) {
length = int.parse(
response.headers.value(HttpHeaders.contentLengthHeader) ?? "-1");
}
Completer completer = new Completer();
Stream<List<int>> stream = response.stream.transform<List<int>>(
StreamTransformer.fromHandlers(handleData: (data, sink) {
sink.add(data);
if (showDownloadProgress) {
received += data.length;
options.onReceiveProgress(received, length);
}
}));
List<int> buffer = new List<int>();
StreamSubscription subscription;
subscription = stream.listen(
(element) => buffer.addAll(element),
onError: (e) => completer.completeError(e),
onDone: () => completer.complete(),
cancelOnError: true,
);
// ignore: unawaited_futures
options.cancelToken?.whenCancel?.then((_) {
return subscription.cancel();
});
if (options.receiveTimeout > 0) {
try {
await completer.future
.timeout(new Duration(milliseconds: options.receiveTimeout));
} on TimeoutException {
await subscription.cancel();
throw DioError(
request: options,
message: "Receiving data timeout[${options.receiveTimeout}ms]",
type: DioErrorType.RECEIVE_TIMEOUT,
);
}
} else {
await completer.future;
}
if (options.responseType == ResponseType.bytes) return buffer;
String responseBody;
if (options.responseDecoder != null) {
responseBody = options.responseDecoder(buffer, options, response..stream=null);
} else {
responseBody = utf8.decode(buffer, allowMalformed: true);
}
if (responseBody != null &&
responseBody.isNotEmpty &&
options.responseType == ResponseType.json &&
response.headers.contentType?.mimeType == ContentType.json.mimeType) {
if (jsonDecodeCallback != null) {
return jsonDecodeCallback(responseBody);
} else {
return json.decode(responseBody);
}
}
return responseBody;
}
}
| dio/package_src/lib/src/transformer.dart/0 | {'file_path': 'dio/package_src/lib/src/transformer.dart', 'repo_id': 'dio', 'token_count': 2016} |
import 'package:duck_duck_shop/domain.dart';
import 'package:duck_duck_shop/registry.dart';
import 'package:duck_duck_shop/widgets.dart';
import 'package:flutter/material.dart';
import '../../coordinators.dart';
class SplashPage extends StatefulWidget {
const SplashPage({Key key, @required this.isColdStart}) : super(key: key);
final bool isColdStart;
@override
_SplashPageState createState() => _SplashPageState();
}
class _SplashPageState extends State<SplashPage> {
Stream<String> _stream;
AuthRepository _auth;
@override
void initState() {
super.initState();
_auth = Registry.di.repository.auth;
_stream = _auth.onAuthStateChanged;
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: StreamBuilder<String>(
stream: _stream,
builder: (context, snapshot) {
if (snapshot.hasData) {
WidgetsBinding.instance.addPostFrameCallback(
(_) async {
await Coordinators.toShop(context);
},
);
}
return _Content(isColdStart: widget.isColdStart, auth: _auth);
},
),
);
}
}
class _Content extends StatefulWidget {
const _Content({Key key, @required this.isColdStart, @required this.auth}) : super(key: key);
final bool isColdStart;
final AuthRepository auth;
@override
_ContentState createState() => _ContentState();
}
class _ContentState extends State<_Content> {
bool isLoading;
@override
void initState() {
super.initState();
isLoading = widget.isColdStart;
if (widget.isColdStart) {
_onLogin();
}
}
@override
Widget build(BuildContext context) {
return Stack(
children: [
Positioned.fill(
top: null,
bottom: 124.0,
child: Builder(builder: (_) {
if (isLoading) {
return const Center(child: CircularProgressIndicator());
}
return Center(
child: FilledButton(
color: Colors.white,
onPressed: _onLogin,
child: Text(
'Continue with Google',
style: Theme.of(context).textTheme.bodyText1.copyWith(color: Colors.white),
),
),
);
}),
)
],
);
}
void _onLogin() async {
try {
setState(() => isLoading = true);
// TODO: move this out of here
await widget.auth.signIn();
} catch (e) {
// TODO: move this out of here
final message = e.toString();
if (message.isNotEmpty) {
print(message);
}
// TODO: move this out of here
await widget.auth.signOut();
if (!mounted) {
return;
}
setState(() => isLoading = false);
}
}
}
| duck_duck_shop/lib/screens/splash/splash_page.dart/0 | {'file_path': 'duck_duck_shop/lib/screens/splash/splash_page.dart', 'repo_id': 'duck_duck_shop', 'token_count': 1270} |
import 'dart:async';
import 'package:flutter/material.dart';
const zoneKey = Object();
void main() {
runZoned(
() => runApp(const MyApp()),
zoneValues: {zoneKey: 'Hello World'},
);
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final dynamic value = Zone.current[zoneKey];
return MaterialApp(
home: Scaffold(
body: Center(child: Text('$value')),
),
);
}
}
| e2e_zones/lib/main.dart/0 | {'file_path': 'e2e_zones/lib/main.dart', 'repo_id': 'e2e_zones', 'token_count': 193} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: public_member_api_docs
part of flutter_gpu;
base class ColorAttachment {
ColorAttachment({
this.loadAction = LoadAction.clear,
this.storeAction = StoreAction.store,
this.clearValue = const ui.Color(0x00000000),
required this.texture,
this.resolveTexture = null,
});
LoadAction loadAction;
StoreAction storeAction;
ui.Color clearValue;
Texture texture;
Texture? resolveTexture;
}
base class DepthStencilAttachment {
DepthStencilAttachment({
this.depthLoadAction = LoadAction.clear,
this.depthStoreAction = StoreAction.dontCare,
this.depthClearValue = 0.0,
this.stencilLoadAction = LoadAction.clear,
this.stencilStoreAction = StoreAction.dontCare,
this.stencilClearValue = 0,
required this.texture,
});
LoadAction depthLoadAction;
StoreAction depthStoreAction;
double depthClearValue;
LoadAction stencilLoadAction;
StoreAction stencilStoreAction;
int stencilClearValue;
Texture texture;
}
base class ColorBlendEquation {
ColorBlendEquation({
this.colorBlendOperation = BlendOperation.add,
this.sourceColorBlendFactor = BlendFactor.one,
this.destinationColorBlendFactor = BlendFactor.oneMinusSourceAlpha,
this.alphaBlendOperation = BlendOperation.add,
this.sourceAlphaBlendFactor = BlendFactor.one,
this.destinationAlphaBlendFactor = BlendFactor.oneMinusSourceAlpha,
});
BlendOperation colorBlendOperation;
BlendFactor sourceColorBlendFactor;
BlendFactor destinationColorBlendFactor;
BlendOperation alphaBlendOperation;
BlendFactor sourceAlphaBlendFactor;
BlendFactor destinationAlphaBlendFactor;
}
base class SamplerOptions {
SamplerOptions({
this.minFilter = MinMagFilter.nearest,
this.magFilter = MinMagFilter.nearest,
this.mipFilter = MipFilter.nearest,
this.widthAddressMode = SamplerAddressMode.clampToEdge,
this.heightAddressMode = SamplerAddressMode.clampToEdge,
});
MinMagFilter minFilter;
MinMagFilter magFilter;
MipFilter mipFilter;
SamplerAddressMode widthAddressMode;
SamplerAddressMode heightAddressMode;
}
base class RenderTarget {
const RenderTarget(
{this.colorAttachments = const <ColorAttachment>[],
this.depthStencilAttachment});
RenderTarget.singleColor(ColorAttachment colorAttachment,
{DepthStencilAttachment? depthStencilAttachment})
: this(
colorAttachments: [colorAttachment],
depthStencilAttachment: depthStencilAttachment);
final List<ColorAttachment> colorAttachments;
final DepthStencilAttachment? depthStencilAttachment;
}
base class RenderPass extends NativeFieldWrapperClass1 {
/// Creates a new RenderPass.
RenderPass._(CommandBuffer commandBuffer, RenderTarget renderTarget) {
_initialize();
String? error;
for (final (index, color) in renderTarget.colorAttachments.indexed) {
error = _setColorAttachment(
index,
color.loadAction.index,
color.storeAction.index,
color.clearValue.value,
color.texture,
color.resolveTexture);
if (error != null) {
throw Exception(error);
}
}
if (renderTarget.depthStencilAttachment != null) {
final ds = renderTarget.depthStencilAttachment!;
error = _setDepthStencilAttachment(
ds.depthLoadAction.index,
ds.depthStoreAction.index,
ds.depthClearValue,
ds.stencilLoadAction.index,
ds.stencilStoreAction.index,
ds.stencilClearValue,
ds.texture);
if (error != null) {
throw Exception(error);
}
}
error = _begin(commandBuffer);
if (error != null) {
throw Exception(error);
}
}
void bindPipeline(RenderPipeline pipeline) {
_bindPipeline(pipeline);
}
void bindVertexBuffer(BufferView bufferView, int vertexCount) {
bufferView.buffer._bindAsVertexBuffer(
this, bufferView.offsetInBytes, bufferView.lengthInBytes, vertexCount);
}
void bindIndexBuffer(
BufferView bufferView, IndexType indexType, int indexCount) {
bufferView.buffer._bindAsIndexBuffer(this, bufferView.offsetInBytes,
bufferView.lengthInBytes, indexType, indexCount);
}
void bindUniform(UniformSlot slot, BufferView bufferView) {
bool success = bufferView.buffer._bindAsUniform(
this, slot, bufferView.offsetInBytes, bufferView.lengthInBytes);
if (!success) {
throw Exception("Failed to bind uniform");
}
}
void bindTexture(UniformSlot slot, Texture texture,
{SamplerOptions? sampler}) {
if (sampler == null) {
sampler = SamplerOptions();
}
bool success = _bindTexture(
slot.shader,
slot.uniformName,
texture,
sampler.minFilter.index,
sampler.magFilter.index,
sampler.mipFilter.index,
sampler.widthAddressMode.index,
sampler.heightAddressMode.index);
if (!success) {
throw Exception("Failed to bind texture");
}
}
void clearBindings() {
_clearBindings();
}
void setColorBlendEnable(bool enable, {int colorAttachmentIndex = 0}) {
_setColorBlendEnable(colorAttachmentIndex, enable);
}
void setColorBlendEquation(ColorBlendEquation equation,
{int colorAttachmentIndex = 0}) {
_setColorBlendEquation(
colorAttachmentIndex,
equation.colorBlendOperation.index,
equation.sourceColorBlendFactor.index,
equation.destinationColorBlendFactor.index,
equation.alphaBlendOperation.index,
equation.sourceAlphaBlendFactor.index,
equation.destinationAlphaBlendFactor.index);
}
void setDepthWriteEnable(bool enable) {
_setDepthWriteEnable(enable);
}
void setDepthCompareOperation(CompareFunction compareFunction) {
_setDepthCompareOperation(compareFunction.index);
}
void draw() {
if (!_draw()) {
throw Exception("Failed to append draw");
}
}
/// Wrap with native counterpart.
@Native<Void Function(Handle)>(
symbol: 'InternalFlutterGpu_RenderPass_Initialize')
external void _initialize();
@Native<
Handle Function(Pointer<Void>, Int, Int, Int, Int, Pointer<Void>,
Handle)>(symbol: 'InternalFlutterGpu_RenderPass_SetColorAttachment')
external String? _setColorAttachment(
int colorAttachmentIndex,
int loadAction,
int storeAction,
int clearColor,
Texture texture,
Texture? resolveTexture);
@Native<
Handle Function(
Pointer<Void>, Int, Int, Float, Int, Int, Int, Pointer<Void>)>(
symbol: 'InternalFlutterGpu_RenderPass_SetDepthStencilAttachment')
external String? _setDepthStencilAttachment(
int depthLoadAction,
int depthStoreAction,
double depthClearValue,
int stencilLoadAction,
int stencilStoreAction,
int stencilClearValue,
Texture texture);
@Native<Handle Function(Pointer<Void>, Pointer<Void>)>(
symbol: 'InternalFlutterGpu_RenderPass_Begin')
external String? _begin(CommandBuffer commandBuffer);
@Native<Void Function(Pointer<Void>, Pointer<Void>)>(
symbol: 'InternalFlutterGpu_RenderPass_BindPipeline')
external void _bindPipeline(RenderPipeline pipeline);
@Native<Void Function(Pointer<Void>, Pointer<Void>, Int, Int, Int)>(
symbol: 'InternalFlutterGpu_RenderPass_BindVertexBufferDevice')
external void _bindVertexBufferDevice(DeviceBuffer buffer, int offsetInBytes,
int lengthInBytes, int vertexCount);
@Native<Void Function(Pointer<Void>, Pointer<Void>, Int, Int, Int)>(
symbol: 'InternalFlutterGpu_RenderPass_BindVertexBufferHost')
external void _bindVertexBufferHost(
HostBuffer buffer, int offsetInBytes, int lengthInBytes, int vertexCount);
@Native<Void Function(Pointer<Void>, Pointer<Void>, Int, Int, Int, Int)>(
symbol: 'InternalFlutterGpu_RenderPass_BindIndexBufferDevice')
external void _bindIndexBufferDevice(DeviceBuffer buffer, int offsetInBytes,
int lengthInBytes, int indexType, int indexCount);
@Native<Void Function(Pointer<Void>, Pointer<Void>, Int, Int, Int, Int)>(
symbol: 'InternalFlutterGpu_RenderPass_BindIndexBufferHost')
external void _bindIndexBufferHost(HostBuffer buffer, int offsetInBytes,
int lengthInBytes, int indexType, int indexCount);
@Native<
Bool Function(Pointer<Void>, Pointer<Void>, Handle, Pointer<Void>, Int,
Int)>(symbol: 'InternalFlutterGpu_RenderPass_BindUniformDevice')
external bool _bindUniformDevice(Shader shader, String uniformName,
DeviceBuffer buffer, int offsetInBytes, int lengthInBytes);
@Native<
Bool Function(Pointer<Void>, Pointer<Void>, Handle, Pointer<Void>, Int,
Int)>(symbol: 'InternalFlutterGpu_RenderPass_BindUniformHost')
external bool _bindUniformHost(Shader shader, String uniformName,
HostBuffer buffer, int offsetInBytes, int lengthInBytes);
@Native<
Bool Function(
Pointer<Void>,
Pointer<Void>,
Handle,
Pointer<Void>,
Int,
Int,
Int,
Int,
Int)>(symbol: 'InternalFlutterGpu_RenderPass_BindTexture')
external bool _bindTexture(
Shader shader,
String uniformName,
Texture texture,
int minFilter,
int magFilter,
int mipFilter,
int widthAddressMode,
int heightAddressMode);
@Native<Void Function(Pointer<Void>)>(
symbol: 'InternalFlutterGpu_RenderPass_ClearBindings')
external void _clearBindings();
@Native<Void Function(Pointer<Void>, Int, Bool)>(
symbol: 'InternalFlutterGpu_RenderPass_SetColorBlendEnable')
external void _setColorBlendEnable(int colorAttachmentIndex, bool enable);
@Native<Void Function(Pointer<Void>, Int, Int, Int, Int, Int, Int, Int)>(
symbol: 'InternalFlutterGpu_RenderPass_SetColorBlendEquation')
external void _setColorBlendEquation(
int colorAttachmentIndex,
int colorBlendOperation,
int sourceColorBlendFactor,
int destinationColorBlendFactor,
int alphaBlendOperation,
int sourceAlphaBlendFactor,
int destinationAlphaBlendFactor);
@Native<Void Function(Pointer<Void>, Bool)>(
symbol: 'InternalFlutterGpu_RenderPass_SetDepthWriteEnable')
external void _setDepthWriteEnable(bool enable);
@Native<Void Function(Pointer<Void>, Int)>(
symbol: 'InternalFlutterGpu_RenderPass_SetDepthCompareOperation')
external void _setDepthCompareOperation(int compareOperation);
@Native<Bool Function(Pointer<Void>)>(
symbol: 'InternalFlutterGpu_RenderPass_Draw')
external bool _draw();
}
| engine/lib/gpu/lib/src/render_pass.dart/0 | {'file_path': 'engine/lib/gpu/lib/src/render_pass.dart', 'repo_id': 'engine', 'token_count': 3901} |
# For more information on test and runner configurations:
#
# * https://github.com/dart-lang/test/blob/master/pkgs/test/doc/configuration.md#platforms
platforms:
- firefox
- vm
| engine/lib/web_ui/dart_test_firefox.yaml/0 | {'file_path': 'engine/lib/web_ui/dart_test_firefox.yaml', 'repo_id': 'engine', 'token_count': 62} |
// 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;
abstract class PathMetrics extends collection.IterableBase<PathMetric> {
@override
Iterator<PathMetric> get iterator;
}
abstract class PathMetricIterator implements Iterator<PathMetric> {
@override
PathMetric get current;
@override
bool moveNext();
}
abstract class PathMetric {
double get length;
int get contourIndex;
Tangent? getTangentForOffset(double distance);
Path extractPath(double start, double end, {bool startWithMoveTo = true});
bool get isClosed;
}
class Tangent {
const Tangent(this.position, this.vector);
factory Tangent.fromAngle(Offset position, double angle) {
return Tangent(position, Offset(math.cos(angle), math.sin(angle)));
}
final Offset position;
final Offset vector;
// flip the sign to be consistent with [Path.arcTo]'s `sweepAngle`
double get angle => -math.atan2(vector.dy, vector.dx);
}
| engine/lib/web_ui/lib/path_metrics.dart/0 | {'file_path': 'engine/lib/web_ui/lib/path_metrics.dart', 'repo_id': 'engine', 'token_count': 324} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:typed_data';
import 'package:ui/src/engine.dart';
import 'package:ui/ui_web/src/ui_web.dart' as ui_web;
// This URL was found by using the Google Fonts Developer API to find the URL
// for Roboto. The API warns that this URL is not stable. In order to update
// this, list out all of the fonts and find the URL for the regular
// Roboto font. The API reference is here:
// https://developers.google.com/fonts/docs/developer_api
const String _robotoUrl =
'https://fonts.gstatic.com/s/roboto/v20/KFOmCnqEu92Fr1Me5WZLCzYlKw.ttf';
/// Manages the fonts used in the Skia-based backend.
class SkiaFontCollection implements FlutterFontCollection {
final Set<String> _downloadedFontFamilies = <String>{};
@override
late FontFallbackManager fontFallbackManager =
FontFallbackManager(SkiaFallbackRegistry(this));
/// Fonts that started the download process, but are not yet registered.
///
/// /// Once downloaded successfully, this map is cleared and the resulting
/// [UnregisteredFont]s are added to [_registeredFonts].
final List<UnregisteredFont> _unregisteredFonts = <UnregisteredFont>[];
final List<RegisteredFont> _registeredFonts = <RegisteredFont>[];
final List<RegisteredFont> registeredFallbackFonts = <RegisteredFont>[];
/// Returns fonts that have been downloaded, registered, and parsed.
///
/// This should only be used in tests.
List<RegisteredFont>? get debugRegisteredFonts {
List<RegisteredFont>? result;
assert(() {
result = _registeredFonts;
return true;
}());
return result;
}
final Map<String, List<SkFont>> familyToFontMap = <String, List<SkFont>>{};
void _registerWithFontProvider() {
if (_fontProvider != null) {
_fontProvider!.delete();
_fontProvider = null;
skFontCollection?.delete();
skFontCollection = null;
}
_fontProvider = canvasKit.TypefaceFontProvider.Make();
skFontCollection = canvasKit.FontCollection.Make();
skFontCollection!.enableFontFallback();
skFontCollection!.setDefaultFontManager(_fontProvider);
familyToFontMap.clear();
for (final RegisteredFont font in _registeredFonts) {
_fontProvider!.registerFont(font.bytes, font.family);
familyToFontMap
.putIfAbsent(font.family, () => <SkFont>[])
.add(SkFont(font.typeface));
}
for (final RegisteredFont font in registeredFallbackFonts) {
_fontProvider!.registerFont(font.bytes, font.family);
familyToFontMap
.putIfAbsent(font.family, () => <SkFont>[])
.add(SkFont(font.typeface));
}
}
@override
Future<bool> loadFontFromList(Uint8List list, {String? fontFamily}) async {
if (fontFamily == null) {
fontFamily = _readActualFamilyName(list);
if (fontFamily == null) {
printWarning('Failed to read font family name. Aborting font load.');
return false;
}
}
// Make sure CanvasKit is actually loaded
await renderer.initialize();
final SkTypeface? typeface =
canvasKit.Typeface.MakeFreeTypeFaceFromData(list.buffer);
if (typeface != null) {
_registeredFonts.add(RegisteredFont(list, fontFamily, typeface));
_registerWithFontProvider();
} else {
printWarning('Failed to parse font family "$fontFamily"');
return false;
}
return true;
}
/// Loads fonts from `FontManifest.json`.
@override
Future<AssetFontsResult> loadAssetFonts(FontManifest manifest) async {
final List<Future<FontDownloadResult>> pendingDownloads = <Future<FontDownloadResult>>[];
bool loadedRoboto = false;
for (final FontFamily family in manifest.families) {
if (family.name == 'Roboto') {
loadedRoboto = true;
}
for (final FontAsset fontAsset in family.fontAssets) {
final String url = ui_web.assetManager.getAssetUrl(fontAsset.asset);
pendingDownloads.add(_downloadFont(fontAsset.asset, url, family.name));
}
}
/// We need a default fallback font for CanvasKit, in order to avoid
/// crashing while laying out text with an unregistered font. We chose
/// Roboto to match Android.
if (!loadedRoboto) {
// Download Roboto and add it to the font buffers.
pendingDownloads.add(_downloadFont('Roboto', _robotoUrl, 'Roboto'));
}
final Map<String, FontLoadError> fontFailures = <String, FontLoadError>{};
final List<(String, UnregisteredFont)> downloadedFonts = <(String, UnregisteredFont)>[];
for (final FontDownloadResult result in await Future.wait(pendingDownloads)) {
if (result.font != null) {
downloadedFonts.add((result.assetName, result.font!));
} else {
fontFailures[result.assetName] = result.error!;
}
}
// Make sure CanvasKit is actually loaded
await renderer.initialize();
final List<String> loadedFonts = <String>[];
for (final (String assetName, UnregisteredFont unregisteredFont) in downloadedFonts) {
final Uint8List bytes = unregisteredFont.bytes.asUint8List();
final SkTypeface? typeface =
canvasKit.Typeface.MakeFreeTypeFaceFromData(bytes.buffer);
if (typeface != null) {
loadedFonts.add(assetName);
_registeredFonts.add(RegisteredFont(bytes, unregisteredFont.family, typeface));
} else {
printWarning('Failed to load font ${unregisteredFont.family} at ${unregisteredFont.url}');
printWarning('Verify that ${unregisteredFont.url} contains a valid font.');
fontFailures[assetName] = FontInvalidDataError(unregisteredFont.url);
}
}
registerDownloadedFonts();
return AssetFontsResult(loadedFonts, fontFailures);
}
void registerDownloadedFonts() {
RegisteredFont? makeRegisterFont(ByteBuffer buffer, String url, String family) {
final Uint8List bytes = buffer.asUint8List();
final SkTypeface? typeface =
canvasKit.Typeface.MakeFreeTypeFaceFromData(bytes.buffer);
if (typeface != null) {
return RegisteredFont(bytes, family, typeface);
} else {
printWarning('Failed to load font $family at $url');
printWarning('Verify that $url contains a valid font.');
return null;
}
}
for (final UnregisteredFont unregisteredFont in _unregisteredFonts) {
final RegisteredFont? registeredFont = makeRegisterFont(
unregisteredFont.bytes,
unregisteredFont.url,
unregisteredFont.family
);
if (registeredFont != null) {
_registeredFonts.add(registeredFont);
}
}
_unregisteredFonts.clear();
_registerWithFontProvider();
}
Future<FontDownloadResult> _downloadFont(
String assetName,
String url,
String fontFamily
) async {
final ByteBuffer fontData;
// Try to get the font leniently. Do not crash the app when failing to
// fetch the font in the spirit of "gradual degradation of functionality".
try {
final HttpFetchResponse response = await httpFetch(url);
if (!response.hasPayload) {
printWarning('Font family $fontFamily not found (404) at $url');
return FontDownloadResult.fromError(assetName, FontNotFoundError(url));
}
fontData = await response.asByteBuffer();
} catch (e) {
printWarning('Failed to load font $fontFamily at $url');
printWarning(e.toString());
return FontDownloadResult.fromError(assetName, FontDownloadError(url, e));
}
_downloadedFontFamilies.add(fontFamily);
return FontDownloadResult.fromFont(assetName, UnregisteredFont(fontData, url, fontFamily));
}
String? _readActualFamilyName(Uint8List bytes) {
final SkFontMgr tmpFontMgr =
canvasKit.FontMgr.FromData(<Uint8List>[bytes])!;
final String? actualFamily = tmpFontMgr.getFamilyName(0);
tmpFontMgr.delete();
return actualFamily;
}
TypefaceFontProvider? _fontProvider;
SkFontCollection? skFontCollection;
@override
void clear() {}
@override
void debugResetFallbackFonts() {
fontFallbackManager = FontFallbackManager(SkiaFallbackRegistry(this));
registeredFallbackFonts.clear();
}
}
/// Represents a font that has been registered.
class RegisteredFont {
RegisteredFont(this.bytes, this.family, this.typeface) {
// This is a hack which causes Skia to cache the decoded font.
final SkFont skFont = SkFont(typeface);
skFont.getGlyphBounds(<int>[0], null, null);
}
/// The font family name for this font.
final String family;
/// The byte data for this font.
final Uint8List bytes;
/// The [SkTypeface] created from this font's [bytes].
///
/// This is used to determine which code points are supported by this font.
final SkTypeface typeface;
}
/// Represents a font that has been downloaded but not registered.
class UnregisteredFont {
const UnregisteredFont(this.bytes, this.url, this.family);
final ByteBuffer bytes;
final String url;
final String family;
}
class FontDownloadResult {
FontDownloadResult.fromFont(this.assetName, UnregisteredFont this.font) : error = null;
FontDownloadResult.fromError(this.assetName, FontLoadError this.error) : font = null;
final String assetName;
final UnregisteredFont? font;
final FontLoadError? error;
}
class SkiaFallbackRegistry implements FallbackFontRegistry {
SkiaFallbackRegistry(this.fontCollection);
SkiaFontCollection fontCollection;
@override
List<int> getMissingCodePoints(List<int> codeUnits, List<String> fontFamilies) {
final List<SkFont> fonts = <SkFont>[];
for (final String font in fontFamilies) {
final List<SkFont>? typefacesForFamily = fontCollection.familyToFontMap[font];
if (typefacesForFamily != null) {
fonts.addAll(typefacesForFamily);
}
}
final List<bool> codePointsSupported =
List<bool>.filled(codeUnits.length, false);
final String testString = String.fromCharCodes(codeUnits);
for (final SkFont font in fonts) {
final Uint16List glyphs = font.getGlyphIDs(testString);
assert(glyphs.length == codePointsSupported.length);
for (int i = 0; i < glyphs.length; i++) {
codePointsSupported[i] |= glyphs[i] != 0;
}
}
final List<int> missingCodeUnits = <int>[];
for (int i = 0; i < codePointsSupported.length; i++) {
if (!codePointsSupported[i]) {
missingCodeUnits.add(codeUnits[i]);
}
}
return missingCodeUnits;
}
@override
Future<void> loadFallbackFont(String familyName, String url) async {
final ByteBuffer buffer = await httpFetchByteBuffer(url);
final SkTypeface? typeface =
canvasKit.Typeface.MakeFreeTypeFaceFromData(buffer);
if (typeface == null) {
printWarning('Failed to parse fallback font $familyName as a font.');
return;
}
fontCollection.registeredFallbackFonts.add(
RegisteredFont(buffer.asUint8List(), familyName, typeface)
);
}
@override
void updateFallbackFontFamilies(List<String> families) {
fontCollection.registerDownloadedFonts();
}
}
| engine/lib/web_ui/lib/src/engine/canvaskit/fonts.dart/0 | {'file_path': 'engine/lib/web_ui/lib/src/engine/canvaskit/fonts.dart', 'repo_id': 'engine', 'token_count': 3920} |
// 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 '../scene_painting.dart';
import 'canvas.dart';
import 'canvaskit_api.dart';
import 'image.dart';
import 'native_memory.dart';
import 'renderer.dart';
import 'surface.dart';
/// Implements [ui.Picture] on top of [SkPicture].
class CkPicture implements ScenePicture {
CkPicture(SkPicture skPicture) {
_ref = UniqueRef<SkPicture>(this, skPicture, 'Picture');
}
late final UniqueRef<SkPicture> _ref;
SkPicture get skiaObject => _ref.nativeObject;
@override
ui.Rect get cullRect => fromSkRect(skiaObject.cullRect());
@override
int get approximateBytesUsed => skiaObject.approximateBytesUsed();
@override
bool get debugDisposed {
bool? result;
assert(() {
result = _isDisposed;
return true;
}());
if (result != null) {
return result!;
}
throw StateError(
'Picture.debugDisposed is only available when asserts are enabled.');
}
/// This is set to true when [dispose] is called and is never reset back to
/// false.
///
/// This extra flag is necessary on top of [rawSkiaObject] because
/// [rawSkiaObject] being null does not indicate permanent deletion.
bool _isDisposed = false;
/// The stack trace taken when [dispose] was called.
///
/// Returns null if [dispose] has not been called. Returns null in non-debug
/// modes.
StackTrace? _debugDisposalStackTrace;
/// Throws an [AssertionError] if this picture was disposed.
///
/// The [mainErrorMessage] is used as the first line in the error message. It
/// is expected to end with a period, e.g. "Failed to draw picture." The full
/// message will also explain that the error is due to the fact that the
/// picture was disposed and include the stack trace taken when the picture
/// was disposed.
bool debugCheckNotDisposed(String mainErrorMessage) {
if (_isDisposed) {
throw StateError(
'$mainErrorMessage\n'
'The picture has been disposed. When the picture was disposed the '
'stack trace was:\n'
'$_debugDisposalStackTrace',
);
}
return true;
}
@override
void dispose() {
assert(debugCheckNotDisposed('Cannot dispose picture.'));
assert(() {
_debugDisposalStackTrace = StackTrace.current;
return true;
}());
ui.Picture.onDispose?.call(this);
_isDisposed = true;
_ref.dispose();
}
@override
Future<ui.Image> toImage(int width, int height) async {
return toImageSync(width, height);
}
@override
CkImage toImageSync(int width, int height) {
assert(debugCheckNotDisposed('Cannot convert picture to image.'));
final Surface surface = CanvasKitRenderer.instance.pictureToImageSurface;
final CkSurface ckSurface = surface
.createOrUpdateSurface(ui.Size(width.toDouble(), height.toDouble()));
final CkCanvas ckCanvas = ckSurface.getCanvas();
ckCanvas.clear(const ui.Color(0x00000000));
ckCanvas.drawPicture(this);
final SkImage skImage = ckSurface.surface.makeImageSnapshot();
final SkImageInfo imageInfo = SkImageInfo(
alphaType: canvasKit.AlphaType.Premul,
colorType: canvasKit.ColorType.RGBA_8888,
colorSpace: SkColorSpaceSRGB,
width: width.toDouble(),
height: height.toDouble(),
);
final Uint8List pixels = skImage.readPixels(0, 0, imageInfo);
final SkImage? rasterImage =
canvasKit.MakeImage(imageInfo, pixels, (4 * width).toDouble());
if (rasterImage == null) {
throw StateError('Unable to convert image pixels into SkImage.');
}
return CkImage(rasterImage);
}
}
| engine/lib/web_ui/lib/src/engine/canvaskit/picture.dart/0 | {'file_path': 'engine/lib/web_ui/lib/src/engine/canvaskit/picture.dart', 'repo_id': 'engine', 'token_count': 1327} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:ui/ui.dart' as ui;
import '../engine.dart';
class EngineFlutterDisplay extends ui.Display {
EngineFlutterDisplay({
required this.id,
required this.size,
required this.refreshRate,
});
/// The single [EngineFlutterDisplay] that the web page is rendered on.
static EngineFlutterDisplay get instance => _instance;
static final EngineFlutterDisplay _instance = EngineFlutterDisplay(
id: 0,
size: ui.Size(domWindow.screen?.width ?? 0, domWindow.screen?.height ?? 0),
refreshRate: 60,
);
@override
final int id;
// TODO(mdebbar): https://github.com/flutter/flutter/issues/133562
// `size` and `refreshRate` should be kept up-to-date with the
// browser. E.g. the window could be resized or moved to another display with
// a different refresh rate.
@override
final ui.Size size;
@override
final double refreshRate;
@override
double get devicePixelRatio =>
_debugDevicePixelRatioOverride ?? browserDevicePixelRatio;
/// The real device pixel ratio of the browser.
///
/// This value cannot be overriden by tests, for example.
double get browserDevicePixelRatio {
final double ratio = domWindow.devicePixelRatio;
// Guard against WebOS returning 0.
return (ratio == 0.0) ? 1.0 : ratio;
}
/// Overrides the default device pixel ratio.
///
/// This is useful in tests to emulate screens of different dimensions.
///
/// Passing `null` resets the device pixel ratio to the browser's default.
void debugOverrideDevicePixelRatio(double? value) {
_debugDevicePixelRatioOverride = value;
}
double? _debugDevicePixelRatioOverride;
}
/// Controls the screen orientation using the browser's screen orientation API.
class ScreenOrientation {
const ScreenOrientation();
static ScreenOrientation get instance => _instance;
static const ScreenOrientation _instance = ScreenOrientation();
static const String lockTypeAny = 'any';
static const String lockTypeNatural = 'natural';
static const String lockTypeLandscape = 'landscape';
static const String lockTypePortrait = 'portrait';
static const String lockTypePortraitPrimary = 'portrait-primary';
static const String lockTypePortraitSecondary = 'portrait-secondary';
static const String lockTypeLandscapePrimary = 'landscape-primary';
static const String lockTypeLandscapeSecondary = 'landscape-secondary';
/// Sets preferred screen orientation.
///
/// Specifies the set of orientations the application interface can be
/// displayed in.
///
/// The [orientations] argument is a list of DeviceOrientation values.
/// The empty list uses Screen unlock api and causes the application to
/// defer to the operating system default.
///
/// See w3c screen api: https://www.w3.org/TR/screen-orientation/
Future<bool> setPreferredOrientation(List<dynamic> orientations) async {
final DomScreen? screen = domWindow.screen;
if (screen != null) {
final DomScreenOrientation? screenOrientation = screen.orientation;
if (screenOrientation != null) {
if (orientations.isEmpty) {
screenOrientation.unlock();
return true;
} else {
final String? lockType =
_deviceOrientationToLockType(orientations.first as String?);
if (lockType != null) {
try {
await screenOrientation.lock(lockType);
return true;
} catch (_) {
// On Chrome desktop an error with 'not supported on this device
// error' is fired.
return Future<bool>.value(false);
}
}
}
}
}
// API is not supported on this browser return false.
return false;
}
// Converts device orientation to w3c OrientationLockType enum.
//
// See also: https://developer.mozilla.org/en-US/docs/Web/API/ScreenOrientation/lock
static String? _deviceOrientationToLockType(String? deviceOrientation) {
switch (deviceOrientation) {
case 'DeviceOrientation.portraitUp':
return lockTypePortraitPrimary;
case 'DeviceOrientation.portraitDown':
return lockTypePortraitSecondary;
case 'DeviceOrientation.landscapeLeft':
return lockTypeLandscapePrimary;
case 'DeviceOrientation.landscapeRight':
return lockTypeLandscapeSecondary;
default:
return null;
}
}
}
| engine/lib/web_ui/lib/src/engine/display.dart/0 | {'file_path': 'engine/lib/web_ui/lib/src/engine/display.dart', 'repo_id': 'engine', 'token_count': 1527} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:ui/ui.dart' as ui;
import '../color_filter.dart';
import '../dom.dart';
import '../embedder.dart';
import '../util.dart';
import '../vector_math.dart';
import 'shaders/shader.dart';
import 'surface.dart';
import 'surface_stats.dart';
/// A surface that applies an [imageFilter] to its children.
class PersistedImageFilter extends PersistedContainerSurface
implements ui.ImageFilterEngineLayer {
PersistedImageFilter(PersistedImageFilter? super.oldLayer, this.filter, this.offset);
final ui.ImageFilter filter;
final ui.Offset offset;
@override
void recomputeTransformAndClip() {
transform = parent!.transform;
final double dx = offset.dx;
final double dy = offset.dy;
if (dx != 0.0 || dy != 0.0) {
transform = transform!.clone();
transform!.translate(dx, dy);
}
projectedClip = null;
}
/// Cached inverse of transform on this node. Unlike transform, this
/// Matrix only contains local transform (not chain multiplied since root).
Matrix4? _localTransformInverse;
@override
Matrix4 get localTransformInverse => _localTransformInverse ??=
Matrix4.translationValues(-offset.dx, -offset.dy, 0);
DomElement? _svgFilter;
@override
DomElement? get childContainer => _childContainer;
DomElement? _childContainer;
@override
void adoptElements(PersistedImageFilter oldSurface) {
super.adoptElements(oldSurface);
_svgFilter = oldSurface._svgFilter;
_childContainer = oldSurface._childContainer;
oldSurface._svgFilter = null;
oldSurface._childContainer = null;
}
@override
void discard() {
super.discard();
flutterViewEmbedder.removeResource(_svgFilter);
_svgFilter = null;
_childContainer = null;
}
@override
DomElement createElement() {
final DomElement element = defaultCreateElement('flt-image-filter');
final DomElement container = defaultCreateElement('flt-image-filter-interior');
if (debugExplainSurfaceStats) {
// This creates an additional interior element. Count it too.
surfaceStatsFor(this).allocatedDomNodeCount++;
}
setElementStyle(container, 'position', 'absolute');
setElementStyle(container, 'transform-origin', '0 0 0');
setElementStyle(element, 'position', 'absolute');
setElementStyle(element, 'transform-origin', '0 0 0');
_childContainer = container;
element.appendChild(container);
return element;
}
@override
void apply() {
EngineImageFilter backendFilter;
if (filter is ui.ColorFilter) {
backendFilter = createHtmlColorFilter(filter as EngineColorFilter)!;
} else {
backendFilter = filter as EngineImageFilter;
}
flutterViewEmbedder.removeResource(_svgFilter);
_svgFilter = null;
if (backendFilter is ModeHtmlColorFilter) {
_svgFilter = backendFilter.makeSvgFilter(rootElement);
/// Some blendModes do not make an svgFilter. See [EngineHtmlColorFilter.makeSvgFilter()]
if (_svgFilter == null) {
return;
}
} else if (backendFilter is MatrixHtmlColorFilter) {
_svgFilter = backendFilter.makeSvgFilter(rootElement);
}
_childContainer!.style.filter = backendFilter.filterAttribute;
_childContainer!.style.transform = backendFilter.transformAttribute;
rootElement!.style
..left = '${offset.dx}px'
..top = '${offset.dy}px';
}
@override
void update(PersistedImageFilter oldSurface) {
super.update(oldSurface);
if (oldSurface.filter != filter || oldSurface.offset != offset) {
apply();
}
}
}
| engine/lib/web_ui/lib/src/engine/html/image_filter.dart/0 | {'file_path': 'engine/lib/web_ui/lib/src/engine/html/image_filter.dart', 'repo_id': 'engine', 'token_count': 1255} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:typed_data';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' as ui;
// This file implements a SceneBuilder and Scene that works with any renderer
// implementation that provides:
// * A `ui.Canvas` that conforms to `SceneCanvas`
// * A `ui.Picture` that conforms to `ScenePicture`
// * A `ui.ImageFilter` that conforms to `SceneImageFilter`
//
// These contain a few augmentations to the normal `dart:ui` API that provide
// additional sizing information that the scene builder uses to determine how
// these object might occlude one another.
class EngineScene implements ui.Scene {
EngineScene(this.rootLayer);
final EngineRootLayer rootLayer;
// We keep a refcount here because this can be asynchronously rendered, so we
// don't necessarily want to dispose immediately when the user calls dispose.
// Instead, we need to stay alive until we're done rendering.
int _refCount = 1;
void beginRender() {
assert(_refCount > 0);
_refCount++;
}
void endRender() {
_refCount--;
_disposeIfNeeded();
}
@override
void dispose() {
_refCount--;
_disposeIfNeeded();
}
void _disposeIfNeeded() {
assert(_refCount >= 0);
if (_refCount == 0) {
rootLayer.dispose();
}
}
@override
Future<ui.Image> toImage(int width, int height) async {
return toImageSync(width, height);
}
@override
ui.Image toImageSync(int width, int height) {
final ui.PictureRecorder recorder = ui.PictureRecorder();
final ui.Rect canvasRect = ui.Rect.fromLTWH(0, 0, width.toDouble(), height.toDouble());
final ui.Canvas canvas = ui.Canvas(recorder, canvasRect);
// Only rasterizes the picture slices.
for (final PictureSlice slice in rootLayer.slices.whereType<PictureSlice>()) {
canvas.drawPicture(slice.picture);
}
return recorder.endRecording().toImageSync(width, height);
}
}
class EngineSceneBuilder implements ui.SceneBuilder {
LayerBuilder currentBuilder = LayerBuilder.rootLayer();
@override
void addPerformanceOverlay(int enabledOptions, ui.Rect bounds) {
// We don't plan to implement this on the web.
throw UnimplementedError();
}
@override
void addPicture(
ui.Offset offset,
ui.Picture picture, {
bool isComplexHint = false,
bool willChangeHint = false
}) {
currentBuilder.addPicture(
offset,
picture,
isComplexHint:
isComplexHint,
willChangeHint: willChangeHint
);
}
@override
void addPlatformView(
int viewId, {
ui.Offset offset = ui.Offset.zero,
double width = 0.0,
double height = 0.0
}) {
currentBuilder.addPlatformView(
viewId,
offset: offset,
width: width,
height: height
);
}
@override
void addRetained(ui.EngineLayer retainedLayer) {
currentBuilder.mergeLayer(retainedLayer as PictureEngineLayer);
}
@override
void addTexture(
int textureId, {
ui.Offset offset = ui.Offset.zero,
double width = 0.0,
double height = 0.0,
bool freeze = false,
ui.FilterQuality filterQuality = ui.FilterQuality.low
}) {
// addTexture is not implemented on web.
}
@override
ui.BackdropFilterEngineLayer pushBackdropFilter(
ui.ImageFilter filter, {
ui.BlendMode blendMode = ui.BlendMode.srcOver,
ui.BackdropFilterEngineLayer? oldLayer
}) => pushLayer<BackdropFilterLayer>(
BackdropFilterLayer(),
BackdropFilterOperation(filter, blendMode),
);
@override
ui.ClipPathEngineLayer pushClipPath(
ui.Path path, {
ui.Clip clipBehavior = ui.Clip.antiAlias,
ui.ClipPathEngineLayer? oldLayer
}) => pushLayer<ClipPathLayer>(
ClipPathLayer(),
ClipPathOperation(path, clipBehavior),
);
@override
ui.ClipRRectEngineLayer pushClipRRect(
ui.RRect rrect, {
required ui.Clip clipBehavior,
ui.ClipRRectEngineLayer? oldLayer
}) => pushLayer<ClipRRectLayer>(
ClipRRectLayer(),
ClipRRectOperation(rrect, clipBehavior)
);
@override
ui.ClipRectEngineLayer pushClipRect(
ui.Rect rect, {
ui.Clip clipBehavior = ui.Clip.antiAlias,
ui.ClipRectEngineLayer? oldLayer
}) {
return pushLayer<ClipRectLayer>(
ClipRectLayer(),
ClipRectOperation(rect, clipBehavior)
);
}
@override
ui.ColorFilterEngineLayer pushColorFilter(
ui.ColorFilter filter, {
ui.ColorFilterEngineLayer? oldLayer
}) => pushLayer<ColorFilterLayer>(
ColorFilterLayer(),
ColorFilterOperation(filter),
);
@override
ui.ImageFilterEngineLayer pushImageFilter(
ui.ImageFilter filter, {
ui.Offset offset = ui.Offset.zero,
ui.ImageFilterEngineLayer? oldLayer
}) => pushLayer<ImageFilterLayer>(
ImageFilterLayer(),
ImageFilterOperation(filter, offset),
);
@override
ui.OffsetEngineLayer pushOffset(
double dx,
double dy, {
ui.OffsetEngineLayer? oldLayer
}) => pushLayer<OffsetLayer>(
OffsetLayer(),
OffsetOperation(dx, dy)
);
@override
ui.OpacityEngineLayer pushOpacity(int alpha, {
ui.Offset offset = ui.Offset.zero,
ui.OpacityEngineLayer? oldLayer
}) => pushLayer<OpacityLayer>(
OpacityLayer(),
OpacityOperation(alpha, offset),
);
@override
ui.ShaderMaskEngineLayer pushShaderMask(
ui.Shader shader,
ui.Rect maskRect,
ui.BlendMode blendMode, {
ui.ShaderMaskEngineLayer? oldLayer,
ui.FilterQuality filterQuality = ui.FilterQuality.low
}) => pushLayer<ShaderMaskLayer>(
ShaderMaskLayer(),
ShaderMaskOperation(shader, maskRect, blendMode)
);
@override
ui.TransformEngineLayer pushTransform(
Float64List matrix4, {
ui.TransformEngineLayer? oldLayer
}) => pushLayer<TransformLayer>(
TransformLayer(),
TransformOperation(matrix4),
);
@override
void setCheckerboardOffscreenLayers(bool checkerboard) {
// Not implemented on web
}
@override
void setCheckerboardRasterCacheImages(bool checkerboard) {
// Not implemented on web
}
@override
void setProperties(
double width,
double height,
double insetTop,
double insetRight,
double insetBottom,
double insetLeft,
bool focusable
) {
// Not implemented on web
}
@override
void setRasterizerTracingThreshold(int frameInterval) {
// Not implemented on web
}
@override
ui.Scene build() {
while (currentBuilder.parent != null) {
pop();
}
final PictureEngineLayer rootLayer = currentBuilder.build();
return EngineScene(rootLayer as EngineRootLayer);
}
@override
void pop() {
final PictureEngineLayer layer = currentBuilder.build();
final LayerBuilder? parentBuilder = currentBuilder.parent;
if (parentBuilder == null) {
throw StateError('Popped too many times.');
}
currentBuilder = parentBuilder;
currentBuilder.mergeLayer(layer);
}
T pushLayer<T extends PictureEngineLayer>(T layer, LayerOperation operation) {
currentBuilder = LayerBuilder.childLayer(
parent: currentBuilder,
layer: layer,
operation: operation
);
return layer;
}
}
| engine/lib/web_ui/lib/src/engine/scene_builder.dart/0 | {'file_path': 'engine/lib/web_ui/lib/src/engine/scene_builder.dart', 'repo_id': 'engine', 'token_count': 2637} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:meta/meta.dart';
import '../browser_detection.dart';
import '../dom.dart';
import 'semantics.dart';
/// The maximum [semanticsActivationAttempts] before we give up waiting for
/// the user to enable semantics.
///
/// This number is arbitrary and can be adjusted if it doesn't work well.
const int kMaxSemanticsActivationAttempts = 20;
/// After an event related to semantics activation has been received, we consume
/// the consecutive events on the engine. Do not send them to the framework.
/// For example when a 'mousedown' targeting a placeholder received following
/// 'mouseup' is also not sent to the framework.
/// Otherwise these events can cause unintended gestures on the framework side.
const Duration _periodToConsumeEvents = Duration(milliseconds: 300);
/// The message in the label for the placeholder element used to enable
/// accessibility.
///
/// This uses US English as the default message. Set this value prior to
/// calling `runApp` to translate to another language.
String placeholderMessage = 'Enable accessibility';
/// A helper for [EngineSemanticsOwner].
///
/// [SemanticsHelper] prepares and placeholder to enable semantics.
///
/// It decides if an event is purely semantics enabling related or a regular
/// event which should be forwarded to the framework.
///
/// It does this by using a [SemanticsEnabler]. The [SemanticsEnabler]
/// implementation is chosen using form factor type.
///
/// See [DesktopSemanticsEnabler], [MobileSemanticsEnabler].
class SemanticsHelper {
SemanticsEnabler _semanticsEnabler =
isDesktop ? DesktopSemanticsEnabler() : MobileSemanticsEnabler();
@visibleForTesting
set semanticsEnabler(SemanticsEnabler semanticsEnabler) {
_semanticsEnabler = semanticsEnabler;
}
bool shouldEnableSemantics(DomEvent event) {
return _semanticsEnabler.shouldEnableSemantics(event);
}
DomElement prepareAccessibilityPlaceholder() {
return _semanticsEnabler.prepareAccessibilityPlaceholder();
}
/// Stops waiting for the user to enable semantics and removes the
/// placeholder.
///
/// This is used when semantics is enabled programmatically and therefore the
/// placehodler is no longer needed.
void dispose() {
_semanticsEnabler.dispose();
}
}
@visibleForTesting
abstract class SemanticsEnabler {
/// Whether to enable semantics.
///
/// Semantics should be enabled if the web engine is no longer waiting for
/// extra signals from the user events. See [isWaitingToEnableSemantics].
///
/// Or if the received [DomEvent] is suitable/enough for enabling the
/// semantics. See [tryEnableSemantics].
bool shouldEnableSemantics(DomEvent event) {
if (!isWaitingToEnableSemantics) {
// Forward to framework as normal.
return true;
} else {
return tryEnableSemantics(event);
}
}
/// Attempts to activate semantics.
///
/// Returns true if the `event` is not related to semantics activation and
/// should be forwarded to the framework.
bool tryEnableSemantics(DomEvent event);
/// Creates the placeholder for accessibility.
///
/// Puts it inside the glasspane.
///
/// On focus the element announces that accessibility can be enabled by
/// tapping/clicking. (Announcement depends on the assistive technology)
DomElement prepareAccessibilityPlaceholder();
/// Whether platform is still considering enabling semantics.
///
/// At this stage a relevant set of events are always assessed to see if
/// they activate the semantics.
///
/// If not they are sent to framework as normal events.
bool get isWaitingToEnableSemantics;
/// Stops waiting for the user to enable semantics and removes the placeholder.
void dispose();
}
/// The desktop semantics enabler uses a simpler strategy compared to mobile.
///
/// A placeholder element is created completely outside the view and is not
/// reachable via touch or mouse. Assistive technology can still find it either
/// using keyboard shortcuts or via next/previous touch gesture (for touch
/// screens). This simplification removes the need for pointer event
/// disambiguation or timers. The placeholder simply waits for a click event
/// and enables semantics.
@visibleForTesting
class DesktopSemanticsEnabler extends SemanticsEnabler {
/// A temporary placeholder used to capture a request to activate semantics.
DomElement? _semanticsPlaceholder;
/// Whether we are waiting for the user to enable semantics.
@override
bool get isWaitingToEnableSemantics => _semanticsPlaceholder != null;
@override
bool tryEnableSemantics(DomEvent event) {
// Semantics may be enabled programmatically. If there's a race between that
// and the DOM event, we may end up here while there's no longer a placeholder
// to work with.
if (!isWaitingToEnableSemantics) {
return true;
}
if (EngineSemantics.instance.semanticsEnabled) {
// Semantics already enabled, forward to framework as normal.
return true;
}
// In touch screen laptops, the touch is received as a mouse click
const Set<String> kInterestingEventTypes = <String>{
'click',
'keyup',
'keydown',
'mouseup',
'mousedown',
'pointerdown',
'pointerup',
};
if (!kInterestingEventTypes.contains(event.type)) {
// The event is not relevant, forward to framework as normal.
return true;
}
// Check for the event target.
final bool enableConditionPassed = event.target == _semanticsPlaceholder;
if (!enableConditionPassed) {
// This was not a semantics activating event; forward as normal.
return true;
}
EngineSemantics.instance.semanticsEnabled = true;
dispose();
return false;
}
@override
DomElement prepareAccessibilityPlaceholder() {
final DomElement placeholder =
_semanticsPlaceholder = createDomElement('flt-semantics-placeholder');
// Only listen to "click" because other kinds of events are reported via
// PointerBinding.
placeholder.addEventListener('click', createDomEventListener((DomEvent event) {
tryEnableSemantics(event);
}), true);
// Adding roles to semantics placeholder. 'aria-live' will make sure that
// the content is announced to the assistive technology user as soon as the
// page receives focus. 'tabindex' makes sure the button is the first
// target of tab. 'aria-label' is used to define the placeholder message
// to the assistive technology user.
placeholder
..setAttribute('role', 'button')
..setAttribute('aria-live', 'polite')
..setAttribute('tabindex', '0')
..setAttribute('aria-label', placeholderMessage);
// The placeholder sits just outside the window so only AT can reach it.
placeholder.style
..position = 'absolute'
..left = '-1px'
..top = '-1px'
..width = '1px'
..height = '1px';
return placeholder;
}
@override
void dispose() {
_semanticsPlaceholder?.remove();
_semanticsPlaceholder = null;
}
}
@visibleForTesting
class MobileSemanticsEnabler extends SemanticsEnabler {
/// We do not immediately enable semantics when the user requests it, but
/// instead wait for a short period of time before doing it. This is because
/// the request comes as an event targeted on the [_semanticsPlaceholder].
/// This event, depending on the browser, comes as a burst of events.
/// For example, Safari on IOS sends "touchstart", "touchend", and "click".
/// So during a short time period we consume all events and prevent forwarding
/// to the framework. Otherwise, the events will be interpreted twice, once as
/// a request to activate semantics, and a second time by Flutter's gesture
/// recognizers.
@visibleForTesting
Timer? semanticsActivationTimer;
/// A temporary placeholder used to capture a request to activate semantics.
DomElement? _semanticsPlaceholder;
/// The number of events we processed that could potentially activate
/// semantics.
int semanticsActivationAttempts = 0;
/// Instructs [_tryEnableSemantics] to remove [_semanticsPlaceholder].
///
/// For Blink browser engine the placeholder is removed upon any next event.
///
/// For Webkit browser engine the placeholder is removed upon the next
/// "touchend" event. This is to prevent Safari from swallowing the event
/// that happens on an element that's being removed. Blink doesn't have
/// this issue.
bool _schedulePlaceholderRemoval = false;
/// Whether we are waiting for the user to enable semantics.
@override
bool get isWaitingToEnableSemantics => _semanticsPlaceholder != null;
@override
bool tryEnableSemantics(DomEvent event) {
// Semantics may be enabled programmatically. If there's a race between that
// and the DOM event, we may end up here while there's no longer a placeholder
// to work with.
if (!isWaitingToEnableSemantics) {
return true;
}
if (_schedulePlaceholderRemoval) {
// The event type can also be click for VoiceOver.
final bool removeNow = browserEngine != BrowserEngine.webkit ||
event.type == 'touchend' ||
event.type == 'pointerup' ||
event.type == 'click';
if (removeNow) {
dispose();
}
return true;
}
if (EngineSemantics.instance.semanticsEnabled) {
// Semantics already enabled, forward to framework as normal.
return true;
}
semanticsActivationAttempts += 1;
if (semanticsActivationAttempts >= kMaxSemanticsActivationAttempts) {
// We have received multiple user events, none of which resulted in
// semantics activation. This is a signal that the user is not interested
// in semantics, and so we will stop waiting for it.
_schedulePlaceholderRemoval = true;
return true;
}
// ios-safari browsers which starts sending `pointer` events instead of
// `touch` events. (Tested with 12.1 which uses touch events vs 13.5
// which uses pointer events.)
const Set<String> kInterestingEventTypes = <String>{
'click',
'touchstart',
'touchend',
'pointerdown',
'pointermove',
'pointerup',
};
if (!kInterestingEventTypes.contains(event.type)) {
// The event is not relevant, forward to framework as normal.
return true;
}
if (semanticsActivationTimer != null) {
// We are in a waiting period to activate a timer. While the timer is
// active we should consume events pertaining to semantics activation.
// Otherwise the event will also be interpreted by the framework and
// potentially result in activating a gesture in the app.
return false;
}
// Look at where exactly (within 1 pixel) the event landed. If it landed
// exactly in the middle of the placeholder we interpret it as a signal
// to enable accessibility. This is because when VoiceOver and TalkBack
// generate a tap it lands it in the middle of the focused element. This
// method is a bit flawed in that a user's finger could theoretically land
// in the middle of the element too. However, the chance of that happening
// is very small. Even low-end phones typically have >2 million pixels
// (e.g. Moto G4). It is very unlikely that a user will land their finger
// exactly in the middle. In the worst case an unlucky user would
// accidentally enable accessibility and the app will be slightly slower
// than normal, but the app will continue functioning as normal. Our
// semantics tree is designed to not interfere with Flutter's gesture
// detection.
bool enableConditionPassed = false;
late final DomPoint activationPoint;
switch (event.type) {
case 'click':
final DomMouseEvent click = event as DomMouseEvent;
activationPoint = click.offset;
case 'touchstart':
case 'touchend':
final DomTouchEvent touchEvent = event as DomTouchEvent;
activationPoint = touchEvent.changedTouches.first.client;
case 'pointerdown':
case 'pointerup':
final DomPointerEvent touch = event as DomPointerEvent;
activationPoint = touch.client;
default:
// The event is not relevant, forward to framework as normal.
return true;
}
final DomRect activatingElementRect =
_semanticsPlaceholder!.getBoundingClientRect();
final double midX = activatingElementRect.left +
(activatingElementRect.right - activatingElementRect.left) / 2;
final double midY = activatingElementRect.top +
(activatingElementRect.bottom - activatingElementRect.top) / 2;
final double deltaX = activationPoint.x.toDouble() - midX;
final double deltaY = activationPoint.y.toDouble() - midY;
final double deltaSquared = deltaX * deltaX + deltaY * deltaY;
if (deltaSquared < 1.0) {
enableConditionPassed = true;
}
if (enableConditionPassed) {
assert(semanticsActivationTimer == null);
_schedulePlaceholderRemoval = true;
semanticsActivationTimer = Timer(_periodToConsumeEvents, () {
dispose();
EngineSemantics.instance.semanticsEnabled = true;
});
return false;
}
// This was not a semantics activating event; forward as normal.
return true;
}
@override
DomElement prepareAccessibilityPlaceholder() {
final DomElement placeholder =
_semanticsPlaceholder = createDomElement('flt-semantics-placeholder');
// Only listen to "click" because other kinds of events are reported via
// PointerBinding.
placeholder.addEventListener('click', createDomEventListener((DomEvent event) {
tryEnableSemantics(event);
}), true);
placeholder
..setAttribute('role', 'button')
..setAttribute('aria-label', placeholderMessage);
placeholder.style
..position = 'absolute'
..left = '0'
..top = '0'
..right = '0'
..bottom = '0';
return placeholder;
}
@override
void dispose() {
_semanticsPlaceholder?.remove();
_semanticsPlaceholder = null;
semanticsActivationTimer = null;
}
}
| engine/lib/web_ui/lib/src/engine/semantics/semantics_helper.dart/0 | {'file_path': 'engine/lib/web_ui/lib/src/engine/semantics/semantics_helper.dart', 'repo_id': 'engine', 'token_count': 4327} |
// 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:js_interop';
import 'package:ui/src/engine.dart';
class SkwasmObjectWrapper<T extends NativeType> {
SkwasmObjectWrapper(this.handle, this.registry) {
registry.register(this);
}
final SkwasmFinalizationRegistry<T> registry;
final Pointer<T> handle;
bool _isDisposed = false;
void dispose() {
assert(!_isDisposed);
registry.evict(this);
_isDisposed = true;
}
bool get debugDisposed => _isDisposed;
}
typedef DisposeFunction<T extends NativeType> = void Function(Pointer<T>);
class SkwasmFinalizationRegistry<T extends NativeType> {
SkwasmFinalizationRegistry(this.dispose)
: registry = createDomFinalizationRegistry(((JSNumber address) =>
dispose(Pointer<T>.fromAddress(address.toDartDouble.toInt()))
).toJS);
final DomFinalizationRegistry registry;
final DisposeFunction<T> dispose;
void register(SkwasmObjectWrapper<T> wrapper) {
registry.register(wrapper, wrapper.handle.address, wrapper);
}
void evict(SkwasmObjectWrapper<T> wrapper) {
registry.unregister(wrapper);
dispose(wrapper.handle);
}
}
| engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/memory.dart/0 | {'file_path': 'engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/memory.dart', 'repo_id': 'engine', 'token_count': 431} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
@DefaultAsset('skwasm')
library skwasm_impl;
import 'dart:ffi';
import 'package:ui/src/engine/skwasm/skwasm_impl.dart';
final class RawShader extends Opaque {}
typedef ShaderHandle = Pointer<RawShader>;
final class RawRuntimeEffect extends Opaque {}
typedef RuntimeEffectHandle = Pointer<RawRuntimeEffect>;
@Native<ShaderHandle Function(
RawPointArray,
RawColorArray,
Pointer<Float>,
Int,
Int,
RawMatrix33,
)>(symbol: 'shader_createLinearGradient', isLeaf: true)
external ShaderHandle shaderCreateLinearGradient(
RawPointArray endPoints, // two points
RawColorArray colors,
Pointer<Float> stops, // Can be nullptr
int count, // Number of stops/colors
int tileMode,
RawMatrix33 matrix, // Can be nullptr
);
@Native<ShaderHandle Function(
Float,
Float,
Float,
RawColorArray,
Pointer<Float>,
Int,
Int,
RawMatrix33,
)>(symbol: 'shader_createRadialGradient', isLeaf: true)
external ShaderHandle shaderCreateRadialGradient(
double centerX,
double centerY,
double radius,
RawColorArray colors,
Pointer<Float> stops,
int count,
int tileMode,
RawMatrix33 localMatrix,
);
@Native<ShaderHandle Function(
RawPointArray,
Float,
Float,
RawColorArray,
Pointer<Float>,
Int,
Int,
RawMatrix33,
)>(symbol: 'shader_createConicalGradient', isLeaf: true)
external ShaderHandle shaderCreateConicalGradient(
RawPointArray endPoints, // Two points,
double startRadius,
double endRadius,
RawColorArray colors,
Pointer<Float> stops,
int count,
int tileMode,
RawMatrix33 localMatrix,
);
@Native<ShaderHandle Function(
Float,
Float,
RawColorArray,
Pointer<Float>,
Int,
Int,
Float,
Float,
RawMatrix33,
)>(symbol: 'shader_createSweepGradient', isLeaf: true)
external ShaderHandle shaderCreateSweepGradient(
double centerX,
double centerY,
RawColorArray colors,
Pointer<Float> stops,
int count,
int tileMode,
double startAngle,
double endAngle,
RawMatrix33 localMatrix
);
@Native<Void Function(ShaderHandle)>(symbol: 'shader_dispose', isLeaf: true)
external void shaderDispose(ShaderHandle handle);
@Native<RuntimeEffectHandle Function(SkStringHandle)>(symbol: 'runtimeEffect_create', isLeaf: true)
external RuntimeEffectHandle runtimeEffectCreate(SkStringHandle source);
@Native<Void Function(RuntimeEffectHandle)>(symbol: 'runtimeEffect_dispose', isLeaf: true)
external void runtimeEffectDispose(RuntimeEffectHandle handle);
@Native<Size Function(RuntimeEffectHandle)>(symbol: 'runtimeEffect_getUniformSize', isLeaf: true)
external int runtimeEffectGetUniformSize(RuntimeEffectHandle handle);
@Native<ShaderHandle Function(
RuntimeEffectHandle,
SkDataHandle,
Pointer<ShaderHandle>,
Size
)>(symbol: 'shader_createRuntimeEffectShader', isLeaf: true)
external ShaderHandle shaderCreateRuntimeEffectShader(
RuntimeEffectHandle runtimeEffect,
SkDataHandle uniforms,
Pointer<ShaderHandle> childShaders,
int childCount
);
@Native<ShaderHandle Function(
ImageHandle,
Int,
Int,
Int,
RawMatrix33,
)>(symbol: 'shader_createFromImage', isLeaf: true)
external ShaderHandle shaderCreateFromImage(
ImageHandle handle,
int tileModeX,
int tileModeY,
int quality,
RawMatrix33 localMatrix,
);
| engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/raw/raw_shaders.dart/0 | {'file_path': 'engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/raw/raw_shaders.dart', 'repo_id': 'engine', 'token_count': 1099} |
// 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 web_sdk/sdk_rewriter.dart uses this directive.
// ignore: unnecessary_library_directive
library skwasm_stub;
export 'skwasm_stub/renderer.dart';
| engine/lib/web_ui/lib/src/engine/skwasm/skwasm_stub.dart/0 | {'file_path': 'engine/lib/web_ui/lib/src/engine/skwasm/skwasm_stub.dart', 'repo_id': 'engine', 'token_count': 98} |
// 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.
const int kChar_0 = 48;
const int kChar_9 = kChar_0 + 9;
const int kChar_A = 65;
const int kChar_Z = 90;
const int kChar_a = 97;
const int kChar_z = 122;
const int kCharBang = 33;
const int kMashriqi_0 = 0x660;
const int kMashriqi_9 = kMashriqi_0 + 9;
enum _ComparisonResult {
inside,
higher,
lower,
}
/// Each instance of [UnicodeRange] represents a range of unicode characters
/// that are assigned a [CharProperty]. For example, the following snippet:
///
/// ```dart
/// UnicodeRange(0x0041, 0x005A, CharProperty.ALetter);
/// ```
///
/// is saying that all characters between 0x0041 ("A") and 0x005A ("Z") are
/// assigned the property [CharProperty.ALetter].
///
/// Note that the Unicode spec uses inclusive ranges and we are doing the
/// same here.
class UnicodeRange<P> {
const UnicodeRange(this.start, this.end, this.property);
final int start;
final int end;
final P property;
/// Compare a [value] to this range.
///
/// The return value is either:
/// - lower: The value is lower than the range.
/// - higher: The value is higher than the range
/// - inside: The value is within the range.
_ComparisonResult compare(int value) {
if (value < start) {
return _ComparisonResult.lower;
}
if (value > end) {
return _ComparisonResult.higher;
}
return _ComparisonResult.inside;
}
}
/// Checks whether the given char code is a UTF-16 surrogate.
///
/// See:
/// - http://www.unicode.org/faq//utf_bom.html#utf16-2
bool isUtf16Surrogate(int char) {
return char & 0xF800 == 0xD800;
}
/// Combines a pair of UTF-16 surrogate into a single character code point.
///
/// The surrogate pair is expected to start at [index] in the [text].
///
/// See:
/// - http://www.unicode.org/faq//utf_bom.html#utf16-3
int combineSurrogatePair(String text, int index) {
final int hi = text.codeUnitAt(index);
final int lo = text.codeUnitAt(index + 1);
final int x = (hi & ((1 << 6) - 1)) << 10 | lo & ((1 << 10) - 1);
final int w = (hi >> 6) & ((1 << 5) - 1);
final int u = w + 1;
return u << 16 | x;
}
/// Returns the code point from [text] at [index] and handles surrogate pairs
/// for cases that involve two UTF-16 codes.
int? getCodePoint(String text, int index) {
if (index < 0 || index >= text.length) {
return null;
}
final int char = text.codeUnitAt(index);
if (isUtf16Surrogate(char) && index < text.length - 1) {
return combineSurrogatePair(text, index);
}
return char;
}
/// Given a list of [UnicodeRange]s, this class performs efficient lookup
/// to find which range a value falls into.
///
/// The lookup algorithm expects the ranges to have the following constraints:
/// - Be sorted.
/// - No overlap between the ranges.
/// - Gaps between ranges are ok.
///
/// This is used in the context of unicode to find out what property a letter
/// has. The properties are then used to decide word boundaries, line break
/// opportunities, etc.
class UnicodePropertyLookup<P> {
UnicodePropertyLookup(this.ranges, this.defaultProperty);
/// Creates a [UnicodePropertyLookup] from packed line break data.
factory UnicodePropertyLookup.fromPackedData(
String packedData,
int singleRangesCount,
List<P> propertyEnumValues,
P defaultProperty,
) {
return UnicodePropertyLookup<P>(
_unpackProperties<P>(packedData, singleRangesCount, propertyEnumValues),
defaultProperty,
);
}
/// The list of unicode ranges and their associated properties.
final List<UnicodeRange<P>> ranges;
/// The default property to use when a character doesn't belong in any
/// known range.
final P defaultProperty;
/// Cache for lookup results.
final Map<int, P> _cache = <int, P>{};
/// Take a [text] and an [index], and returns the property of the character
/// located at that [index].
///
/// If the [index] is out of range, null will be returned.
P find(String text, int index) {
final int? codePoint = getCodePoint(text, index);
return codePoint == null ? defaultProperty : findForChar(codePoint);
}
/// Takes one character as an integer code unit and returns its property.
///
/// If a property can't be found for the given character, then the default
/// property will be returned.
P findForChar(int? char) {
if (char == null) {
return defaultProperty;
}
final P? cacheHit = _cache[char];
if (cacheHit != null) {
return cacheHit;
}
final int rangeIndex = _binarySearch(char);
final P result = rangeIndex == -1 ? defaultProperty : ranges[rangeIndex].property;
// Cache the result.
_cache[char] = result;
return result;
}
int _binarySearch(int value) {
int min = 0;
int max = ranges.length;
while (min < max) {
final int mid = min + ((max - min) >> 1);
final UnicodeRange<P> range = ranges[mid];
switch (range.compare(value)) {
case _ComparisonResult.higher:
min = mid + 1;
case _ComparisonResult.lower:
max = mid;
case _ComparisonResult.inside:
return mid;
}
}
return -1;
}
}
List<UnicodeRange<P>> _unpackProperties<P>(
String packedData,
int singleRangesCount,
List<P> propertyEnumValues,
) {
// Packed data is mostly structured in chunks of 9 characters each:
//
// * [0..3]: Range start, encoded as a base36 integer.
// * [4..7]: Range end, encoded as a base36 integer.
// * [8]: Index of the property enum value, encoded as a single letter.
//
// When the range is a single number (i.e. range start == range end), it gets
// packed more efficiently in a chunk of 6 characters:
//
// * [0..3]: Range start (and range end), encoded as a base 36 integer.
// * [4]: "!" to indicate that there's no range end.
// * [5]: Index of the property enum value, encoded as a single letter.
// `packedData.length + singleRangesCount * 3` would have been the size of the
// packed data if the efficient packing of single-range items wasn't applied.
assert((packedData.length + singleRangesCount * 3) % 9 == 0);
final List<UnicodeRange<P>> ranges = <UnicodeRange<P>>[];
final int dataLength = packedData.length;
int i = 0;
while (i < dataLength) {
final int rangeStart = _consumeInt(packedData, i);
i += 4;
int rangeEnd;
if (packedData.codeUnitAt(i) == kCharBang) {
rangeEnd = rangeStart;
i++;
} else {
rangeEnd = _consumeInt(packedData, i);
i += 4;
}
final int charCode = packedData.codeUnitAt(i);
final P property =
propertyEnumValues[_getEnumIndexFromPackedValue(charCode)];
i++;
ranges.add(UnicodeRange<P>(rangeStart, rangeEnd, property));
}
return ranges;
}
int _getEnumIndexFromPackedValue(int charCode) {
// This has to stay in sync with [EnumValue.serialized] in
// `tool/unicode_sync_script.dart`.
assert((charCode >= kChar_A && charCode <= kChar_Z) ||
(charCode >= kChar_a && charCode <= kChar_z));
// Uppercase letters were assigned to the first 26 enum values.
if (charCode <= kChar_Z) {
return charCode - kChar_A;
}
// Lowercase letters were assigned to enum values above 26.
return 26 + charCode - kChar_a;
}
int _consumeInt(String packedData, int index) {
// The implementation is equivalent to:
//
// ```dart
// return int.tryParse(packedData.substring(index, index + 4), radix: 36);
// ```
//
// But using substring is slow when called too many times. This custom
// implementation makes the unpacking 25%-45% faster than using substring.
final int digit0 = getIntFromCharCode(packedData.codeUnitAt(index + 3));
final int digit1 = getIntFromCharCode(packedData.codeUnitAt(index + 2));
final int digit2 = getIntFromCharCode(packedData.codeUnitAt(index + 1));
final int digit3 = getIntFromCharCode(packedData.codeUnitAt(index));
return digit0 + (digit1 * 36) + (digit2 * 36 * 36) + (digit3 * 36 * 36 * 36);
}
/// Does the same thing as [int.parse(str, 36)] but takes only a single
/// character as a [charCode] integer.
int getIntFromCharCode(int charCode) {
assert((charCode >= kChar_0 && charCode <= kChar_9) ||
(charCode >= kChar_a && charCode <= kChar_z));
if (charCode <= kChar_9) {
return charCode - kChar_0;
}
// "a" starts from 10 and remaining letters go up from there.
return charCode - kChar_a + 10;
}
| engine/lib/web_ui/lib/src/engine/text/unicode_range.dart/0 | {'file_path': 'engine/lib/web_ui/lib/src/engine/text/unicode_range.dart', 'repo_id': 'engine', 'token_count': 2873} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:ui/src/engine/dom.dart';
import '../hot_restart_cache_handler.dart' show registerElementForCleanup;
import 'embedding_strategy.dart';
/// An [EmbeddingStrategy] that renders flutter inside a target host element.
///
/// This strategy attempts to minimize DOM modifications outside of the host
/// element, so it plays "nice" with other web frameworks.
class CustomElementEmbeddingStrategy implements EmbeddingStrategy {
/// Creates a [CustomElementEmbeddingStrategy] to embed a Flutter view into [_hostElement].
CustomElementEmbeddingStrategy(this._hostElement) {
_hostElement.clearChildren();
}
@override
DomEventTarget get globalEventTarget => _rootElement;
/// The target element in which this strategy will embed the Flutter view.
final DomElement _hostElement;
/// The root element of the Flutter view.
late final DomElement _rootElement;
@override
void initialize({
Map<String, String>? hostElementAttributes,
}) {
// ignore:avoid_function_literals_in_foreach_calls
hostElementAttributes?.entries.forEach((MapEntry<String, String> entry) {
_setHostAttribute(entry.key, entry.value);
});
_setHostAttribute('flt-embedding', 'custom-element');
}
@override
void attachViewRoot(DomElement rootElement) {
rootElement
..style.width = '100%'
..style.height = '100%'
..style.display = 'block'
..style.overflow = 'hidden'
..style.position = 'relative';
_hostElement.appendChild(rootElement);
registerElementForCleanup(rootElement);
_rootElement = rootElement;
}
@override
void attachResourcesHost(DomElement resourceHost, {DomElement? nextTo}) {
_hostElement.insertBefore(resourceHost, nextTo);
registerElementForCleanup(resourceHost);
}
void _setHostAttribute(String name, String value) {
_hostElement.setAttribute(name, value);
}
}
| engine/lib/web_ui/lib/src/engine/view_embedder/embedding_strategy/custom_element_embedding_strategy.dart/0 | {'file_path': 'engine/lib/web_ui/lib/src/engine/view_embedder/embedding_strategy/custom_element_embedding_strategy.dart', 'repo_id': 'engine', 'token_count': 638} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:meta/meta.dart';
import 'package:ui/src/engine.dart';
import 'url_strategy.dart';
/// Function type that handles pop state events.
typedef EventListener = dynamic Function(Object event);
/// Encapsulates all calls to DOM apis, which allows the [UrlStrategy] classes
/// to be platform agnostic and testable.
///
/// For convenience, the [PlatformLocation] class can be used by implementations
/// of [UrlStrategy] to interact with DOM apis like pushState, popState, etc.
abstract interface class PlatformLocation {
/// Registers an event listener for the `popstate` event.
///
/// See: https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onpopstate
void addPopStateListener(EventListener fn);
/// Unregisters the given listener (added by [addPopStateListener]) from the
/// `popstate` event.
///
/// See: https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onpopstate
void removePopStateListener(EventListener fn);
/// The `pathname` part of the URL in the browser address bar.
///
/// See: https://developer.mozilla.org/en-US/docs/Web/API/Location/pathname
String get pathname;
/// The `query` part of the URL in the browser address bar.
///
/// See: https://developer.mozilla.org/en-US/docs/Web/API/Location/search
String get search;
/// The `hash]` part of the URL in the browser address bar.
///
/// See: https://developer.mozilla.org/en-US/docs/Web/API/Location/hash
String? get hash;
/// The `state` in the current history entry.
///
/// See: https://developer.mozilla.org/en-US/docs/Web/API/History/state
Object? get state;
/// Adds a new entry to the browser history stack.
///
/// See: https://developer.mozilla.org/en-US/docs/Web/API/History/pushState
void pushState(Object? state, String title, String url);
/// Replaces the current entry in the browser history stack.
///
/// See: https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState
void replaceState(Object? state, String title, String url);
/// Moves forwards or backwards through the history stack.
///
/// A negative [count] value causes a backward move in the history stack. And
/// a positive [count] value causs a forward move.
///
/// Examples:
///
/// * `go(-2)` moves back 2 steps in history.
/// * `go(3)` moves forward 3 steps in hisotry.
///
/// See: https://developer.mozilla.org/en-US/docs/Web/API/History/go
void go(int count);
/// The base href where the Flutter app is being served.
///
/// See: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base
String? getBaseHref();
}
final Map<EventListener, DomEventListener> _popStateListenersCache =
<EventListener, DomEventListener>{};
/// Delegates to real browser APIs to provide platform location functionality.
class BrowserPlatformLocation implements PlatformLocation {
/// Default constructor for [BrowserPlatformLocation].
const BrowserPlatformLocation();
DomLocation get _location => domWindow.location;
DomHistory get _history => domWindow.history;
@visibleForTesting
DomEventListener getOrCreateDomEventListener(EventListener fn) {
return _popStateListenersCache.putIfAbsent(fn, () => createDomEventListener(fn));
}
@override
void addPopStateListener(EventListener fn) {
domWindow.addEventListener('popstate', getOrCreateDomEventListener(fn));
}
@override
void removePopStateListener(EventListener fn) {
assert(
_popStateListenersCache.containsKey(fn),
'Removing a listener that was never added or was removed already.',
);
domWindow.removeEventListener('popstate', getOrCreateDomEventListener(fn));
_popStateListenersCache.remove(fn);
}
@override
String get pathname => _location.pathname!;
@override
String get search => _location.search!;
@override
String get hash => _location.locationHash;
@override
Object? get state => _history.state;
@override
void pushState(Object? state, String title, String url) {
_history.pushState(state, title, url);
}
@override
void replaceState(Object? state, String title, String url) {
_history.replaceState(state, title, url);
}
@override
void go(int count) {
_history.go(count);
}
@override
String? getBaseHref() => domDocument.baseUri;
}
| engine/lib/web_ui/lib/ui_web/src/ui_web/navigation/platform_location.dart/0 | {'file_path': 'engine/lib/web_ui/lib/ui_web/src/ui_web/navigation/platform_location.dart', 'repo_id': 'engine', 'token_count': 1373} |
// 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';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
void testMain() {
test('CanvasKit reuses the instance already set on `window`', () async {
// First initialization should make CanvasKit available through `window`.
await renderer.initialize();
expect(windowFlutterCanvasKit, isNotNull);
// Remember the initial instance.
final CanvasKit firstCanvasKitInstance = windowFlutterCanvasKit!;
// Try to load CanvasKit again.
await renderer.initialize();
// Should find the existing instance and reuse it.
expect(firstCanvasKitInstance, windowFlutterCanvasKit);
});
}
| engine/lib/web_ui/test/canvaskit/hot_restart_test.dart/0 | {'file_path': 'engine/lib/web_ui/test/canvaskit/hot_restart_test.dart', 'repo_id': 'engine', 'token_count': 271} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:js_interop';
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'common.dart';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
void testMain() {
group('CanvasKit', () {
setUpCanvasKitTest();
setUp(() async {
EngineFlutterDisplay.instance.debugOverrideDevicePixelRatio(1.0);
});
Future<DomImageBitmap> newBitmap(int width, int height) async {
return createImageBitmap(
createBlankDomImageData(width, height) as JSAny, (
x: 0,
y: 0,
width: width,
height: height,
));
}
// Regression test for https://github.com/flutter/flutter/issues/75286
test('updates canvas logical size when device-pixel ratio changes',
() async {
final RenderCanvas canvas = RenderCanvas();
canvas.render(await newBitmap(10, 16));
expect(canvas.canvasElement.width, 10);
expect(canvas.canvasElement.height, 16);
expect(canvas.canvasElement.style.width, '10px');
expect(canvas.canvasElement.style.height, '16px');
// Increase device-pixel ratio: this makes CSS pixels bigger, so we need
// fewer of them to cover the browser window.
EngineFlutterDisplay.instance.debugOverrideDevicePixelRatio(2.0);
canvas.render(await newBitmap(10, 16));
expect(canvas.canvasElement.width, 10);
expect(canvas.canvasElement.height, 16);
expect(canvas.canvasElement.style.width, '5px');
expect(canvas.canvasElement.style.height, '8px');
// Decrease device-pixel ratio: this makes CSS pixels smaller, so we need
// more of them to cover the browser window.
EngineFlutterDisplay.instance.debugOverrideDevicePixelRatio(0.5);
canvas.render(await newBitmap(10, 16));
expect(canvas.canvasElement.width, 10);
expect(canvas.canvasElement.height, 16);
expect(canvas.canvasElement.style.width, '20px');
expect(canvas.canvasElement.style.height, '32px');
});
});
}
| engine/lib/web_ui/test/canvaskit/render_canvas_test.dart/0 | {'file_path': 'engine/lib/web_ui/test/canvaskit/render_canvas_test.dart', 'repo_id': 'engine', 'token_count': 829} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' as ui;
// The scene that will be rendered in the next call to `onDrawFrame`.
ui.Scene? _sceneToRender;
// Completer that will complete when the call to render completes.
Completer<void>? _sceneCompleter;
/// Sets up rendering so that `onDrawFrame` will render the last requested
/// scene.
void setUpRenderingForTests() {
// Set `onDrawFrame` to call `renderer.renderScene`.
EnginePlatformDispatcher.instance.onDrawFrame = () {
if (_sceneToRender != null) {
EnginePlatformDispatcher.instance.render(_sceneToRender!).then<void>((_) {
_sceneCompleter?.complete();
}).catchError((Object error) {
_sceneCompleter?.completeError(error);
});
_sceneToRender = null;
}
};
}
/// Render the given [scene] in an `onDrawFrame` scope.
Future<void> renderScene(ui.Scene scene) {
_sceneToRender = scene;
_sceneCompleter = Completer<void>();
EnginePlatformDispatcher.instance.invokeOnDrawFrame();
return _sceneCompleter!.future;
}
| engine/lib/web_ui/test/common/rendering.dart/0 | {'file_path': 'engine/lib/web_ui/test/common/rendering.dart', 'repo_id': 'engine', 'token_count': 416} |
// 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:typed_data';
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/test_initialization.dart';
const MethodCodec codec = JSONMethodCodec();
EngineFlutterWindow get implicitView =>
EnginePlatformDispatcher.instance.implicitView!;
void main() {
internalBootstrapBrowserTest(() => testMain);
}
void testMain() {
group('without implicit view', () {
test('Handles navigation gracefully when no implicit view exists', () async {
expect(EnginePlatformDispatcher.instance.implicitView, isNull);
final Completer<ByteData?> completer = Completer<ByteData?>();
ui.PlatformDispatcher.instance.sendPlatformMessage(
'flutter/navigation',
codec.encodeMethodCall(const MethodCall(
'routeUpdated',
<String, dynamic>{'routeName': '/foo'},
)),
(ByteData? response) => completer.complete(response),
);
final ByteData? response = await completer.future;
expect(response, isNull);
});
});
group('with implicit view', () {
late TestUrlStrategy strategy;
setUpAll(() async {
await bootstrapAndRunApp(withImplicitView: true);
});
setUp(() async {
strategy = TestUrlStrategy();
await implicitView.debugInitializeHistory(strategy, useSingle: true);
});
tearDown(() async {
await implicitView.resetHistory();
});
test('Tracks pushed, replaced and popped routes', () async {
final Completer<void> completer = Completer<void>();
ui.PlatformDispatcher.instance.sendPlatformMessage(
'flutter/navigation',
codec.encodeMethodCall(const MethodCall(
'routeUpdated',
<String, dynamic>{'routeName': '/foo'},
)),
(_) => completer.complete(),
);
await completer.future;
expect(strategy.getPath(), '/foo');
});
});
}
| engine/lib/web_ui/test/engine/navigation_test.dart/0 | {'file_path': 'engine/lib/web_ui/test/engine/navigation_test.dart', 'repo_id': 'engine', 'token_count': 794} |
// 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/html/shaders/normalized_gradient.dart';
import 'package:ui/ui.dart' as ui hide window;
void main() {
internalBootstrapBrowserTest(() => testMain);
}
void testMain() {
group('Shader Normalized Gradient', () {
test('3 stop at start', () {
final NormalizedGradient gradient = NormalizedGradient(const <ui.Color>[
ui.Color(0xFF000000), ui.Color(0xFFFF7f3f)
], stops: <double>[0.0, 0.5]);
int res = _computeColorAt(gradient, 0.0);
assert(res == 0xFF000000);
res = _computeColorAt(gradient, 0.25);
assert(res == 0xFF7f3f1f);
res = _computeColorAt(gradient, 0.5);
assert(res == 0xFFFF7f3f);
res = _computeColorAt(gradient, 0.7);
assert(res == 0xFFFF7f3f);
res = _computeColorAt(gradient, 1.0);
assert(res == 0xFFFF7f3f);
});
test('3 stop at end', () {
final NormalizedGradient gradient = NormalizedGradient(const <ui.Color>[
ui.Color(0xFF000000), ui.Color(0xFFFF7f3f)
], stops: <double>[0.5, 1.0]);
int res = _computeColorAt(gradient, 0.0);
assert(res == 0xFF000000);
res = _computeColorAt(gradient, 0.25);
assert(res == 0xFF000000);
res = _computeColorAt(gradient, 0.5);
assert(res == 0xFF000000);
res = _computeColorAt(gradient, 0.75);
assert(res == 0xFF7f3f1f);
res = _computeColorAt(gradient, 1.0);
assert(res == 0xFFFF7f3f);
});
test('4 stop', () {
final NormalizedGradient gradient = NormalizedGradient(const <ui.Color>[
ui.Color(0xFF000000), ui.Color(0xFFFF7f3f)
], stops: <double>[0.25, 0.5]);
int res = _computeColorAt(gradient, 0.0);
assert(res == 0xFF000000);
res = _computeColorAt(gradient, 0.25);
assert(res == 0xFF000000);
res = _computeColorAt(gradient, 0.4);
assert(res == 0xFF994c25);
res = _computeColorAt(gradient, 0.5);
assert(res == 0xFFFF7f3f);
res = _computeColorAt(gradient, 0.75);
assert(res == 0xFFFF7f3f);
res = _computeColorAt(gradient, 1.0);
assert(res == 0xFFFF7f3f);
});
test('5 stop', () {
final NormalizedGradient gradient = NormalizedGradient(const <ui.Color>[
ui.Color(0x10000000), ui.Color(0x20FF0000),
ui.Color(0x4000FF00), ui.Color(0x800000FF),
ui.Color(0xFFFFFFFF)
], stops: <double>[0.0, 0.1, 0.2, 0.5, 1.0]);
int res = _computeColorAt(gradient, 0.0);
assert(res == 0x10000000);
res = _computeColorAt(gradient, 0.05);
assert(res == 0x187f0000);
res = _computeColorAt(gradient, 0.1);
assert(res == 0x20ff0000);
res = _computeColorAt(gradient, 0.15);
assert(res == 0x307f7f00);
res = _computeColorAt(gradient, 0.2);
assert(res == 0x4000ff00);
res = _computeColorAt(gradient, 0.4);
assert(res == 0x6a0054a9);
res = _computeColorAt(gradient, 0.5);
assert(res == 0x800000fe);
res = _computeColorAt(gradient, 0.9);
assert(res == 0xe5ccccff);
res = _computeColorAt(gradient, 1.0);
assert(res == 0xffffffff);
});
test('2 stops at ends', () {
final NormalizedGradient gradient = NormalizedGradient(const <ui.Color>[
ui.Color(0x00000000), ui.Color(0xFFFFFFFF)
]);
int res = _computeColorAt(gradient, 0.0);
assert(res == 0);
res = _computeColorAt(gradient, 1.0);
assert(res == 0xFFFFFFFF);
res = _computeColorAt(gradient, 0.5);
assert(res == 0x7f7f7f7f);
});
});
}
int _computeColorAt(NormalizedGradient gradient, double t) {
int i = 0;
while (t > gradient.thresholdAt(i + 1)) {
++i;
}
final double r = t * gradient.scaleAt(i * 4) + gradient.biasAt(i * 4);
final double g = t * gradient.scaleAt(i * 4 + 1) + gradient.biasAt(i * 4 + 1);
final double b = t * gradient.scaleAt(i * 4 + 2) + gradient.biasAt(i * 4 + 2);
final double a = t * gradient.scaleAt(i * 4 + 3) + gradient.biasAt(i * 4 + 3);
int val = 0;
val |= (a * 0xFF).toInt() & 0xFF;
val<<=8;
val |= (r * 0xFF).toInt() & 0xFF;
val<<=8;
val |= (g * 0xFF).toInt() & 0xFF;
val<<=8;
val |= (b * 0xFF).toInt() & 0xFF;
return val;
}
| engine/lib/web_ui/test/engine/surface/shaders/normalized_gradient_test.dart/0 | {'file_path': 'engine/lib/web_ui/test/engine/surface/shaders/normalized_gradient_test.dart', 'repo_id': 'engine', 'token_count': 1986} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import '../../common/matchers.dart';
void main() {
internalBootstrapBrowserTest(() => doTests);
}
void doTests() {
group('StyleManager', () {
test('styleSceneHost', () {
expect(
() => StyleManager.styleSceneHost(createDomHTMLDivElement()),
throwsAssertionError,
);
final DomElement sceneHost = createDomElement('flt-scene-host');
StyleManager.styleSceneHost(sceneHost);
expect(sceneHost.style.pointerEvents, 'none');
expect(sceneHost.style.opacity, isEmpty);
final DomElement sceneHost2 = createDomElement('flt-scene-host');
StyleManager.styleSceneHost(sceneHost2, debugShowSemanticsNodes: true);
expect(sceneHost2.style.pointerEvents, 'none');
expect(sceneHost2.style.opacity, isNotEmpty);
});
test('styleSemanticsHost', () {
expect(
() => StyleManager.styleSemanticsHost(createDomHTMLDivElement(), 1.0),
throwsAssertionError,
reason: 'Only accepts a <flt-semantics-host> element.'
);
final DomElement semanticsHost = createDomElement('flt-semantics-host');
StyleManager.styleSemanticsHost(semanticsHost, 4.0);
expect(semanticsHost.style.transform, 'scale(0.25)');
expect(semanticsHost.style.position, 'absolute');
expect(semanticsHost.style.transformOrigin, anyOf('0px 0px 0px', '0px 0px'));
});
test('scaleSemanticsHost', () {
expect(
() => StyleManager.scaleSemanticsHost(createDomHTMLDivElement(), 1.0),
throwsAssertionError,
reason: 'Only accepts a <flt-semantics-host> element.'
);
final DomElement semanticsHost = createDomElement('flt-semantics-host');
StyleManager.scaleSemanticsHost(semanticsHost, 5.0);
expect(semanticsHost.style.transform, 'scale(0.2)');
// Didn't set other styles.
expect(semanticsHost.style.position, isEmpty);
expect(semanticsHost.style.transformOrigin, isEmpty);
});
});
}
| engine/lib/web_ui/test/engine/view_embedder/style_manager_test.dart/0 | {'file_path': 'engine/lib/web_ui/test/engine/view_embedder/style_manager_test.dart', 'repo_id': 'engine', 'token_count': 824} |
// 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 window;
import '../../common/test_initialization.dart';
import 'helper.dart';
const String _rtlWord1 = 'واحد';
const String _rtlWord2 = 'اثنان';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
Future<void> testMain() async {
setUpUnitTests(
withImplicitView: true,
emulateTesterEnvironment: false,
setUpTestViewDimensions: false,
);
void paintBasicBidiStartingWithLtr(
EngineCanvas canvas,
Rect bounds,
double y,
TextDirection textDirection,
TextAlign textAlign,
) {
// The text starts with a left-to-right word.
const String text = 'One 12 $_rtlWord1 $_rtlWord2 34 two 56';
final EngineParagraphStyle paragraphStyle = EngineParagraphStyle(
fontFamily: 'Roboto',
fontSize: 20.0,
textDirection: textDirection,
textAlign: textAlign,
);
final CanvasParagraph paragraph = plain(
paragraphStyle,
text,
textStyle: EngineTextStyle.only(color: blue),
);
final double maxWidth = bounds.width - 10;
paragraph.layout(constrain(maxWidth));
canvas.drawParagraph(paragraph, Offset(bounds.left + 5, bounds.top + y + 5));
}
test('basic bidi starting with ltr', () {
const Rect bounds = Rect.fromLTWH(0, 0, 340, 600);
final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy());
const double height = 40;
// Border for ltr paragraphs.
final Rect ltrBox = const Rect.fromLTWH(0, 0, 320, 5 * height).inflate(5).translate(10, 10);
canvas.drawRect(
ltrBox,
SurfacePaintData()
..color = black.value
..style = PaintingStyle.stroke,
);
// LTR with different text align values:
paintBasicBidiStartingWithLtr(canvas, ltrBox, 0 * height, TextDirection.ltr, TextAlign.left);
paintBasicBidiStartingWithLtr(canvas, ltrBox, 1 * height, TextDirection.ltr, TextAlign.right);
paintBasicBidiStartingWithLtr(canvas, ltrBox, 2 * height, TextDirection.ltr, TextAlign.center);
paintBasicBidiStartingWithLtr(canvas, ltrBox, 3 * height, TextDirection.ltr, TextAlign.start);
paintBasicBidiStartingWithLtr(canvas, ltrBox, 4 * height, TextDirection.ltr, TextAlign.end);
// Border for rtl paragraphs.
final Rect rtlBox = ltrBox.translate(0, ltrBox.height + 10);
canvas.drawRect(
rtlBox,
SurfacePaintData()
..color = black.value
..style = PaintingStyle.stroke,
);
// RTL with different text align values:
paintBasicBidiStartingWithLtr(canvas, rtlBox, 0 * height, TextDirection.rtl, TextAlign.left);
paintBasicBidiStartingWithLtr(canvas, rtlBox, 1 * height, TextDirection.rtl, TextAlign.right);
paintBasicBidiStartingWithLtr(canvas, rtlBox, 2 * height, TextDirection.rtl, TextAlign.center);
paintBasicBidiStartingWithLtr(canvas, rtlBox, 3 * height, TextDirection.rtl, TextAlign.start);
paintBasicBidiStartingWithLtr(canvas, rtlBox, 4 * height, TextDirection.rtl, TextAlign.end);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_bidi_start_ltr');
});
test('basic bidi starting with ltr (DOM)', () {
const Rect bounds = Rect.fromLTWH(0, 0, 340, 600);
final DomCanvas canvas = DomCanvas(domDocument.createElement('flt-picture'));
const double height = 40;
// Border for ltr paragraphs.
final Rect ltrBox = const Rect.fromLTWH(0, 0, 320, 5 * height).inflate(5).translate(10, 10);
canvas.drawRect(
ltrBox,
SurfacePaintData()
..color = black.value
..style = PaintingStyle.stroke,
);
// LTR with different text align values:
paintBasicBidiStartingWithLtr(canvas, ltrBox, 0 * height, TextDirection.ltr, TextAlign.left);
paintBasicBidiStartingWithLtr(canvas, ltrBox, 1 * height, TextDirection.ltr, TextAlign.right);
paintBasicBidiStartingWithLtr(canvas, ltrBox, 2 * height, TextDirection.ltr, TextAlign.center);
paintBasicBidiStartingWithLtr(canvas, ltrBox, 3 * height, TextDirection.ltr, TextAlign.start);
paintBasicBidiStartingWithLtr(canvas, ltrBox, 4 * height, TextDirection.ltr, TextAlign.end);
// Border for rtl paragraphs.
final Rect rtlBox = ltrBox.translate(0, ltrBox.height + 10);
canvas.drawRect(
rtlBox,
SurfacePaintData()
..color = black.value
..style = PaintingStyle.stroke,
);
// RTL with different text align values:
paintBasicBidiStartingWithLtr(canvas, rtlBox, 0 * height, TextDirection.rtl, TextAlign.left);
paintBasicBidiStartingWithLtr(canvas, rtlBox, 1 * height, TextDirection.rtl, TextAlign.right);
paintBasicBidiStartingWithLtr(canvas, rtlBox, 2 * height, TextDirection.rtl, TextAlign.center);
paintBasicBidiStartingWithLtr(canvas, rtlBox, 3 * height, TextDirection.rtl, TextAlign.start);
paintBasicBidiStartingWithLtr(canvas, rtlBox, 4 * height, TextDirection.rtl, TextAlign.end);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_bidi_start_ltr_dom');
});
void paintBasicBidiStartingWithRtl(
EngineCanvas canvas,
Rect bounds,
double y,
TextDirection textDirection,
TextAlign textAlign,
) {
// The text starts with a right-to-left word.
const String text = '$_rtlWord1 12 one 34 $_rtlWord2 56 two';
final EngineParagraphStyle paragraphStyle = EngineParagraphStyle(
fontFamily: 'Roboto',
fontSize: 20.0,
textDirection: textDirection,
textAlign: textAlign,
);
final CanvasParagraph paragraph = plain(
paragraphStyle,
text,
textStyle: EngineTextStyle.only(color: blue),
);
final double maxWidth = bounds.width - 10;
paragraph.layout(constrain(maxWidth));
canvas.drawParagraph(paragraph, Offset(bounds.left + 5, bounds.top + y + 5));
}
test('basic bidi starting with rtl', () {
const Rect bounds = Rect.fromLTWH(0, 0, 340, 600);
final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy());
const double height = 40;
// Border for ltr paragraphs.
final Rect ltrBox = const Rect.fromLTWH(0, 0, 320, 5 * height).inflate(5).translate(10, 10);
canvas.drawRect(
ltrBox,
SurfacePaintData()
..color = black.value
..style = PaintingStyle.stroke,
);
// LTR with different text align values:
paintBasicBidiStartingWithRtl(canvas, ltrBox, 0 * height, TextDirection.ltr, TextAlign.left);
paintBasicBidiStartingWithRtl(canvas, ltrBox, 1 * height, TextDirection.ltr, TextAlign.right);
paintBasicBidiStartingWithRtl(canvas, ltrBox, 2 * height, TextDirection.ltr, TextAlign.center);
paintBasicBidiStartingWithRtl(canvas, ltrBox, 3 * height, TextDirection.ltr, TextAlign.start);
paintBasicBidiStartingWithRtl(canvas, ltrBox, 4 * height, TextDirection.ltr, TextAlign.end);
// Border for rtl paragraphs.
final Rect rtlBox = ltrBox.translate(0, ltrBox.height + 10);
canvas.drawRect(
rtlBox,
SurfacePaintData()
..color = black.value
..style = PaintingStyle.stroke,
);
// RTL with different text align values:
paintBasicBidiStartingWithRtl(canvas, rtlBox, 0 * height, TextDirection.rtl, TextAlign.left);
paintBasicBidiStartingWithRtl(canvas, rtlBox, 1 * height, TextDirection.rtl, TextAlign.right);
paintBasicBidiStartingWithRtl(canvas, rtlBox, 2 * height, TextDirection.rtl, TextAlign.center);
paintBasicBidiStartingWithRtl(canvas, rtlBox, 3 * height, TextDirection.rtl, TextAlign.start);
paintBasicBidiStartingWithRtl(canvas, rtlBox, 4 * height, TextDirection.rtl, TextAlign.end);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_bidi_start_rtl');
});
test('basic bidi starting with rtl (DOM)', () {
const Rect bounds = Rect.fromLTWH(0, 0, 340, 600);
final DomCanvas canvas = DomCanvas(domDocument.createElement('flt-picture'));
const double height = 40;
// Border for ltr paragraphs.
final Rect ltrBox = const Rect.fromLTWH(0, 0, 320, 5 * height).inflate(5).translate(10, 10);
canvas.drawRect(
ltrBox,
SurfacePaintData()
..color = black.value
..style = PaintingStyle.stroke,
);
// LTR with different text align values:
paintBasicBidiStartingWithRtl(canvas, ltrBox, 0 * height, TextDirection.ltr, TextAlign.left);
paintBasicBidiStartingWithRtl(canvas, ltrBox, 1 * height, TextDirection.ltr, TextAlign.right);
paintBasicBidiStartingWithRtl(canvas, ltrBox, 2 * height, TextDirection.ltr, TextAlign.center);
paintBasicBidiStartingWithRtl(canvas, ltrBox, 3 * height, TextDirection.ltr, TextAlign.start);
paintBasicBidiStartingWithRtl(canvas, ltrBox, 4 * height, TextDirection.ltr, TextAlign.end);
// Border for rtl paragraphs.
final Rect rtlBox = ltrBox.translate(0, ltrBox.height + 10);
canvas.drawRect(
rtlBox,
SurfacePaintData()
..color = black.value
..style = PaintingStyle.stroke,
);
// RTL with different text align values:
paintBasicBidiStartingWithRtl(canvas, rtlBox, 0 * height, TextDirection.rtl, TextAlign.left);
paintBasicBidiStartingWithRtl(canvas, rtlBox, 1 * height, TextDirection.rtl, TextAlign.right);
paintBasicBidiStartingWithRtl(canvas, rtlBox, 2 * height, TextDirection.rtl, TextAlign.center);
paintBasicBidiStartingWithRtl(canvas, rtlBox, 3 * height, TextDirection.rtl, TextAlign.start);
paintBasicBidiStartingWithRtl(canvas, rtlBox, 4 * height, TextDirection.rtl, TextAlign.end);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_bidi_start_rtl_dom');
});
void paintMultilineBidi(
EngineCanvas canvas,
Rect bounds,
double y,
TextDirection textDirection,
TextAlign textAlign,
) {
// '''
// Lorem 12 $_rtlWord1
// $_rtlWord2 34 ipsum
// dolor 56
// '''
const String text = 'Lorem 12 $_rtlWord1 $_rtlWord2 34 ipsum dolor 56';
final EngineParagraphStyle paragraphStyle = EngineParagraphStyle(
fontFamily: 'Roboto',
fontSize: 20.0,
textDirection: textDirection,
textAlign: textAlign,
);
final CanvasParagraph paragraph = plain(
paragraphStyle,
text,
textStyle: EngineTextStyle.only(color: blue),
);
final double maxWidth = bounds.width - 10;
paragraph.layout(constrain(maxWidth));
canvas.drawParagraph(paragraph, Offset(bounds.left + 5, bounds.top + y + 5));
}
test('multiline bidi', () {
const Rect bounds = Rect.fromLTWH(0, 0, 400, 500);
final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy());
const double height = 95;
// Border for ltr paragraphs.
final Rect ltrBox = const Rect.fromLTWH(0, 0, 150, 5 * height).inflate(5).translate(10, 10);
canvas.drawRect(
ltrBox,
SurfacePaintData()
..color = black.value
..style = PaintingStyle.stroke,
);
// LTR with different text align values:
paintMultilineBidi(canvas, ltrBox, 0 * height, TextDirection.ltr, TextAlign.left);
paintMultilineBidi(canvas, ltrBox, 1 * height, TextDirection.ltr, TextAlign.right);
paintMultilineBidi(canvas, ltrBox, 2 * height, TextDirection.ltr, TextAlign.center);
paintMultilineBidi(canvas, ltrBox, 3 * height, TextDirection.ltr, TextAlign.start);
paintMultilineBidi(canvas, ltrBox, 4 * height, TextDirection.ltr, TextAlign.end);
// Border for rtl paragraphs.
final Rect rtlBox = ltrBox.translate(ltrBox.width + 10, 0);
canvas.drawRect(
rtlBox,
SurfacePaintData()
..color = black.value
..style = PaintingStyle.stroke,
);
// RTL with different text align values:
paintMultilineBidi(canvas, rtlBox, 0 * height, TextDirection.rtl, TextAlign.left);
paintMultilineBidi(canvas, rtlBox, 1 * height, TextDirection.rtl, TextAlign.right);
paintMultilineBidi(canvas, rtlBox, 2 * height, TextDirection.rtl, TextAlign.center);
paintMultilineBidi(canvas, rtlBox, 3 * height, TextDirection.rtl, TextAlign.start);
paintMultilineBidi(canvas, rtlBox, 4 * height, TextDirection.rtl, TextAlign.end);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_bidi_multiline');
});
test('multiline bidi (DOM)', () {
const Rect bounds = Rect.fromLTWH(0, 0, 400, 500);
final DomCanvas canvas = DomCanvas(domDocument.createElement('flt-picture'));
const double height = 95;
final Rect ltrBox = const Rect.fromLTWH(0, 0, 150, 5 * height).inflate(5).translate(10, 10);
canvas.drawRect(
ltrBox,
SurfacePaintData()
..color = black.value
..style = PaintingStyle.stroke,
);
// LTR with different text align values:
paintMultilineBidi(canvas, ltrBox, 0 * height, TextDirection.ltr, TextAlign.left);
paintMultilineBidi(canvas, ltrBox, 1 * height, TextDirection.ltr, TextAlign.right);
paintMultilineBidi(canvas, ltrBox, 2 * height, TextDirection.ltr, TextAlign.center);
paintMultilineBidi(canvas, ltrBox, 3 * height, TextDirection.ltr, TextAlign.start);
paintMultilineBidi(canvas, ltrBox, 4 * height, TextDirection.ltr, TextAlign.end);
// Border for rtl paragraphs.
final Rect rtlBox = ltrBox.translate(ltrBox.width + 10, 0);
canvas.drawRect(
rtlBox,
SurfacePaintData()
..color = black.value
..style = PaintingStyle.stroke,
);
// RTL with different text align values:
paintMultilineBidi(canvas, rtlBox, 0 * height, TextDirection.rtl, TextAlign.left);
paintMultilineBidi(canvas, rtlBox, 1 * height, TextDirection.rtl, TextAlign.right);
paintMultilineBidi(canvas, rtlBox, 2 * height, TextDirection.rtl, TextAlign.center);
paintMultilineBidi(canvas, rtlBox, 3 * height, TextDirection.rtl, TextAlign.start);
paintMultilineBidi(canvas, rtlBox, 4 * height, TextDirection.rtl, TextAlign.end);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_bidi_multiline_dom');
});
void paintMultSpanBidi(
EngineCanvas canvas,
Rect bounds,
double y,
TextDirection textDirection,
TextAlign textAlign,
) {
final EngineParagraphStyle paragraphStyle = EngineParagraphStyle(
fontFamily: 'Roboto',
fontSize: 20.0,
textDirection: textDirection,
textAlign: textAlign,
);
// '''
// Lorem 12 $_rtlWord1
// $_rtlWord2 34 ipsum
// dolor 56
// '''
final CanvasParagraph paragraph = rich(paragraphStyle, (CanvasParagraphBuilder builder) {
builder.pushStyle(EngineTextStyle.only(color: blue));
builder.addText('Lorem ');
builder.pushStyle(EngineTextStyle.only(color: green));
builder.addText('12 ');
builder.pushStyle(EngineTextStyle.only(color: red));
builder.addText('$_rtlWord1 ');
builder.pushStyle(EngineTextStyle.only(color: black));
builder.addText('$_rtlWord2 ');
builder.pushStyle(EngineTextStyle.only(color: blue));
builder.addText('34 ipsum ');
builder.pushStyle(EngineTextStyle.only(color: green));
builder.addText('dolor 56 ');
});
final double maxWidth = bounds.width - 10;
paragraph.layout(constrain(maxWidth));
canvas.drawParagraph(paragraph, Offset(bounds.left + 5, bounds.top + y + 5));
}
test('multi span bidi', () {
const Rect bounds = Rect.fromLTWH(0, 0, 400, 900);
final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy());
const double height = 95;
// Border for ltr paragraphs.
final Rect ltrBox = const Rect.fromLTWH(0, 0, 150, 5 * height).inflate(5).translate(10, 10);
canvas.drawRect(
ltrBox,
SurfacePaintData()
..color = black.value
..style = PaintingStyle.stroke,
);
// LTR with different text align values:
paintMultSpanBidi(canvas, ltrBox, 0 * height, TextDirection.ltr, TextAlign.left);
paintMultSpanBidi(canvas, ltrBox, 1 * height, TextDirection.ltr, TextAlign.right);
paintMultSpanBidi(canvas, ltrBox, 2 * height, TextDirection.ltr, TextAlign.center);
paintMultSpanBidi(canvas, ltrBox, 3 * height, TextDirection.ltr, TextAlign.start);
paintMultSpanBidi(canvas, ltrBox, 4 * height, TextDirection.ltr, TextAlign.end);
// Border for rtl paragraphs.
final Rect rtlBox = ltrBox.translate(ltrBox.width + 10, 0);
canvas.drawRect(
rtlBox,
SurfacePaintData()
..color = black.value
..style = PaintingStyle.stroke,
);
// RTL with different text align values:
paintMultSpanBidi(canvas, rtlBox, 0 * height, TextDirection.rtl, TextAlign.left);
paintMultSpanBidi(canvas, rtlBox, 1 * height, TextDirection.rtl, TextAlign.right);
paintMultSpanBidi(canvas, rtlBox, 2 * height, TextDirection.rtl, TextAlign.center);
paintMultSpanBidi(canvas, rtlBox, 3 * height, TextDirection.rtl, TextAlign.start);
paintMultSpanBidi(canvas, rtlBox, 4 * height, TextDirection.rtl, TextAlign.end);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_bidi_multispan');
});
test('multi span bidi (DOM)', () {
const Rect bounds = Rect.fromLTWH(0, 0, 400, 900);
final DomCanvas canvas = DomCanvas(domDocument.createElement('flt-picture'));
const double height = 95;
// Border for ltr paragraphs.
final Rect ltrBox = const Rect.fromLTWH(0, 0, 150, 5 * height).inflate(5).translate(10, 10);
canvas.drawRect(
ltrBox,
SurfacePaintData()
..color = black.value
..style = PaintingStyle.stroke,
);
// LTR with different text align values:
paintMultSpanBidi(canvas, ltrBox, 0 * height, TextDirection.ltr, TextAlign.left);
paintMultSpanBidi(canvas, ltrBox, 1 * height, TextDirection.ltr, TextAlign.right);
paintMultSpanBidi(canvas, ltrBox, 2 * height, TextDirection.ltr, TextAlign.center);
paintMultSpanBidi(canvas, ltrBox, 3 * height, TextDirection.ltr, TextAlign.start);
paintMultSpanBidi(canvas, ltrBox, 4 * height, TextDirection.ltr, TextAlign.end);
// Border for rtl paragraphs.
final Rect rtlBox = ltrBox.translate(ltrBox.width + 10, 0);
canvas.drawRect(
rtlBox,
SurfacePaintData()
..color = black.value
..style = PaintingStyle.stroke,
);
// RTL with different text align values:
paintMultSpanBidi(canvas, rtlBox, 0 * height, TextDirection.rtl, TextAlign.left);
paintMultSpanBidi(canvas, rtlBox, 1 * height, TextDirection.rtl, TextAlign.right);
paintMultSpanBidi(canvas, rtlBox, 2 * height, TextDirection.rtl, TextAlign.center);
paintMultSpanBidi(canvas, rtlBox, 3 * height, TextDirection.rtl, TextAlign.start);
paintMultSpanBidi(canvas, rtlBox, 4 * height, TextDirection.rtl, TextAlign.end);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_bidi_multispan_dom');
});
void paintBidiWithSelection(
EngineCanvas canvas,
Rect bounds,
double y,
TextDirection textDirection,
TextAlign textAlign,
) {
// '''
// Lorem 12 $_rtlWord1
// $_rtlWord2 34 ipsum
// dolor 56
// '''
const String text = 'Lorem 12 $_rtlWord1 $_rtlWord2 34 ipsum dolor 56';
final EngineParagraphStyle paragraphStyle = EngineParagraphStyle(
fontFamily: 'Roboto',
fontSize: 20.0,
textDirection: textDirection,
textAlign: textAlign,
);
final CanvasParagraph paragraph = plain(
paragraphStyle,
text,
textStyle: EngineTextStyle.only(color: blue),
);
final double maxWidth = bounds.width - 10;
paragraph.layout(constrain(maxWidth));
final Offset offset = Offset(bounds.left + 5, bounds.top + y + 5);
// Range for "em 12 " and the first character of `_rtlWord1`.
fillBoxes(canvas, offset, paragraph.getBoxesForRange(3, 10), lightBlue);
// Range for the second half of `_rtlWord1` and all of `_rtlWord2` and " 3".
fillBoxes(canvas, offset, paragraph.getBoxesForRange(11, 21), lightPurple);
// Range for "psum dolo".
fillBoxes(canvas, offset, paragraph.getBoxesForRange(24, 33), green);
canvas.drawParagraph(paragraph, offset);
}
test('bidi with selection', () {
const Rect bounds = Rect.fromLTWH(0, 0, 400, 500);
final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy());
const double height = 95;
// Border for ltr paragraphs.
final Rect ltrBox = const Rect.fromLTWH(0, 0, 150, 5 * height).inflate(5).translate(10, 10);
canvas.drawRect(
ltrBox,
SurfacePaintData()
..color = black.value
..style = PaintingStyle.stroke,
);
// LTR with different text align values:
paintBidiWithSelection(canvas, ltrBox, 0 * height, TextDirection.ltr, TextAlign.left);
paintBidiWithSelection(canvas, ltrBox, 1 * height, TextDirection.ltr, TextAlign.right);
paintBidiWithSelection(canvas, ltrBox, 2 * height, TextDirection.ltr, TextAlign.center);
paintBidiWithSelection(canvas, ltrBox, 3 * height, TextDirection.ltr, TextAlign.start);
paintBidiWithSelection(canvas, ltrBox, 4 * height, TextDirection.ltr, TextAlign.end);
// Border for rtl paragraphs.
final Rect rtlBox = ltrBox.translate(ltrBox.width + 10, 0);
canvas.drawRect(
rtlBox,
SurfacePaintData()
..color = black.value
..style = PaintingStyle.stroke,
);
// RTL with different text align values:
paintBidiWithSelection(canvas, rtlBox, 0 * height, TextDirection.rtl, TextAlign.left);
paintBidiWithSelection(canvas, rtlBox, 1 * height, TextDirection.rtl, TextAlign.right);
paintBidiWithSelection(canvas, rtlBox, 2 * height, TextDirection.rtl, TextAlign.center);
paintBidiWithSelection(canvas, rtlBox, 3 * height, TextDirection.rtl, TextAlign.start);
paintBidiWithSelection(canvas, rtlBox, 4 * height, TextDirection.rtl, TextAlign.end);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_bidi_selection');
});
test('bidi with selection (DOM)', () {
const Rect bounds = Rect.fromLTWH(0, 0, 400, 500);
final DomCanvas canvas = DomCanvas(domDocument.createElement('flt-picture'));
const double height = 95;
// Border for ltr paragraphs.
final Rect ltrBox = const Rect.fromLTWH(0, 0, 150, 5 * height).inflate(5).translate(10, 10);
canvas.drawRect(
ltrBox,
SurfacePaintData()
..color = black.value
..style = PaintingStyle.stroke,
);
// LTR with different text align values:
paintBidiWithSelection(canvas, ltrBox, 0 * height, TextDirection.ltr, TextAlign.left);
paintBidiWithSelection(canvas, ltrBox, 1 * height, TextDirection.ltr, TextAlign.right);
paintBidiWithSelection(canvas, ltrBox, 2 * height, TextDirection.ltr, TextAlign.center);
paintBidiWithSelection(canvas, ltrBox, 3 * height, TextDirection.ltr, TextAlign.start);
paintBidiWithSelection(canvas, ltrBox, 4 * height, TextDirection.ltr, TextAlign.end);
// Border for rtl paragraphs.
final Rect rtlBox = ltrBox.translate(ltrBox.width + 10, 0);
canvas.drawRect(
rtlBox,
SurfacePaintData()
..color = black.value
..style = PaintingStyle.stroke,
);
// RTL with different text align values:
paintBidiWithSelection(canvas, rtlBox, 0 * height, TextDirection.rtl, TextAlign.left);
paintBidiWithSelection(canvas, rtlBox, 1 * height, TextDirection.rtl, TextAlign.right);
paintBidiWithSelection(canvas, rtlBox, 2 * height, TextDirection.rtl, TextAlign.center);
paintBidiWithSelection(canvas, rtlBox, 3 * height, TextDirection.rtl, TextAlign.start);
paintBidiWithSelection(canvas, rtlBox, 4 * height, TextDirection.rtl, TextAlign.end);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_bidi_selection_dom');
});
}
| engine/lib/web_ui/test/html/paragraph/bidi_golden_test.dart/0 | {'file_path': 'engine/lib/web_ui/test/html/paragraph/bidi_golden_test.dart', 'repo_id': 'engine', 'token_count': 9179} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:math' as math;
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' as ui;
import 'package:web_engine_tester/golden_tester.dart';
import '../common/test_initialization.dart';
import 'utils.dart';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
Future<void> testMain() async {
setUpUnitTests(
withImplicitView: true,
setUpTestViewDimensions: false,
);
const ui.Rect region = ui.Rect.fromLTWH(0, 0, 128, 128);
Future<void> drawTestImageWithPaint(ui.Paint paint) async {
final ui.Codec codec = await renderer.instantiateImageCodecFromUrl(
Uri(path: '/test_images/mandrill_128.png')
);
expect(codec.frameCount, 1);
final ui.FrameInfo info = await codec.getNextFrame();
final ui.Image image = info.image;
expect(image.width, 128);
expect(image.height, 128);
final ui.PictureRecorder recorder = ui.PictureRecorder();
final ui.Canvas canvas = ui.Canvas(recorder, region);
canvas.drawImage(
image,
ui.Offset.zero,
paint,
);
await drawPictureUsingCurrentRenderer(recorder.endRecording());
}
test('blur filter', () async {
await drawTestImageWithPaint(ui.Paint()..imageFilter = ui.ImageFilter.blur(
sigmaX: 5.0,
sigmaY: 5.0,
));
await matchGoldenFile('ui_filter_blur_imagefilter.png', region: region);
});
test('dilate filter', () async {
await drawTestImageWithPaint(ui.Paint()..imageFilter = ui.ImageFilter.dilate(
radiusX: 5.0,
radiusY: 5.0,
));
await matchGoldenFile('ui_filter_dilate_imagefilter.png', region: region);
}, skip: !isSkwasm); // Only skwasm supports dilate filter right now
test('erode filter', () async {
await drawTestImageWithPaint(ui.Paint()..imageFilter = ui.ImageFilter.erode(
radiusX: 5.0,
radiusY: 5.0,
));
await matchGoldenFile('ui_filter_erode_imagefilter.png', region: region);
}, skip: !isSkwasm); // Only skwasm supports erode filter
test('matrix filter', () async {
await drawTestImageWithPaint(ui.Paint()..imageFilter = ui.ImageFilter.matrix(
Matrix4.rotationZ(math.pi / 6).toFloat64(),
filterQuality: ui.FilterQuality.high,
));
await matchGoldenFile('ui_filter_matrix_imagefilter.png', region: region);
});
test('resizing matrix filter', () async {
await drawTestImageWithPaint(ui.Paint()
..imageFilter = ui.ImageFilter.matrix(
Matrix4.diagonal3Values(0.5, 0.5, 1).toFloat64(),
filterQuality: ui.FilterQuality.high,
));
await matchGoldenFile('ui_filter_matrix_imagefilter_scaled.png',
region: region);
});
test('composed filters', () async {
final ui.ImageFilter filter = ui.ImageFilter.compose(
outer: ui.ImageFilter.matrix(
Matrix4.rotationZ(math.pi / 6).toFloat64(),
filterQuality: ui.FilterQuality.high,
),
inner: ui.ImageFilter.blur(
sigmaX: 5.0,
sigmaY: 5.0,
)
);
await drawTestImageWithPaint(ui.Paint()..imageFilter = filter);
await matchGoldenFile('ui_filter_composed_imagefilters.png', region: region);
}, skip: isHtml); // Only Skwasm and CanvasKit implement composable filters right now.
test('compose with colorfilter', () async {
final ui.ImageFilter filter = ui.ImageFilter.compose(
outer: const ui.ColorFilter.mode(
ui.Color.fromRGBO(0, 0, 255, 128),
ui.BlendMode.srcOver,
),
inner: ui.ImageFilter.blur(
sigmaX: 5.0,
sigmaY: 5.0,
)
);
await drawTestImageWithPaint(ui.Paint()..imageFilter = filter);
await matchGoldenFile('ui_filter_composed_colorfilter.png', region: region);
}, skip: isHtml); // Only Skwasm and CanvasKit implements composable filters right now.
test('color filter as image filter', () async {
const ui.ColorFilter colorFilter = ui.ColorFilter.mode(
ui.Color.fromRGBO(0, 0, 255, 128),
ui.BlendMode.srcOver,
);
await drawTestImageWithPaint(ui.Paint()..imageFilter = colorFilter);
await matchGoldenFile('ui_filter_colorfilter_as_imagefilter.png', region: region);
expect(colorFilter.toString(), 'ColorFilter.mode(Color(0x800000ff), BlendMode.srcOver)');
});
test('mode color filter', () async {
const ui.ColorFilter colorFilter = ui.ColorFilter.mode(
ui.Color.fromRGBO(0, 0, 255, 128),
ui.BlendMode.srcOver,
);
await drawTestImageWithPaint(ui.Paint()..colorFilter = colorFilter);
await matchGoldenFile('ui_filter_mode_colorfilter.png', region: region);
expect(colorFilter.toString(), 'ColorFilter.mode(Color(0x800000ff), BlendMode.srcOver)');
});
test('linearToSRGBGamma color filter', () async {
const ui.ColorFilter colorFilter = ui.ColorFilter.linearToSrgbGamma();
await drawTestImageWithPaint(ui.Paint()..colorFilter = colorFilter);
await matchGoldenFile('ui_filter_linear_to_srgb_colorfilter.png', region: region);
expect(colorFilter.toString(), 'ColorFilter.linearToSrgbGamma()');
}, skip: isHtml); // HTML renderer hasn't implemented this.
test('srgbToLinearGamma color filter', () async {
const ui.ColorFilter colorFilter = ui.ColorFilter.srgbToLinearGamma();
await drawTestImageWithPaint(ui.Paint()..colorFilter = colorFilter);
await matchGoldenFile('ui_filter_srgb_to_linear_colorfilter.png', region: region);
expect(colorFilter.toString(), 'ColorFilter.srgbToLinearGamma()');
}, skip: isHtml); // HTML renderer hasn't implemented this.
test('matrix color filter', () async {
const ui.ColorFilter sepia = ui.ColorFilter.matrix(<double>[
0.393, 0.769, 0.189, 0, 0,
0.349, 0.686, 0.168, 0, 0,
0.272, 0.534, 0.131, 0, 0,
0, 0, 0, 1, 0,
]);
await drawTestImageWithPaint(ui.Paint()..colorFilter = sepia);
await matchGoldenFile('ui_filter_matrix_colorfilter.png', region: region);
expect(sepia.toString(), startsWith('ColorFilter.matrix([0.393, 0.769, 0.189, '));
});
test('invert colors', () async {
await drawTestImageWithPaint(ui.Paint()..invertColors = true);
await matchGoldenFile('ui_filter_invert_colors.png', region: region);
});
test('invert colors with color filter', () async {
const ui.ColorFilter sepia = ui.ColorFilter.matrix(<double>[
0.393, 0.769, 0.189, 0, 0,
0.349, 0.686, 0.168, 0, 0,
0.272, 0.534, 0.131, 0, 0,
0, 0, 0, 1, 0,
]);
await drawTestImageWithPaint(ui.Paint()
..invertColors = true
..colorFilter = sepia);
await matchGoldenFile('ui_filter_invert_colors_with_colorfilter.png', region: region);
});
test('mask filter', () async {
const ui.MaskFilter maskFilter = ui.MaskFilter.blur(ui.BlurStyle.normal, 25.0);
await drawTestImageWithPaint(ui.Paint()..maskFilter = maskFilter);
await matchGoldenFile('ui_filter_blur_maskfilter.png', region: region);
});
}
| engine/lib/web_ui/test/ui/filters_test.dart/0 | {'file_path': 'engine/lib/web_ui/test/ui/filters_test.dart', 'repo_id': 'engine', 'token_count': 2802} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/ui.dart' as ui;
import 'package:web_engine_tester/golden_tester.dart';
import '../common/test_initialization.dart';
import 'utils.dart';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
Future<void> testMain() async {
const ui.Rect region = ui.Rect.fromLTWH(0, 0, 300, 300);
setUpUnitTests(
withImplicitView: true,
emulateTesterEnvironment: false,
setUpTestViewDimensions: false,
);
test('Test drawing a shadow of an opaque object', () async {
final ui.Picture picture = drawPicture((ui.Canvas canvas) {
final ui.Path path = ui.Path();
path.moveTo(50, 150);
path.cubicTo(100, 50, 200, 250, 250, 150);
canvas.drawShadow(
path,
const ui.Color(0xFF000000),
5,
false);
canvas.drawPath(path, ui.Paint()..color = const ui.Color(0xFFFF00FF));
});
await drawPictureUsingCurrentRenderer(picture);
await matchGoldenFile('shadow_opaque_object.png', region: region);
});
test('Test drawing a shadow of a translucent object', () async {
final ui.Picture picture = drawPicture((ui.Canvas canvas) {
final ui.Path path = ui.Path();
path.moveTo(50, 150);
path.cubicTo(100, 250, 200, 50, 250, 150);
canvas.drawShadow(
path,
const ui.Color(0xFF000000),
5,
true);
canvas.drawPath(path, ui.Paint()..color = const ui.Color(0x8F00FFFF));
});
await drawPictureUsingCurrentRenderer(picture);
await matchGoldenFile('shadow_translucent_object.png', region: region);
});
}
| engine/lib/web_ui/test/ui/shadow_test.dart/0 | {'file_path': 'engine/lib/web_ui/test/ui/shadow_test.dart', 'repo_id': 'engine', 'token_count': 704} |
// 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:fuchsia.builtin';
String? OnEchoString(String? str) {
print('Got echo string: $str');
return str;
}
void main(List<String> args) {
receiveEchoStringCallback = OnEchoString;
}
| engine/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_echo_server/main.dart/0 | {'file_path': 'engine/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_echo_server/main.dart', 'repo_id': 'engine', 'token_count': 114} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.