forked from flutter/engine
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshell_test.dart
More file actions
561 lines (481 loc) · 15.7 KB
/
shell_test.dart
File metadata and controls
561 lines (481 loc) · 15.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
// 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' show scheduleMicrotask;
import 'dart:convert' show json, utf8;
import 'dart:isolate';
import 'dart:typed_data';
import 'dart:ui';
void expect(Object? a, Object? b) {
if (a != b) {
throw AssertionError('Expected $a to == $b');
}
}
void main() {}
@pragma('vm:entry-point')
void mainNotifyNative() {
notifyNative();
}
@pragma('vm:external-name', 'NativeReportTimingsCallback')
external void nativeReportTimingsCallback(List<int> timings);
@pragma('vm:external-name', 'NativeOnBeginFrame')
external void nativeOnBeginFrame(int microseconds);
@pragma('vm:external-name', 'NativeOnPointerDataPacket')
external void nativeOnPointerDataPacket(List<int> sequences);
@pragma('vm:entry-point')
void onErrorA() {
PlatformDispatcher.instance.onError = (Object error, StackTrace? stack) {
notifyErrorA(error.toString());
return true;
};
Future<void>.delayed(const Duration(seconds: 2)).then((_) {
throw Exception('I should be coming from A');
});
}
@pragma('vm:entry-point')
void onErrorB() {
PlatformDispatcher.instance.onError = (Object error, StackTrace? stack) {
notifyErrorB(error.toString());
return true;
};
throw Exception('I should be coming from B');
}
@pragma('vm:external-name', 'NotifyErrorA')
external void notifyErrorA(String message);
@pragma('vm:external-name', 'NotifyErrorB')
external void notifyErrorB(String message);
@pragma('vm:entry-point')
void drawFrames() {
// Wait for native to tell us to start going.
notifyNative();
PlatformDispatcher.instance.onBeginFrame = (Duration beginTime) {
final SceneBuilder builder = SceneBuilder();
final PictureRecorder recorder = PictureRecorder();
final Canvas canvas = Canvas(recorder);
canvas.drawPaint(Paint()..color = const Color(0xFFABCDEF));
final Picture picture = recorder.endRecording();
builder.addPicture(Offset.zero, picture);
final Scene scene = builder.build();
window.render(scene);
scene.dispose();
picture.dispose();
};
PlatformDispatcher.instance.scheduleFrame();
}
@pragma('vm:entry-point')
void reportTimingsMain() {
PlatformDispatcher.instance.onReportTimings = (List<FrameTiming> timings) {
List<int> timestamps = [];
for (FrameTiming t in timings) {
for (FramePhase phase in FramePhase.values) {
timestamps.add(t.timestampInMicroseconds(phase));
}
}
nativeReportTimingsCallback(timestamps);
PlatformDispatcher.instance.onReportTimings = (List<FrameTiming> timings) {};
};
}
@pragma('vm:entry-point')
void onBeginFrameMain() {
PlatformDispatcher.instance.onBeginFrame = (Duration beginTime) {
nativeOnBeginFrame(beginTime.inMicroseconds);
};
PlatformDispatcher.instance.scheduleFrame();
}
@pragma('vm:entry-point')
void onPointerDataPacketMain() {
PlatformDispatcher.instance.onPointerDataPacket = (PointerDataPacket packet) {
List<int> sequence = <int>[];
for (PointerData data in packet.data) {
sequence.add(PointerChange.values.indexOf(data.change));
}
nativeOnPointerDataPacket(sequence);
};
}
@pragma('vm:entry-point')
void emptyMain() {}
@pragma('vm:entry-point')
void reportMetrics() {
window.onMetricsChanged = () {
_reportMetrics(
window.devicePixelRatio,
window.physicalSize.width,
window.physicalSize.height,
);
};
}
@pragma('vm:external-name', 'ReportMetrics')
external void _reportMetrics(double devicePixelRatio, double width, double height);
@pragma('vm:entry-point')
void dummyReportTimingsMain() {
PlatformDispatcher.instance.onReportTimings = (List<FrameTiming> timings) {};
}
@pragma('vm:entry-point')
void fixturesAreFunctionalMain() {
sayHiFromFixturesAreFunctionalMain();
}
@pragma('vm:external-name', 'SayHiFromFixturesAreFunctionalMain')
external void sayHiFromFixturesAreFunctionalMain();
@pragma('vm:entry-point')
@pragma('vm:external-name', 'NotifyNative')
external void notifyNative();
@pragma('vm:entry-point')
void thousandCallsToNative() {
for (int i = 0; i < 1000; i++) {
notifyNative();
}
}
void secondaryIsolateMain(String message) {
print('Secondary isolate got message: ' + message);
notifyNative();
}
@pragma('vm:entry-point')
void testCanLaunchSecondaryIsolate() {
Isolate.spawn(secondaryIsolateMain, 'Hello from root isolate.');
notifyNative();
}
@pragma('vm:entry-point')
void testSkiaResourceCacheSendsResponse() {
final PlatformMessageResponseCallback callback = (ByteData? data) {
if (data == null) {
throw 'Response must not be null.';
}
final String response = utf8.decode(data.buffer.asUint8List());
final List<bool> jsonResponse = json.decode(response).cast<bool>();
if (jsonResponse[0] != true) {
throw 'Response was not true';
}
notifyNative();
};
const String jsonRequest = '''{
"method": "Skia.setResourceCacheMaxBytes",
"args": 10000
}''';
PlatformDispatcher.instance.sendPlatformMessage(
'flutter/skia',
ByteData.sublistView(utf8.encode(jsonRequest)),
callback,
);
}
@pragma('vm:external-name', 'NotifyWidthHeight')
external void notifyWidthHeight(int width, int height);
@pragma('vm:entry-point')
void canCreateImageFromDecompressedData() {
const int imageWidth = 10;
const int imageHeight = 10;
final Uint8List pixels = Uint8List.fromList(List<int>.generate(
imageWidth * imageHeight * 4,
(int i) => i % 4 < 2 ? 0x00 : 0xFF,
));
decodeImageFromPixels(
pixels,
imageWidth,
imageHeight,
PixelFormat.rgba8888,
(Image image) {
notifyWidthHeight(image.width, image.height);
},
);
}
@pragma('vm:entry-point')
void canAccessIsolateLaunchData() {
notifyMessage(
utf8.decode(
PlatformDispatcher.instance.getPersistentIsolateData()!.buffer.asUint8List(),
),
);
}
@pragma('vm:entry-point')
void performanceModeImpactsNotifyIdle() {
notifyNativeBool(false);
PlatformDispatcher.instance.requestDartPerformanceMode(DartPerformanceMode.latency);
notifyNativeBool(true);
PlatformDispatcher.instance.requestDartPerformanceMode(DartPerformanceMode.balanced);
}
@pragma('vm:entry-point')
void callNotifyDestroyed() {
notifyDestroyed();
}
@pragma('vm:external-name', 'NotifyMessage')
external void notifyMessage(String string);
@pragma('vm:entry-point')
void canRegisterImageDecoders() {
decodeImageFromList(
// The test ImageGenerator will always behave the same regardless of input.
Uint8List(1),
(Image result) {
notifyWidthHeight(result.width, result.height);
},
);
}
@pragma('vm:external-name', 'NotifyLocalTime')
external void notifyLocalTime(String string);
@pragma('vm:external-name', 'WaitFixture')
external bool waitFixture();
// Return local date-time as a string, to an hour resolution. So, "2020-07-23
// 14:03:22" will become "2020-07-23 14".
String localTimeAsString() {
final now = DateTime.now().toLocal();
// This is: "$y-$m-$d $h:$min:$sec.$ms$us";
final timeStr = now.toString();
// Forward only "$y-$m-$d $h" for timestamp comparison. Not using DateTime
// formatting since package:intl is not available.
return timeStr.split(":")[0];
}
@pragma('vm:entry-point')
void localtimesMatch() {
notifyLocalTime(localTimeAsString());
}
@pragma('vm:entry-point')
void timezonesChange() {
do {
notifyLocalTime(localTimeAsString());
} while (waitFixture());
}
@pragma('vm:external-name', 'NotifyCanAccessResource')
external void notifyCanAccessResource(bool success);
@pragma('vm:external-name', 'NotifySetAssetBundlePath')
external void notifySetAssetBundlePath();
@pragma('vm:entry-point')
void canAccessResourceFromAssetDir() async {
notifySetAssetBundlePath();
window.sendPlatformMessage(
'flutter/assets',
ByteData.sublistView(utf8.encode('kernel_blob.bin')),
(ByteData? byteData) {
notifyCanAccessResource(byteData != null);
},
);
}
@pragma('vm:external-name', 'NotifyNativeWhenEngineRun')
external void notifyNativeWhenEngineRun(bool success);
@pragma('vm:external-name', 'NotifyNativeWhenEngineSpawn')
external void notifyNativeWhenEngineSpawn(bool success);
@pragma('vm:entry-point')
void canReceiveArgumentsWhenEngineRun(List<String> args) {
notifyNativeWhenEngineRun(args.length == 2 && args[0] == 'foo' && args[1] == 'bar');
}
@pragma('vm:entry-point')
void canReceiveArgumentsWhenEngineSpawn(List<String> args) {
notifyNativeWhenEngineSpawn(args.length == 2 && args[0] == 'arg1' && args[1] == 'arg2');
}
@pragma('vm:entry-point')
void onBeginFrameWithNotifyNativeMain() {
PlatformDispatcher.instance.onBeginFrame = (Duration beginTime) {
nativeOnBeginFrame(beginTime.inMicroseconds);
};
notifyNative();
}
@pragma('vm:entry-point')
void frameCallback(Object? image, int durationMilliseconds, String decodeError) {
if (image == null) {
throw Exception('Expeccted image in frame callback to be non-null');
}
}
Picture CreateRedBox(Size size) {
Paint paint = Paint()
..color = Color.fromARGB(255, 255, 0, 0)
..style = PaintingStyle.fill;
PictureRecorder baseRecorder = PictureRecorder();
Canvas canvas = Canvas(baseRecorder);
canvas.drawRect(Rect.fromLTRB(0.0, 0.0, size.width, size.height), paint);
return baseRecorder.endRecording();
}
@pragma('vm:entry-point')
void scene_with_red_box() {
PlatformDispatcher.instance.onBeginFrame = (Duration duration) {
SceneBuilder builder = SceneBuilder();
builder.pushOffset(0.0, 0.0);
builder.addPicture(Offset(0.0, 0.0), CreateRedBox(Size(2.0, 2.0)));
builder.pop();
PlatformDispatcher.instance.views.first.render(builder.build());
};
PlatformDispatcher.instance.scheduleFrame();
}
@pragma('vm:external-name', 'NativeOnBeforeToImageSync')
external void onBeforeToImageSync();
@pragma('vm:entry-point')
Future<void> toImageSync() async {
final PictureRecorder recorder = PictureRecorder();
final Canvas canvas = Canvas(recorder);
canvas.drawPaint(Paint()..color = const Color(0xFFAAAAAA));
final Picture picture = recorder.endRecording();
onBeforeToImageSync();
final Image image = picture.toImageSync(20, 25);
expect(image.width, 20);
expect(image.height, 25);
final ByteData dataBefore = (await image.toByteData())!;
expect(dataBefore.lengthInBytes, 20 * 25 * 4);
for (final int byte in dataBefore.buffer.asUint32List()) {
expect(byte, 0xFFAAAAAA);
}
// Cause the rasterizer to get torn down.
notifyNative();
final ByteData dataAfter = (await image.toByteData())!;
expect(dataAfter.lengthInBytes, 20 * 25 * 4);
for (final int byte in dataAfter.buffer.asUint32List()) {
expect(byte, 0xFFAAAAAA);
}
// Verify that the image can be drawn successfully.
final PictureRecorder recorder2 = PictureRecorder();
final Canvas canvas2 = Canvas(recorder2);
canvas2.drawImage(image, Offset.zero, Paint());
final Picture picture2 = recorder2.endRecording();
picture.dispose();
picture2.dispose();
notifyNative();
}
@pragma('vm:entry-point')
Future<void> included() async {
}
Future<void> excluded() async {
}
class IsolateParam {
const IsolateParam(this.sendPort, this.rawHandle);
final SendPort sendPort;
final int rawHandle;
}
@pragma('vm:entry-point')
Future<void> runCallback(IsolateParam param) async {
try {
final Future<dynamic> Function() func = PluginUtilities.getCallbackFromHandle(
CallbackHandle.fromRawHandle(param.rawHandle)
)! as Future<dynamic> Function();
await func.call();
param.sendPort.send(true);
}
on NoSuchMethodError {
param.sendPort.send(false);
}
}
@pragma('vm:entry-point')
@pragma('vm:external-name', 'NotifyNativeBool')
external void notifyNativeBool(bool value);
@pragma('vm:external-name', 'NotifyDestroyed')
external void notifyDestroyed();
@pragma('vm:entry-point')
Future<void> testPluginUtilitiesCallbackHandle() async {
ReceivePort port = ReceivePort();
await Isolate.spawn(
runCallback,
IsolateParam(
port.sendPort,
PluginUtilities.getCallbackHandle(included)!.toRawHandle()
),
onError: port.sendPort
);
final dynamic result1 = await port.first;
if (result1 != true) {
print('Expected $result1 to == true');
notifyNativeBool(false);
return;
}
port.close();
if (const bool.fromEnvironment('dart.vm.product')) {
port = ReceivePort();
await Isolate.spawn(
runCallback,
IsolateParam(
port.sendPort,
PluginUtilities.getCallbackHandle(excluded)!.toRawHandle()
),
onError: port.sendPort
);
final dynamic result2 = await port.first;
if (result2 != false) {
print('Expected $result2 to == false');
notifyNativeBool(false);
return;
}
port.close();
}
notifyNativeBool(true);
}
@pragma('vm:entry-point')
Future<void> testThatAssetLoadingHappensOnWorkerThread() async {
try {
await ImmutableBuffer.fromAsset('DoesNotExist');
} catch (err) { /* Do nothing */ }
notifyNative();
}
@pragma('vm:external-name', 'NativeReportViewIdsCallback')
external void nativeReportViewIdsCallback(bool hasImplicitView, List<int> viewIds);
List<int> getCurrentViewIds() {
final List<int> result = PlatformDispatcher.instance.views
.map((FlutterView view) => view.viewId)
.toList()
..sort();
assert(result.toSet().length == result.length,
'Unexpected duplicate view ID found: $result');
return result;
}
bool listEquals<T>(List<T> a, List<T> b) {
if (a.length != b.length) {
return false;
}
for (int i = 0; i < a.length; i += 1) {
if (a[i] != b[i]) {
return false;
}
}
return true;
}
// This entrypoint reports whether there's an implicit view and the list of view
// IDs using nativeReportViewIdsCallback on initialization and every time the
// list of view IDs changes.
@pragma('vm:entry-point')
void testReportViewIds() {
List<int> viewIds = getCurrentViewIds();
nativeReportViewIdsCallback(PlatformDispatcher.instance.implicitView != null, viewIds);
PlatformDispatcher.instance.onMetricsChanged = () {
final List<int> newViewIds = getCurrentViewIds();
if (!listEquals(viewIds, newViewIds)) {
viewIds = newViewIds;
nativeReportViewIdsCallback(PlatformDispatcher.instance.implicitView != null, viewIds);
}
};
}
// Returns a list of [view_id 1, view_width 1, view_id 2, view_width 2, ...]
// for all views.
List<int> getCurrentViewWidths() {
final List<int> result = <int>[];
for (final FlutterView view in PlatformDispatcher.instance.views) {
result.add(view.viewId);
result.add(view.physicalSize.width.round());
}
return result;
}
@pragma('vm:external-name', 'NativeReportViewWidthsCallback')
external void nativeReportViewWidthsCallback(List<int> viewWidthPacket);
// This entrypoint reports the list of views and their widths using
// nativeReportViewWidthsCallback on initialization and every onMetricsChanged.
@pragma('vm:entry-point')
void testReportViewWidths() {
nativeReportViewWidthsCallback(getCurrentViewWidths());
PlatformDispatcher.instance.onMetricsChanged = () {
nativeReportViewWidthsCallback(getCurrentViewWidths());
};
}
@pragma('vm:entry-point')
void renderWarmUpImplicitView() {
bool beginFrameDone = false;
PlatformDispatcher.instance.scheduleWarmUpFrame(
beginFrame: () {
expect(beginFrameDone, false);
beginFrameDone = true;
},
drawFrame: () {
expect(beginFrameDone, true);
final SceneBuilder builder = SceneBuilder();
final PictureRecorder recorder = PictureRecorder();
final Canvas canvas = Canvas(recorder);
canvas.drawPaint(Paint()..color = const Color(0xFFABCDEF));
final Picture picture = recorder.endRecording();
builder.addPicture(Offset.zero, picture);
final Scene scene = builder.build();
PlatformDispatcher.instance.implicitView!.render(scene);
scene.dispose();
picture.dispose();
},
);
}