[web] remove implicit casts and implicit dynamic (flutter/engine#27882)

This commit is contained in:
Yegor
2021-08-04 17:23:21 -07:00
committed by GitHub
parent 7aaf6cbd4d
commit 2e89a0784a
42 changed files with 283 additions and 170 deletions

View File

@@ -6,11 +6,6 @@
include: ../../analysis_options.yaml
analyzer:
strong-mode:
implicit-casts: true
implicit-dynamic: true
linter:
rules:
public_member_api_docs: false

View File

@@ -61,7 +61,7 @@ class AssetManager {
final html.HttpRequest request =
await html.HttpRequest.request(url, responseType: 'arraybuffer');
final ByteBuffer response = request.response;
final ByteBuffer response = request.response as ByteBuffer;
return response.asByteData();
} on html.ProgressEvent catch (e) {
final html.EventTarget? target = e.target;

View File

@@ -969,8 +969,8 @@ class NotoDownloader {
if (assertionsEnabled) {
_debugActiveDownloadCount += 1;
}
final Future<ByteBuffer> result = html.window.fetch(url).then(
(dynamic fetchResult) => fetchResult
final Future<ByteBuffer> result = httpFetch(url).then(
(html.Body fetchResult) => fetchResult
.arrayBuffer()
.then<ByteBuffer>((dynamic x) => x as ByteBuffer));
if (assertionsEnabled) {
@@ -988,8 +988,8 @@ class NotoDownloader {
if (assertionsEnabled) {
_debugActiveDownloadCount += 1;
}
final Future<String> result = html.window.fetch(url).then(
(dynamic response) =>
final Future<String> result = httpFetch(url).then(
(html.Body response) =>
response.text().then<String>((dynamic x) => x as String));
if (assertionsEnabled) {
result.whenComplete(() {

View File

@@ -109,7 +109,7 @@ class SkiaFontCollection {
}
final List<dynamic>? fontManifest =
json.decode(utf8.decode(byteData.buffer.asUint8List()));
json.decode(utf8.decode(byteData.buffer.asUint8List())) as List<dynamic>?;
if (fontManifest == null) {
throw AssertionError(
'There was a problem trying to load FontManifest.json');
@@ -119,16 +119,16 @@ class SkiaFontCollection {
for (final Map<String, dynamic> fontFamily
in fontManifest.cast<Map<String, dynamic>>()) {
final String family = fontFamily['family']!;
final List<dynamic> fontAssets = fontFamily['fonts'];
final String family = fontFamily.readString('family');
final List<dynamic> fontAssets = fontFamily.readList('fonts');
if (family == 'Roboto') {
registeredRoboto = true;
}
for (final dynamic fontAssetItem in fontAssets) {
final Map<String, dynamic> fontAsset = fontAssetItem;
final String asset = fontAsset['asset'];
final Map<String, dynamic> fontAsset = fontAssetItem as Map<String, dynamic>;
final String asset = fontAsset.readString('asset');
_unloadedFonts
.add(_registerFont(assetManager.getAssetUrl(asset), family));
}
@@ -151,7 +151,7 @@ class SkiaFontCollection {
Future<RegisteredFont?> _registerFont(String url, String family) async {
ByteBuffer buffer;
try {
buffer = await html.window.fetch(url).then(_getArrayBuffer);
buffer = await httpFetch(url).then(_getArrayBuffer);
} catch (e) {
printWarning('Failed to load font $family at $url');
printWarning(e.toString());
@@ -178,8 +178,7 @@ class SkiaFontCollection {
return actualFamily;
}
Future<ByteBuffer> _getArrayBuffer(dynamic fetchResult) {
// TODO(yjbanov): fetchResult.arrayBuffer is a dynamic invocation. Clean it up.
Future<ByteBuffer> _getArrayBuffer(html.Body fetchResult) {
return fetchResult
.arrayBuffer()
.then<ByteBuffer>((dynamic x) => x as ByteBuffer);

View File

@@ -179,7 +179,7 @@ void _startDownloadingCanvasKit(String? canvasKitBase) {
// First check if `exports` and `module` are already defined. If so, then
// CommonJS is being used, and we shouldn't have any problems.
final js.JsFunction objectConstructor = js.context['Object'];
final js.JsFunction objectConstructor = js.context['Object'] as js.JsFunction;
if (js.context['exports'] == null) {
final js.JsObject exportsAccessor = js.JsObject.jsify(<String, dynamic>{
'get': js.allowInterop(() {

View File

@@ -361,7 +361,7 @@ class TransformEngineLayer extends ContainerLayer
@override
void preroll(PrerollContext prerollContext, Matrix4 matrix) {
final Matrix4 childMatrix = matrix * _transform;
final Matrix4 childMatrix = matrix.multiplied(_transform);
prerollContext.mutatorsStack.pushTransform(_transform);
final ui.Rect childPaintBounds = prerollChildren(prerollContext, childMatrix);
paintBounds = transformRect(_transform, childPaintBounds);

View File

@@ -725,7 +725,7 @@ class CkParagraph extends SkiaObject<SkParagraph> implements ui.Paragraph {
final List<ui.TextBox> result = <ui.TextBox>[];
for (int i = 0; i < skRects.length; i++) {
final List<double> rect = skRects[i];
final List<double> rect = skRects[i] as List<double>;
result.add(ui.TextBox.fromLTRBD(
rect[0],
rect[1],

View File

@@ -25,7 +25,7 @@ class ClipboardMessageHandler {
const MethodCodec codec = JSONMethodCodec();
bool errorEnvelopeEncoded = false;
_copyToClipboardStrategy
.setData(methodCall.arguments['text'])
.setData(methodCall.arguments['text'] as String?)
.then((bool success) {
if (success) {
callback!(codec.encodeSuccessEnvelope(true));

View File

@@ -115,12 +115,12 @@ class DomRenderer {
/// See for more details:
/// https://developer.mozilla.org/en-US/docs/Web/API/Document/hasFocus
bool get windowHasFocus =>
js_util.callMethod(html.document, 'hasFocus', <dynamic>[]) ?? false;
js_util.callMethod(html.document, 'hasFocus', <dynamic>[]) as bool;
void _setupHotRestart() {
// This persists across hot restarts to clear stale DOM.
_staleHotRestartState =
js_util.getProperty(html.window, _staleHotRestartStore);
js_util.getProperty(html.window, _staleHotRestartStore) as List<html.Element?>?;
if (_staleHotRestartState == null) {
_staleHotRestartState = <html.Element?>[];
js_util.setProperty(
@@ -238,7 +238,10 @@ class DomRenderer {
static void setElementTransform(html.Element element, String transformValue) {
js_util.setProperty(
js_util.getProperty(element, 'style'), 'transform', transformValue);
js_util.getProperty(element, 'style') as Object,
'transform',
transformValue,
);
}
void setText(html.Element element, String text) {
@@ -571,7 +574,7 @@ class DomRenderer {
return Future<bool>.value(true);
} else {
final String? lockType =
_deviceOrientationToLockType(orientations.first);
_deviceOrientationToLockType(orientations.first as String?);
if (lockType != null) {
final Completer<bool> completer = Completer<bool>();
try {

View File

@@ -69,15 +69,16 @@ class OffScreenCanvas {
0, 0, width, height]);
}
/// Converts canvas contents to an image and returns as data url.
/// Converts canvas contents to an image and returns as data URL.
Future<String> toDataUrl() {
final Completer<String> completer = Completer<String>();
if (offScreenCanvas != null) {
offScreenCanvas!.convertToBlob().then((html.Blob value) {
final html.FileReader fileReader = html.FileReader();
fileReader.onLoad.listen((html.ProgressEvent event) {
completer.complete(js_util.getProperty(
js_util.getProperty(event, 'target')!, 'result')!);
completer.complete(
js_util.getProperty(js_util.getProperty(event, 'target') as Object, 'result') as String,
);
});
fileReader.readAsDataUrl(value);
});

View File

@@ -113,8 +113,11 @@ class GlContext {
}
js_util.callMethod(glContext, 'shaderSource', <dynamic>[shader, source]);
js_util.callMethod(glContext, 'compileShader', <dynamic>[shader]);
final bool shaderStatus = js_util
.callMethod(glContext, 'getShaderParameter', <dynamic>[shader, compileStatus]);
final bool shaderStatus = js_util.callMethod(
glContext,
'getShaderParameter',
<dynamic>[shader, compileStatus],
) as bool;
if (!shaderStatus) {
throw Exception('Shader compilation failed: ${getShaderInfoLog(shader)}');
}
@@ -122,7 +125,7 @@ class GlContext {
}
Object createProgram() =>
js_util.callMethod(glContext, 'createProgram', const <dynamic>[])!;
js_util.callMethod(glContext, 'createProgram', const <dynamic>[]) as Object;
void attachShader(Object? program, Object shader) {
js_util.callMethod(glContext, 'attachShader', <dynamic>[program, shader]);
@@ -130,8 +133,12 @@ class GlContext {
void linkProgram(Object program) {
js_util.callMethod(glContext, 'linkProgram', <dynamic>[program]);
if (!js_util
.callMethod(glContext, 'getProgramParameter', <dynamic>[program, kLinkStatus])) {
final bool programStatus = js_util.callMethod(
glContext,
'getProgramParameter',
<dynamic>[program, kLinkStatus],
) as bool;
if (!programStatus) {
throw Exception(getProgramInfoLog(program));
}
}
@@ -219,7 +226,11 @@ class GlContext {
/// Destroys gl context.
void dispose() {
js_util.callMethod(_getExtension('WEBGL_lose_context'), 'loseContext', const <dynamic>[]);
js_util.callMethod(
_getExtension('WEBGL_lose_context') as Object,
'loseContext',
const <dynamic>[],
);
}
void deleteProgram(Object program) {
@@ -393,13 +404,13 @@ class GlContext {
/// Errors that occurred during failed linking or validation of program
/// objects. Typically called after [linkProgram].
String? getProgramInfoLog(Object glProgram) {
return js_util.callMethod(glContext, 'getProgramInfoLog', <dynamic>[glProgram]);
return js_util.callMethod(glContext, 'getProgramInfoLog', <dynamic>[glProgram]) as String?;
}
int? get drawingBufferWidth =>
js_util.getProperty(glContext, 'drawingBufferWidth');
js_util.getProperty(glContext, 'drawingBufferWidth') as int?;
int? get drawingBufferHeight =>
js_util.getProperty(glContext, 'drawingBufferWidth');
js_util.getProperty(glContext, 'drawingBufferWidth') as int?;
/// Reads gl contents as image data.
///

View File

@@ -12,11 +12,14 @@ import 'package:ui/ui.dart' as ui;
import 'browser_detection.dart';
import 'util.dart';
final bool _supportsDecode = js_util.getProperty(
js_util.getProperty(
js_util.getProperty(html.window, 'Image'), 'prototype'),
'decode') !=
null;
Object? get _jsImageDecodeFunction => js_util.getProperty(
js_util.getProperty(
js_util.getProperty(html.window, 'Image') as Object,
'prototype',
) as Object,
'decode',
);
final bool _supportsDecode = _jsImageDecodeFunction != null;
typedef WebOnlyImageCodecChunkCallback = void Function(
int cumulativeBytesLoaded, int expectedTotalBytes);

View File

@@ -136,7 +136,7 @@ class Keyboard {
if (data == null) {
return;
}
final Map<String, dynamic> jsonResponse = _messageCodec.decodeMessage(data);
final Map<String, dynamic> jsonResponse = _messageCodec.decodeMessage(data) as Map<String, dynamic>;
if (jsonResponse['handled'] as bool) {
// If the framework handled it, then don't propagate it any further.
event.preventDefault();

View File

@@ -124,8 +124,9 @@ class KeyboardBinding {
print(event.type);
}
if (EngineSemanticsOwner.instance.receiveGlobalEvent(event)) {
return handler(event);
return handler(event) as html.EventListener?;
}
return null;
}
assert(!_listeners.containsKey(eventName));

View File

@@ -416,12 +416,12 @@ class EnginePlatformDispatcher extends ui.PlatformDispatcher {
});
return;
case 'HapticFeedback.vibrate':
final String? type = decoded.arguments;
final String? type = decoded.arguments as String?;
domRenderer.vibrate(_getHapticFeedbackDuration(type));
replyToPlatformMessage(callback, codec.encodeSuccessEnvelope(true));
return;
case 'SystemChrome.setApplicationSwitcherDescription':
final Map<String, dynamic> arguments = decoded.arguments;
final Map<String, dynamic> arguments = decoded.arguments as Map<String, dynamic>;
// TODO(ferhat): Find more appropriate defaults? Or noop when values are null?
final String label = arguments['label'] as String? ?? '';
final int primaryColor = arguments['primaryColor'] as int? ?? 0xFF000000;
@@ -430,7 +430,7 @@ class EnginePlatformDispatcher extends ui.PlatformDispatcher {
replyToPlatformMessage(callback, codec.encodeSuccessEnvelope(true));
return;
case 'SystemChrome.setPreferredOrientations':
final List<dynamic> arguments = decoded.arguments;
final List<dynamic> arguments = decoded.arguments as List<dynamic>;
domRenderer.setPreferredOrientation(arguments).then((bool success) {
replyToPlatformMessage(
callback, codec.encodeSuccessEnvelope(success));
@@ -461,10 +461,10 @@ class EnginePlatformDispatcher extends ui.PlatformDispatcher {
case 'flutter/mousecursor':
const MethodCodec codec = StandardMethodCodec();
final MethodCall decoded = codec.decodeMethodCall(data);
final Map<dynamic, dynamic> arguments = decoded.arguments;
final Map<dynamic, dynamic> arguments = decoded.arguments as Map<dynamic, dynamic>;
switch (decoded.method) {
case 'activateSystemCursor':
MouseCursor.instance!.activateSystemCursor(arguments['kind']);
MouseCursor.instance!.activateSystemCursor(arguments.tryString('kind'));
}
return;
@@ -1001,7 +1001,7 @@ class EnginePlatformDispatcher extends ui.PlatformDispatcher {
bool _handleWebTestEnd2EndMessage(MethodCodec codec, ByteData? data) {
final MethodCall decoded = codec.decodeMethodCall(data);
final double ratio = double.parse(decoded.arguments);
final double ratio = double.parse(decoded.arguments as String);
switch (decoded.method) {
case 'setDevicePixelRatio':
window.debugOverrideDevicePixelRatio(ratio);

View File

@@ -117,7 +117,7 @@ class PlatformViewManager {
if (factoryFunction is ParameterizedPlatformViewFactory) {
content = factoryFunction(viewId, params: params);
} else {
content = factoryFunction(viewId);
content = (factoryFunction as PlatformViewFactory).call(viewId);
}
_ensureContentCorrectlySized(content, viewType);

View File

@@ -6,6 +6,7 @@ import 'dart:html' as html;
import 'dart:typed_data';
import '../services.dart';
import '../util.dart';
import 'content_manager.dart';
/// The signature for a callback for a Platform Message. From the `ui` package.
@@ -65,9 +66,9 @@ class PlatformViewMessageHandler {
MethodCall methodCall,
_PlatformMessageResponseCallback callback,
) {
final Map<dynamic, dynamic> args = methodCall.arguments;
final int viewId = args['id'];
final String viewType = args['viewType'];
final Map<dynamic, dynamic> args = methodCall.arguments as Map<dynamic, dynamic>;
final int viewId = args.readInt('id');
final String viewType = args.readString('viewType');
if (!_contentManager.knowsViewType(viewType)) {
callback(_codec.encodeErrorEnvelope(
@@ -116,7 +117,7 @@ class PlatformViewMessageHandler {
MethodCall methodCall,
_PlatformMessageResponseCallback callback,
) {
final int viewId = methodCall.arguments;
final int viewId = methodCall.arguments as int;
// The contentManager removes the slot and the contents from its internal
// cache, and the DOM.

View File

@@ -293,7 +293,7 @@ mixin _WheelEventListenerMixin on _BaseAdapter {
}
void _addWheelEventListener(html.EventListener handler) {
final dynamic eventOptions = js_util.newObject();
final Object eventOptions = js_util.newObject() as Object;
final html.EventListener jsHandler = js.allowInterop((html.Event event) => handler(event));
_BaseAdapter._nativeListeners['wheel'] = jsHandler;
js_util.setProperty(eventOptions, 'passive', false);

View File

@@ -106,7 +106,7 @@ class Profiler {
_checkBenchmarkMode();
final OnBenchmark? onBenchmark =
js_util.getProperty(html.window, '_flutter_internal_on_benchmark');
js_util.getProperty(html.window, '_flutter_internal_on_benchmark') as OnBenchmark?;
if (onBenchmark != null) {
onBenchmark(name, value);
}

View File

@@ -8,6 +8,7 @@ import 'dart:typed_data';
import '../../engine.dart' show registerHotRestartListener;
import '../services.dart';
import '../util.dart';
/// Singleton for accessing accessibility announcements from the platform.
final AccessibilityAnnouncements accessibilityAnnouncements =
@@ -58,9 +59,9 @@ class AccessibilityAnnouncements {
/// Decodes the message coming from the 'flutter/accessibility' channel.
void handleMessage(StandardMessageCodec codec, ByteData? data) {
final Map<dynamic, dynamic> inputMap =
codec.decodeMessage(data);
final Map<dynamic, dynamic> dataMap = inputMap['data'];
final String? message = dataMap['message'];
codec.decodeMessage(data) as Map<dynamic, dynamic>;
final Map<dynamic, dynamic> dataMap = inputMap.readDynamicJson('data');
final String? message = dataMap.tryString('message');
if (message != null && message.isNotEmpty) {
_initLiveRegion(message);
_removeElementTimer = Timer(durationA11yMessageIsOnDom, () {

View File

@@ -144,8 +144,8 @@ class JSONMethodCodec implements MethodCodec {
decoded[0] is String &&
(decoded[1] == null || decoded[1] is String)) {
throw PlatformException(
code: decoded[0],
message: decoded[1],
code: decoded[0] as String,
message: decoded[1] as String?,
details: decoded[2],
);
}
@@ -559,7 +559,10 @@ class StandardMethodCodec implements MethodCodec {
(errorMessage == null || errorMessage is String) &&
!buffer.hasRemaining)
throw PlatformException(
code: errorCode, message: errorMessage, details: errorDetails);
code: errorCode,
message: errorMessage as String?,
details: errorDetails,
);
else
throw const FormatException('Invalid envelope');
}

View File

@@ -46,7 +46,7 @@ class FontCollection {
}
final List<dynamic>? fontManifest =
json.decode(utf8.decode(byteData.buffer.asUint8List()));
json.decode(utf8.decode(byteData.buffer.asUint8List())) as List<dynamic>?;
if (fontManifest == null) {
throw AssertionError(
'There was a problem trying to load FontManifest.json');
@@ -60,12 +60,11 @@ class FontCollection {
for (final Map<String, dynamic> fontFamily
in fontManifest.cast<Map<String, dynamic>>()) {
final String? family = fontFamily['family'];
final List<dynamic> fontAssets = fontFamily['fonts'];
final String? family = fontFamily.tryString('family');
final List<Map<String, dynamic>> fontAssets = fontFamily.castList<Map<String, dynamic>>('fonts');
for (final dynamic fontAssetItem in fontAssets) {
final Map<String, dynamic> fontAsset = fontAssetItem;
final String asset = fontAsset['asset'];
for (final Map<String, dynamic> fontAsset in fontAssets) {
final String asset = fontAsset.readString('asset');
final Map<String, String> descriptors = <String, String>{};
for (final String descriptor in fontAsset.keys) {
if (descriptor != 'asset') {

View File

@@ -1372,7 +1372,7 @@ class DomParagraphBuilder implements ui.ParagraphBuilder {
// entirely. Occasionally there will be one [pushStyle], which causes this
// loop to run once then move on to aggregating text.
while (i < _ops.length && _ops[i] is EngineTextStyle) {
final EngineTextStyle style = _ops[i];
final EngineTextStyle style = _ops[i] as EngineTextStyle;
if (style.color != null) {
color = style.color!;
}
@@ -1554,8 +1554,8 @@ class DomParagraphBuilder implements ui.ParagraphBuilder {
/// Builds a [Paragraph] as rich text.
EngineParagraph _buildRichText() {
final List<dynamic> elementStack = <dynamic>[];
dynamic currentElement() =>
final List<html.Element> elementStack = <html.Element>[];
html.Element currentElement() =>
elementStack.isNotEmpty ? elementStack.last : _paragraphElement;
for (int i = 0; i < _ops.length; i++) {

View File

@@ -191,17 +191,20 @@ class EngineAutofillForm {
if (fields != null) {
for (final Map<String, dynamic> field in
fields.cast<Map<String, dynamic>>()) {
final Map<String, dynamic> autofillInfo = field['autofill'];
final Map<String, dynamic> autofillInfo = field.readJson('autofill');
final AutofillInfo autofill = AutofillInfo.fromFrameworkMessage(
autofillInfo,
textCapitalization: TextCapitalizationConfig.fromInputConfiguration(
field['textCapitalization']));
autofillInfo,
textCapitalization: TextCapitalizationConfig.fromInputConfiguration(
field.readString('textCapitalization'),
),
);
ids.add(autofill.uniqueIdentifier);
if (autofill.uniqueIdentifier != focusedElement.uniqueIdentifier) {
final EngineInputType engineInputType =
EngineInputType.fromName(field['inputType']['name']);
final EngineInputType engineInputType = EngineInputType.fromName(
field.readJson('inputType').readString('name'),
);
final html.HtmlElement htmlElement = engineInputType.createDomElement();
autofill.editingState.applyToDomElement(htmlElement);
@@ -367,15 +370,16 @@ class AutofillInfo {
{TextCapitalizationConfig textCapitalization =
const TextCapitalizationConfig.defaultCapitalization()}) {
assert(autofill != null); // ignore: unnecessary_null_comparison
final String uniqueIdentifier = autofill['uniqueIdentifier']!;
final List<dynamic> hintsList = autofill['hints'];
final String uniqueIdentifier = autofill.readString('uniqueIdentifier');
final List<dynamic> hintsList = autofill.readList('hints');
final EditingState editingState =
EditingState.fromFrameworkMessage(autofill['editingValue']);
EditingState.fromFrameworkMessage(autofill.readJson('editingValue'));
return AutofillInfo(
uniqueIdentifier: uniqueIdentifier,
hint: BrowserAutofillHints.instance.flutterToEngine(hintsList[0]),
editingState: editingState,
textCapitalization: textCapitalization);
uniqueIdentifier: uniqueIdentifier,
hint: BrowserAutofillHints.instance.flutterToEngine(hintsList[0] as String),
editingState: editingState,
textCapitalization: textCapitalization,
);
}
void applyToDomElement(html.HtmlElement domElement,
@@ -429,9 +433,9 @@ class EditingState {
/// valid selection range for input DOM elements.
factory EditingState.fromFrameworkMessage(
Map<String, dynamic> flutterEditingState) {
final int selectionBase = flutterEditingState['selectionBase'];
final int selectionExtent = flutterEditingState['selectionExtent'];
final String? text = flutterEditingState['text'];
final int selectionBase = flutterEditingState.readInt('selectionBase');
final int selectionExtent = flutterEditingState.readInt('selectionExtent');
final String? text = flutterEditingState.tryString('text');
return EditingState(
text: text,
@@ -576,24 +580,25 @@ class InputConfiguration {
InputConfiguration.fromFrameworkMessage(
Map<String, dynamic> flutterInputConfiguration)
: inputType = EngineInputType.fromName(
flutterInputConfiguration['inputType']['name'],
isDecimal: flutterInputConfiguration['inputType']['decimal'] ?? false,
flutterInputConfiguration.readJson('inputType').readString('name'),
isDecimal: flutterInputConfiguration.readJson('inputType').tryBool('decimal') ?? false,
),
inputAction =
flutterInputConfiguration['inputAction'] ?? 'TextInputAction.done',
obscureText = flutterInputConfiguration['obscureText'] ?? false,
readOnly = flutterInputConfiguration['readOnly'] ?? false,
autocorrect = flutterInputConfiguration['autocorrect'] ?? true,
flutterInputConfiguration.tryString('inputAction') ?? 'TextInputAction.done',
obscureText = flutterInputConfiguration.tryBool('obscureText') ?? false,
readOnly = flutterInputConfiguration.tryBool('readOnly') ?? false,
autocorrect = flutterInputConfiguration.tryBool('autocorrect') ?? true,
textCapitalization = TextCapitalizationConfig.fromInputConfiguration(
flutterInputConfiguration['textCapitalization'],
flutterInputConfiguration.readString('textCapitalization'),
),
autofill = flutterInputConfiguration.containsKey('autofill')
? AutofillInfo.fromFrameworkMessage(
flutterInputConfiguration['autofill'])
flutterInputConfiguration.readJson('autofill'))
: null,
autofillGroup = EngineAutofillForm.fromFrameworkMessage(
flutterInputConfiguration['autofill'],
flutterInputConfiguration['fields']);
flutterInputConfiguration.tryJson('autofill'),
flutterInputConfiguration.tryList('fields'),
);
/// The type of information being edited in the input control.
final EngineInputType inputType;
@@ -1597,8 +1602,8 @@ class TextEditingChannel {
switch (call.method) {
case 'TextInput.setClient':
command = TextInputSetClient(
clientId: call.arguments[0],
configuration: InputConfiguration.fromFrameworkMessage(call.arguments[1]),
clientId: call.arguments[0] as int,
configuration: InputConfiguration.fromFrameworkMessage(call.arguments[1] as Map<String, dynamic>),
);
break;
@@ -1606,13 +1611,17 @@ class TextEditingChannel {
// Set configuration eagerly because it contains data about the text
// field used to flush the command queue. However, delaye applying the
// configuration because the strategy may not be available yet.
implementation.configuration = InputConfiguration.fromFrameworkMessage(call.arguments);
implementation.configuration = InputConfiguration.fromFrameworkMessage(
call.arguments as Map<String, dynamic>
);
command = const TextInputUpdateConfig();
break;
case 'TextInput.setEditingState':
command = TextInputSetEditingState(
state: EditingState.fromFrameworkMessage(call.arguments),
state: EditingState.fromFrameworkMessage(
call.arguments as Map<String, dynamic>
),
);
break;
@@ -1622,13 +1631,17 @@ class TextEditingChannel {
case 'TextInput.setEditableSizeAndTransform':
command = TextInputSetEditableSizeAndTransform(
geometry: EditableTextGeometry.fromFrameworkMessage(call.arguments),
geometry: EditableTextGeometry.fromFrameworkMessage(
call.arguments as Map<String, dynamic>
),
);
break;
case 'TextInput.setStyle':
command = TextInputSetStyle(
style: EditableTextStyle.fromFrameworkMessage(call.arguments),
style: EditableTextStyle.fromFrameworkMessage(
call.arguments as Map<String, dynamic>,
),
);
break;
@@ -1823,9 +1836,9 @@ class EditableTextStyle {
assert(flutterStyle.containsKey('textAlignIndex'));
assert(flutterStyle.containsKey('textDirectionIndex'));
final int textAlignIndex = flutterStyle['textAlignIndex'];
final int textDirectionIndex = flutterStyle['textDirectionIndex'];
final int? fontWeightIndex = flutterStyle['fontWeightIndex'];
final int textAlignIndex = flutterStyle['textAlignIndex'] as int;
final int textDirectionIndex = flutterStyle['textDirectionIndex'] as int;
final int? fontWeightIndex = flutterStyle['fontWeightIndex'] as int?;
// Convert [fontWeightIndex] to its CSS equivalent value.
final String fontWeight = fontWeightIndex != null
@@ -1836,8 +1849,8 @@ class EditableTextStyle {
// corresponding enum values in [ui.TextAlign] and [ui.TextDirection]
// respectively.
return EditableTextStyle(
fontSize: flutterStyle['fontSize'],
fontFamily: flutterStyle['fontFamily'],
fontSize: flutterStyle.tryDouble('fontSize'),
fontFamily: flutterStyle.tryString('fontFamily'),
textAlign: ui.TextAlign.values[textAlignIndex],
textDirection: ui.TextDirection.values[textDirectionIndex],
fontWeight: fontWeight,
@@ -1885,10 +1898,10 @@ class EditableTextGeometry {
assert(encodedGeometry.containsKey('transform'));
final List<double> transformList =
List<double>.from(encodedGeometry['transform']);
List<double>.from(encodedGeometry.readList('transform'));
return EditableTextGeometry(
width: encodedGeometry['width'],
height: encodedGeometry['height'],
width: encodedGeometry.readDouble('width'),
height: encodedGeometry.readDouble('height'),
globalTransform: Float32List.fromList(transformList),
);
}

View File

@@ -390,7 +390,7 @@ String colorComponentsToCssString(int r, int g, int b, int a) {
/// We need this in [BitmapCanvas] and [RecordingCanvas] to swallow this
/// Firefox exception without interfering with others (potentially useful
/// for the programmer).
bool isNsErrorFailureException(dynamic e) {
bool isNsErrorFailureException(Object e) {
return js_util.getProperty(e, 'name') == 'NS_ERROR_FAILURE';
}
@@ -560,3 +560,83 @@ String blurSigmasToCssString(double sigmaX, double sigmaY) {
bool unsafeIsNull(dynamic object) {
return object == null;
}
/// A typed variant of [html.Window.fetch].
Future<html.Body> httpFetch(String url) async {
final dynamic result = await html.window.fetch(url);
return result as html.Body;
}
/// Extensions to [Map] that make it easier to treat it as a JSON object. The
/// keys are `dynamic` because when JSON is deserialized from method channels
/// it arrives as `Map<dynamic, dynamic>`.
// TODO(yjbanov): use Json typedef when type aliases are shipped
extension JsonExtensions on Map<dynamic, dynamic> {
Map<String, dynamic> readJson(String propertyName) {
return this[propertyName] as Map<String, dynamic>;
}
Map<String, dynamic>? tryJson(String propertyName) {
return this[propertyName] as Map<String, dynamic>?;
}
Map<dynamic, dynamic> readDynamicJson(String propertyName) {
return this[propertyName] as Map<dynamic, dynamic>;
}
Map<dynamic, dynamic>? tryDynamicJson(String propertyName) {
return this[propertyName] as Map<dynamic, dynamic>?;
}
List<dynamic> readList(String propertyName) {
return this[propertyName] as List<dynamic>;
}
List<dynamic>? tryList(String propertyName) {
return this[propertyName] as List<dynamic>?;
}
List<T> castList<T>(String propertyName) {
return (this[propertyName] as List<dynamic>).cast<T>();
}
List<T>? tryCastList<T>(String propertyName) {
final List<dynamic>? rawList = tryList(propertyName);
if (rawList == null) {
return null;
}
return rawList.cast<T>();
}
String readString(String propertyName) {
return this[propertyName] as String;
}
String? tryString(String propertyName) {
return this[propertyName] as String?;
}
bool readBool(String propertyName) {
return this[propertyName] as bool;
}
bool? tryBool(String propertyName) {
return this[propertyName] as bool?;
}
int readInt(String propertyName) {
return this[propertyName] as int;
}
int? tryInt(String propertyName) {
return this[propertyName] as int?;
}
double readDouble(String propertyName) {
return this[propertyName] as double;
}
double? tryDouble(String propertyName) {
return this[propertyName] as double?;
}
}

View File

@@ -375,22 +375,6 @@ class Matrix4 {
det3_201_012 * m[15];
}
/// Returns a new vector or matrix by multiplying [this] with [arg].
dynamic operator *(dynamic arg) {
if (arg is double) {
return scaled(arg);
}
if (arg is Vector3) {
final Vector3 copy = arg.clone();
transform3(copy.storage);
return copy;
}
if (arg is Matrix4) {
return multiplied(arg);
}
throw ArgumentError(arg);
}
/// Transform [arg] of type [Vector3] using the perspective transformation
/// defined by [this].
Vector3 perspectiveTransform(Vector3 arg) {

View File

@@ -21,6 +21,7 @@ import 'navigation/url_strategy.dart';
import 'platform_dispatcher.dart';
import 'services.dart';
import 'test_embedding.dart';
import 'util.dart';
typedef _HandleMessageCallBack = Future<bool> Function();
@@ -152,7 +153,7 @@ class EngineFlutterWindow extends ui.SingletonFlutterWindow {
Future<bool> handleNavigationMessage(ByteData? data) async {
return _waitInTheLine(() async {
final MethodCall decoded = const JSONMethodCodec().decodeMethodCall(data);
final Map<String, dynamic>? arguments = decoded.arguments;
final Map<String, dynamic>? arguments = decoded.arguments as Map<String, dynamic>?;
switch (decoded.method) {
case 'selectMultiEntryHistory':
await _useMultiEntryBrowserHistory();
@@ -164,14 +165,14 @@ class EngineFlutterWindow extends ui.SingletonFlutterWindow {
case 'routeUpdated': // deprecated
assert(arguments != null);
await _useSingleEntryBrowserHistory();
browserHistory.setRouteName(arguments!['routeName']);
browserHistory.setRouteName(arguments!.tryString('routeName'));
return true;
case 'routeInformationUpdated':
assert(arguments != null);
browserHistory.setRouteName(
arguments!['location'],
state: arguments['state'],
replace: arguments['replace'] ?? false,
arguments!.tryString('location'),
state: arguments.tryString('state'),
replace: arguments.tryBool('replace') ?? false,
);
return true;
}

View File

@@ -40,7 +40,7 @@ Future<void> testMain() async {
const MethodCodec codec = JSONMethodCodec();
final Completer<bool> completer = Completer<bool>();
void callback(ByteData? data) {
completer.complete(codec.decodeEnvelope(data!));
completer.complete(codec.decodeEnvelope(data!) as bool);
}
clipboardMessageHandler.setDataMethodCall(
@@ -78,7 +78,7 @@ Future<void> testMain() async {
const MethodCodec codec = JSONMethodCodec();
final Completer<Map<String, dynamic>> completer = Completer<Map<String, dynamic>>();
void callback(ByteData? data) {
completer.complete(codec.decodeEnvelope(data!));
completer.complete(codec.decodeEnvelope(data!) as Map<String, dynamic>);
}
clipboardMessageHandler.getDataMethodCall(callback);

View File

@@ -2325,7 +2325,7 @@ mixin _ButtonedEventMixin on _BasicEventContext {
required double? deltaX,
required double? deltaY,
}) {
final Function jsWheelEvent = js_util.getProperty(html.window, 'WheelEvent');
final Function jsWheelEvent = js_util.getProperty(html.window, 'WheelEvent') as Function;
final List<dynamic> eventArgs = <dynamic>[
'wheel',
<String, dynamic>{
@@ -2336,7 +2336,10 @@ mixin _ButtonedEventMixin on _BasicEventContext {
'deltaY': deltaY,
}
];
return js_util.callConstructor(jsWheelEvent, js_util.jsify(eventArgs));
return js_util.callConstructor(
jsWheelEvent,
js_util.jsify(eventArgs) as List<Object?>,
) as html.Event;
}
}
@@ -2550,7 +2553,7 @@ class _MouseEventContext extends _BasicEventContext
double? clientY,
}) {
final Function jsMouseEvent =
js_util.getProperty(html.window, 'MouseEvent');
js_util.getProperty(html.window, 'MouseEvent') as Function;
final List<dynamic> eventArgs = <dynamic>[
type,
<String, dynamic>{
@@ -2560,7 +2563,10 @@ class _MouseEventContext extends _BasicEventContext
'clientY': clientY,
}
];
return js_util.callConstructor(jsMouseEvent, js_util.jsify(eventArgs));
return js_util.callConstructor(
jsMouseEvent,
js_util.jsify(eventArgs) as List<Object?>,
) as html.MouseEvent;
}
}

View File

@@ -77,8 +77,9 @@ void _profilerTests() {
expect(data, isEmpty);
// Not even a callback.
jsOnBenchmark('string');
expect(
() => jsOnBenchmark('string'),
() => Profiler.instance.benchmark('foo', 123),
throwsA(isA<TypeError>()),
);
});
@@ -159,5 +160,11 @@ class BenchmarkDatapoint {
}
void jsOnBenchmark(dynamic listener) {
js_util.setProperty(html.window, '_flutter_internal_on_benchmark', listener != null ? js.allowInterop(listener) : null);
js_util.setProperty(
html.window,
'_flutter_internal_on_benchmark',
listener is Function
? js.allowInterop(listener)
: listener,
);
}

View File

@@ -918,6 +918,6 @@ HtmlImage createTestImage({int width = 100, int height = 50}) {
ctx.fillRect(66, 0, 33, 50);
ctx.fill();
final html.ImageElement imageElement = html.ImageElement();
imageElement.src = js_util.callMethod(canvas, 'toDataURL', <dynamic>[]);
imageElement.src = js_util.callMethod(canvas, 'toDataURL', <dynamic>[]) as String;
return HtmlImage(imageElement, width, height);
}

View File

@@ -140,6 +140,6 @@ engine.HtmlImage createTestImage({int width = 200, int height = 150}) {
ctx.fillRect(2 * width / 3, 0, width / 3, height);
ctx.fill();
final html.ImageElement imageElement = html.ImageElement();
imageElement.src = js_util.callMethod(canvas, 'toDataURL', <dynamic>[]);
imageElement.src = js_util.callMethod(canvas, 'toDataURL', <dynamic>[]) as String;
return engine.HtmlImage(imageElement, width, height);
}

View File

@@ -120,6 +120,6 @@ HtmlImage createTestImage() {
ctx.fillRect(66, 0, 33, 50);
ctx.fill();
final html.ImageElement imageElement = html.ImageElement();
imageElement.src = js_util.callMethod(canvas, 'toDataURL', <dynamic>[]);
imageElement.src = js_util.callMethod(canvas, 'toDataURL', <dynamic>[]) as String;
return HtmlImage(imageElement, width, height);
}

View File

@@ -189,6 +189,6 @@ HtmlImage createTestImage({int width = 200, int height = 150}) {
ctx.fillRect(2 * width / 3, 0, width / 3, height);
ctx.fill();
final html.ImageElement imageElement = html.ImageElement();
imageElement.src = js_util.callMethod(canvas, 'toDataURL', <dynamic>[]);
imageElement.src = js_util.callMethod(canvas, 'toDataURL', <dynamic>[]) as String;
return HtmlImage(imageElement, width, height);
}

View File

@@ -734,7 +734,7 @@ HtmlImage createTestImage({int width = 100, int height = 50}) {
ctx.fillRect(66, 0, 33, 50);
ctx.fill();
final html.ImageElement imageElement = html.ImageElement();
imageElement.src = js_util.callMethod(canvas, 'toDataURL', <dynamic>[]);
imageElement.src = js_util.callMethod(canvas, 'toDataURL', <dynamic>[]) as String;
return HtmlImage(imageElement, width, height);
}

View File

@@ -424,6 +424,6 @@ Future<HtmlImage> createTestImage({int width = 50, int height = 40}) {
imageElement.onLoad.listen((html.Event event) {
completer.complete(HtmlImage(imageElement, width, height));
});
imageElement.src = js_util.callMethod(canvas, 'toDataURL', <dynamic>[]);
imageElement.src = js_util.callMethod(canvas, 'toDataURL', <dynamic>[]) as String;
return completer.future;
}

View File

@@ -145,6 +145,6 @@ HtmlImage createTestImage() {
ctx.fillRect(width2, width2, width2, width2);
ctx.fill();
final html.ImageElement imageElement = html.ImageElement();
imageElement.src = js_util.callMethod(canvas, 'toDataURL', <dynamic>[]);
imageElement.src = js_util.callMethod(canvas, 'toDataURL', <dynamic>[]) as String;
return HtmlImage(imageElement, width, height);
}

View File

@@ -48,7 +48,7 @@ void testMain() {
ui.window.onPlatformMessage = (String channel, ByteData? data,
ui.PlatformMessageResponseCallback? callback) {
channelReceived = channel;
dataReceived = const JSONMessageCodec().decodeMessage(data);
dataReceived = const JSONMessageCodec().decodeMessage(data) as Map<String, dynamic>?;
};
html.KeyboardEvent event;
@@ -78,7 +78,7 @@ void testMain() {
ui.window.onPlatformMessage = (String channel, ByteData? data,
ui.PlatformMessageResponseCallback? callback) {
channelReceived = channel;
dataReceived = const JSONMessageCodec().decodeMessage(data);
dataReceived = const JSONMessageCodec().decodeMessage(data) as Map<String, dynamic>?;
};
html.KeyboardEvent event;
@@ -107,7 +107,7 @@ void testMain() {
Map<String, dynamic>? dataReceived;
ui.window.onPlatformMessage = (String channel, ByteData? data,
ui.PlatformMessageResponseCallback? callback) {
dataReceived = const JSONMessageCodec().decodeMessage(data);
dataReceived = const JSONMessageCodec().decodeMessage(data) as Map<String, dynamic>?;
};
html.KeyboardEvent event;
@@ -157,7 +157,7 @@ void testMain() {
final List<Map<String, dynamic>> messages = <Map<String, dynamic>>[];
ui.window.onPlatformMessage = (String channel, ByteData? data,
ui.PlatformMessageResponseCallback? callback) {
messages.add(const JSONMessageCodec().decodeMessage(data));
messages.add(const JSONMessageCodec().decodeMessage(data) as Map<String, dynamic>);
};
html.KeyboardEvent event;
@@ -339,7 +339,7 @@ void testMain() {
final List<Map<String, dynamic>> messages = <Map<String, dynamic>>[];
ui.window.onPlatformMessage = (String channel, ByteData? data,
ui.PlatformMessageResponseCallback? callback) {
messages.add(const JSONMessageCodec().decodeMessage(data));
messages.add(const JSONMessageCodec().decodeMessage(data) as Map<String, dynamic>);
};
dispatchKeyboardEvent(
@@ -442,7 +442,7 @@ void testMain() {
final List<Map<String, dynamic>> messages = <Map<String, dynamic>>[];
ui.window.onPlatformMessage = (String channel, ByteData? data,
ui.PlatformMessageResponseCallback? callback) {
messages.add(const JSONMessageCodec().decodeMessage(data));
messages.add(const JSONMessageCodec().decodeMessage(data) as Map<String, dynamic>);
};
dispatchKeyboardEvent(
@@ -514,7 +514,7 @@ void testMain() {
final List<Map<String, dynamic>> messages = <Map<String, dynamic>>[];
ui.window.onPlatformMessage = (String channel, ByteData? data,
ui.PlatformMessageResponseCallback? callback) {
messages.add(const JSONMessageCodec().decodeMessage(data));
messages.add(const JSONMessageCodec().decodeMessage(data) as Map<String, dynamic>);
};
dispatchKeyboardEvent(
@@ -544,7 +544,7 @@ void testMain() {
final List<Map<String, dynamic>> messages = <Map<String, dynamic>>[];
ui.window.onPlatformMessage = (String channel, ByteData? data,
ui.PlatformMessageResponseCallback? callback) {
messages.add(const JSONMessageCodec().decodeMessage(data));
messages.add(const JSONMessageCodec().decodeMessage(data) as Map<String, dynamic>);
};
dispatchKeyboardEvent(
@@ -625,7 +625,7 @@ html.KeyboardEvent dispatchKeyboardEvent(
target ??= html.window;
final Function jsKeyboardEvent =
js_util.getProperty(html.window, 'KeyboardEvent');
js_util.getProperty(html.window, 'KeyboardEvent') as Function;
final List<dynamic> eventArgs = <dynamic>[
type,
<String, dynamic>{
@@ -640,8 +640,10 @@ html.KeyboardEvent dispatchKeyboardEvent(
'cancelable': true,
}
];
final html.KeyboardEvent event =
js_util.callConstructor(jsKeyboardEvent, js_util.jsify(eventArgs));
final html.KeyboardEvent event = js_util.callConstructor(
jsKeyboardEvent,
js_util.jsify(eventArgs) as List<Object?>,
) as html.KeyboardEvent;
target.dispatchEvent(event);
return event;

View File

@@ -303,6 +303,9 @@ String canonicalizeHtml(String htmlContent,
if (mode != HtmlComparisonMode.noAttributes) {
original.attributes.forEach((dynamic name, String value) {
if (name is! String) {
throw '"$name" should be String but was ${name.runtimeType}.';
}
if (name == 'style') {
return;
}

View File

@@ -41,7 +41,7 @@ Future<void> testMain() async {
final html.HttpRequest response = await html.HttpRequest.request(
_testFontUrl,
responseType: 'arraybuffer');
await ui.loadFontFromList(Uint8List.view(response.response),
await ui.loadFontFromList(Uint8List.view(response.response as ByteBuffer),
fontFamily: 'Blehm');
expect(_containsFontFamily('Blehm'), isTrue);
@@ -73,7 +73,7 @@ Future<void> testMain() async {
final html.HttpRequest response = await html.HttpRequest.request(
_testFontUrl,
responseType: 'arraybuffer');
await ui.loadFontFromList(Uint8List.view(response.response),
await ui.loadFontFromList(Uint8List.view(response.response as ByteBuffer),
fontFamily: 'Blehm');
// Verifies the font is loaded, and the cache is cleaned.
@@ -101,7 +101,7 @@ Future<void> testMain() async {
final html.HttpRequest response = await html.HttpRequest.request(
_testFontUrl,
responseType: 'arraybuffer');
await ui.loadFontFromList(Uint8List.view(response.response),
await ui.loadFontFromList(Uint8List.view(response.response as ByteBuffer),
fontFamily: 'Blehm');
final Completer<void> completer = Completer<void>();
html.window.requestAnimationFrame( (_) { completer.complete(); } );

View File

@@ -390,7 +390,7 @@ void testMain() {
int clientId = 0;
/// Emulates sending of a message by the framework to the engine.
void sendFrameworkMessage(dynamic message) {
void sendFrameworkMessage(ByteData? message) {
textEditing!.channel.handleTextInput(message, (ByteData? data) {});
}
@@ -2000,7 +2000,7 @@ KeyboardEvent dispatchKeyboardEvent(
String type, {
required int keyCode,
}) {
final Function jsKeyboardEvent = js_util.getProperty(window, 'KeyboardEvent');
final Function jsKeyboardEvent = js_util.getProperty(window, 'KeyboardEvent') as Function;
final List<dynamic> eventArgs = <dynamic>[
type,
<String, dynamic>{
@@ -2009,7 +2009,7 @@ KeyboardEvent dispatchKeyboardEvent(
}
];
final KeyboardEvent event =
js_util.callConstructor(jsKeyboardEvent, js_util.jsify(eventArgs));
js_util.callConstructor(jsKeyboardEvent, js_util.jsify(eventArgs) as List<Object?>?) as KeyboardEvent;
target.dispatchEvent(event);
return event;

View File

@@ -119,9 +119,9 @@ final String lineBreakCodegen =
Future<void> main(List<String> arguments) async {
final ArgResults result = argParser.parse(arguments);
final PropertiesSyncer syncer = getSyncer(
result['words'],
result['lines'],
result['dry'],
result['words'] as String?,
result['lines'] as String?,
result['dry'] as bool,
);
syncer.perform();