text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
// 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 'dart:convert';
import 'dart:io';
import 'package:collection/collection.dart';
import 'package:devtools_app/src/screens/debugger/span_parser.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:path/path.dart' as path;
const missingEnd = '''
/** there's no end to this comment
''';
const openCodeBlock = '''
/// This is an open code block:
/// ```dart
///
/// This should not cause parsing to fail.
void main() {
// But scope should end when parent scope is closed.
}
''';
void main() {
final grammarFile = File(path.join('assets', 'dart_syntax.json')).absolute;
late Grammar grammar;
final Directory testDataDirectory = Directory(
path.join('test', 'test_infra', 'test_data', 'syntax_highlighting'),
).absolute;
final Directory goldenDirectory = Directory(
path.join('test', 'test_infra', 'goldens', 'syntax_highlighting'),
).absolute;
setUpAll(() async {
expect(grammarFile.existsSync(), true);
final grammarJson = json.decode(await grammarFile.readAsString());
grammar = Grammar.fromJson(grammarJson);
});
group('SpanParser', () {
final updateGoldens = autoUpdateGoldenFiles;
/// Expects parsing [content] using produces the output in [goldenFile].
void expectSpansMatchGolden(
String content,
File goldenFile,
) {
if (updateGoldens) {
final spans = SpanParser.parse(grammar, content);
final actual = _buildGoldenText(content, spans);
goldenFile.writeAsStringSync(actual);
return;
}
if (!goldenFile.existsSync()) {
fail('Missing golden file: ${goldenFile.path}');
}
// Test input content with both line ending kinds.
for (final eol in ['\n', '\r\n']) {
/// Normalizes newlines to the set we're comparing.
String normalize(String code) =>
code.replaceAll('\r', '').replaceAll('\n', eol);
content = normalize(content);
final spans = SpanParser.parse(grammar, content);
final actual = _buildGoldenText(content, spans);
final expected = normalize(goldenFile.readAsStringSync());
expect(
actual,
expected,
reason: 'Content should match when using eol=${jsonEncode(eol)}',
);
}
}
File goldenFileFor(String name) {
final goldenPath = path.join(goldenDirectory.path, '$name.golden');
return File(goldenPath);
}
// Multiline rules allow for matching spans that do not close with a match to
// the 'end' pattern in the case that EOF has been reached.
test('handles EOF gracefully', () {
final goldenFile = goldenFileFor('handles_eof_gracefully');
expectSpansMatchGolden(missingEnd, goldenFile);
// Check the span ends where expected.
final span = SpanParser.parse(grammar, missingEnd).single;
expect(span.scopes, ['comment.block.documentation.dart']);
expect(span.line, 1);
expect(span.column, 1);
expect(span.length, 35);
});
test('handles malformed input', () {
final goldenFile = goldenFileFor('open_code_block');
expectSpansMatchGolden(openCodeBlock, goldenFile);
});
group('golden', () {
// Perform golden tests on the test_data/syntax_highlighting folder.
// These goldens are updated using the usual Flutter --update-goldens
// flag:
//
// flutter test test/shared/span_parser_test.dart --update-goldens
final testFiles = testDataDirectory
.listSync()
.whereType<File>()
.where((file) => path.extension(file.path) == '.dart');
for (final testFile in testFiles) {
final goldenFile = goldenFileFor(path.basename(testFile.path));
test(path.basename(testFile.path), () {
final content = testFile.readAsStringSync();
expectSpansMatchGolden(content, goldenFile);
});
}
});
});
}
String _buildGoldenText(String content, List<ScopeSpan> spans) {
final buffer = StringBuffer();
final spansByLine = groupBy(spans, (ScopeSpan s) => s.line - 1);
final lines = content.split('\n');
for (var i = 0; i < lines.length; i++) {
// We only output characters for the line, excluding any newlines on the
// end.
final line = lines[i].trimRight();
// Track what the eol was (restore the newline, subtract any untrimmed
// part). This may end up as `\r\n` or `\n` depending on whether Windows
// and the git autocrlf setting.
final eol = '${lines[i]}\n'.substring(line.length);
final lineLengthWithNewline = line.length + eol.length;
// If this is the last line and it's blank, skip it.
if (i == lines.length - 1 && line.isEmpty) {
break;
}
buffer.write('>$line$eol');
final lineSpans = spansByLine[i];
if (lineSpans != null) {
for (final span in lineSpans) {
final col = span.column - 1;
var length = span.length;
// Spans may roll over onto the next line, so truncate them and insert
// the remainder into the next.
if (col + length > lineLengthWithNewline) {
final thisLineLength = line.length - col;
final offsetToStartOfNextLine = lineLengthWithNewline - col;
length = thisLineLength;
spansByLine[i + 1] ??= [];
// Insert the wrapped span before other spans on the next line so the
// order is preserved.
spansByLine[i + 1]!.insert(
0,
ScopeSpan(
scopes: span.scopes,
startLocation: ScopeStackLocation(
position: span.start + offsetToStartOfNextLine,
line: span.line + 1,
column: 0,
),
endLocation: span.endLocation,
),
);
} else if (col + length > line.length) {
// Truncate any spans that include the trailing newline.
length = line.length - col;
}
// If this span just covers the trailing newline, skip it
// as it doesn't produce any useful output.
if (col >= line.length) {
continue;
}
buffer.write('#');
buffer.write(' ' * col);
buffer.write('^' * length);
buffer.write(' ');
buffer.write(span.scopes.join(' '));
buffer.write(eol);
}
}
}
return buffer.toString();
}
| devtools/packages/devtools_app/test/shared/span_parser_test.dart/0 | {
"file_path": "devtools/packages/devtools_app/test/shared/span_parser_test.dart",
"repo_id": "devtools",
"token_count": 2584
} | 125 |
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: avoid_print
import 'dart:async';
import 'dart:developer' as developer;
import 'package:ansicolor/ansicolor.dart';
void main() {
// Start paused to avoid race conditions getting the initial output from the
// console.
developer.debugger();
print('starting ansi color app');
// Print out text exercising a wide range of ansi color styles.
final sb = StringBuffer();
final pen = AnsiPen();
// Test the 16 color defaults.
for (int c = 0; c < 16; c++) {
pen
..reset()
..white(bold: true)
..xterm(c, bg: true);
sb.write(pen('$c '));
pen
..reset()
..xterm(c);
sb.write(pen(' $c '));
if (c == 7 || c == 15) {
sb.writeln();
}
}
// Test a few custom colors.
for (int r = 0; r < 6; r += 3) {
sb.writeln();
for (int g = 0; g < 6; g += 3) {
for (int b = 0; b < 6; b += 3) {
final c = r * 36 + g * 6 + b + 16;
pen
..reset()
..rgb(r: r / 5, g: g / 5, b: b / 5, bg: true)
..white(bold: true);
sb.write(pen(' $c '));
pen
..reset()
..rgb(r: r / 5, g: g / 5, b: b / 5);
sb.write(pen(' $c '));
}
sb.writeln();
}
}
for (int c = 0; c < 24; c++) {
if (0 == c % 8) {
sb.writeln();
}
pen
..reset()
..gray(level: c / 23, bg: true)
..white(bold: true);
sb.write(pen(' ${c + 232} '));
pen
..reset()
..gray(level: c / 23);
sb.write(pen(' ${c + 232} '));
}
print(sb.toString());
// Keep the app running indefinitely printing additional messages.
int i = 0;
Timer.periodic(const Duration(milliseconds: 1000), (timer) {
print('Message ${i++}');
});
}
| devtools/packages/devtools_app/test/test_infra/fixtures/color_console_output_app.dart/0 | {
"file_path": "devtools/packages/devtools_app/test/test_infra/fixtures/color_console_output_app.dart",
"repo_id": "devtools",
"token_count": 853
} | 126 |
# flutter_error_app
App for running DevTools integration tests.
## Getting Started
This project is a starting point for a Flutter application.
A few resources to get you started if this is your first Flutter project:
- [Lab: Write your first Flutter app](https://flutter.io/docs/get-started/codelab)
- [Cookbook: Useful Flutter samples](https://flutter.io/docs/cookbook)
For help getting started with Flutter, view our
[online documentation](https://flutter.io/docs), which offers tutorials,
samples, guidance on mobile development, and a full API reference.
| devtools/packages/devtools_app/test/test_infra/fixtures/flutter_error_app/README.md/0 | {
"file_path": "devtools/packages/devtools_app/test/test_infra/fixtures/flutter_error_app/README.md",
"repo_id": "devtools",
"token_count": 155
} | 127 |
// Copyright 2022 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.
const a = 'aaaaa';
const list1 = [];
const list2 = <String>[];
const list3 = ['', '$a'];
const list4 = <String>['', '$a'];
const set1 = {};
const set2 = <String>{};
const set3 = {'', '$a'};
const set4 = <String>{'', '$a'};
const map1 = <String, String>{};
const map2 = {'': '$a'};
const map3 = <String, String>{'': '$a'};
| devtools/packages/devtools_app/test/test_infra/test_data/syntax_highlighting/literals.dart/0 | {
"file_path": "devtools/packages/devtools_app/test/test_infra/test_data/syntax_highlighting/literals.dart",
"repo_id": "devtools",
"token_count": 184
} | 128 |
// Copyright 2022 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:devtools_app/devtools_app.dart';
import 'package:devtools_app/src/screens/vm_developer/object_inspector/vm_class_display.dart';
import 'package:devtools_app/src/screens/vm_developer/vm_developer_common_widgets.dart';
import 'package:devtools_app_shared/ui.dart';
import 'package:devtools_app_shared/utils.dart';
import 'package:devtools_test/devtools_test.dart';
import 'package:devtools_test/helpers.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import 'package:vm_service/vm_service.dart';
import '../vm_developer_test_utils.dart';
void main() {
late MockClassObject mockClassObject;
const windowSize = Size(4000.0, 4000.0);
late Class testClassCopy;
setUp(() {
setUpMockScriptManager();
setGlobal(BreakpointManager, BreakpointManager());
setGlobal(IdeTheme, IdeTheme());
setGlobal(ServiceConnectionManager, FakeServiceConnectionManager());
setGlobal(
DevToolsEnvironmentParameters,
ExternalDevToolsEnvironmentParameters(),
);
setGlobal(PreferencesController, PreferencesController());
setGlobal(NotificationService, NotificationService());
mockClassObject = MockClassObject();
final json = testClass.toJson();
testClassCopy = Class.parse(json)!;
testClassCopy.size = 1024;
mockVmObject(mockClassObject);
when(mockClassObject.obj).thenReturn(testClassCopy);
});
testWidgetsWithWindowSize(
'builds class display',
windowSize,
(WidgetTester tester) async {
await tester.pumpWidget(
wrap(
VmClassDisplay(
clazz: mockClassObject,
controller: ObjectInspectorViewController(),
),
),
);
expect(find.byType(VmObjectDisplayBasicLayout), findsOneWidget);
expect(find.byType(VMInfoCard), findsOneWidget);
expect(find.text('General Information'), findsOneWidget);
expect(find.text('1.0 KB'), findsOneWidget);
expect(find.text('fooLib', findRichText: true), findsOneWidget);
expect(
find.text('fooScript.dart:10:4', findRichText: true),
findsOneWidget,
);
expect(find.text('fooSuperClass', findRichText: true), findsOneWidget);
expect(find.text('fooSuperType', findRichText: true), findsOneWidget);
expect(find.text('Currently allocated instances:'), findsOneWidget);
expect(find.text('3'), findsOneWidget);
expect(find.byType(RequestableSizeWidget), findsNWidgets(2));
expect(find.byType(RetainingPathWidget), findsOneWidget);
expect(find.byType(InboundReferencesTree), findsOneWidget);
// TODO(mtaylee): test ClassInstancesWidget when implemented
},
);
}
| devtools/packages/devtools_app/test/vm_developer/object_inspector/vm_class_display_test.dart/0 | {
"file_path": "devtools/packages/devtools_app/test/vm_developer/object_inspector/vm_class_display_test.dart",
"repo_id": "devtools",
"token_count": 1033
} | 129 |
@media (-webkit-max-device-pixel-ratio: 1) {
* {
image-rendering: pixelated;
}
}
| devtools/packages/devtools_app/web/styles.css/0 | {
"file_path": "devtools/packages/devtools_app/web/styles.css",
"repo_id": "devtools",
"token_count": 39
} | 130 |
// 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.
// This code is directly based on src/io/flutter/inspector/EvalOnDartLibrary.java
// If you add a method to this class you should also add it to EvalOnDartLibrary.java
import 'dart:async';
import 'dart:core' hide Error;
import 'dart:core' as core;
import 'dart:math';
import 'package:flutter/foundation.dart';
import 'package:logging/logging.dart';
import 'package:meta/meta.dart';
import 'package:vm_service/vm_service.dart' hide Error;
import 'package:vm_service/vm_service.dart' as vm_service;
import '../utils/auto_dispose.dart';
import 'service_manager.dart';
final _log = Logger('eval_on_dart_library');
class Disposable {
bool disposed = false;
@mustCallSuper
void dispose() {
disposed = true;
}
}
// TODO(https://github.com/flutter/devtools/issues/6239): try to remove this.
@sealed
class EvalOnDartLibrary extends DisposableController
with AutoDisposeControllerMixin {
EvalOnDartLibrary(
this.libraryName,
this.service, {
required this.serviceManager,
ValueListenable<IsolateRef?>? isolate,
this.disableBreakpoints = true,
this.oneRequestAtATime = false,
}) : _clientId = Random().nextInt(1000000000) {
_libraryRef = Completer<LibraryRef>();
// For evals in tests, we will pass the isolateId into the constructor.
isolate ??= serviceManager.isolateManager.selectedIsolate;
addAutoDisposeListener(isolate, () => _init(isolate!.value));
_init(isolate.value);
}
/// Whether to wait for one request to complete before issuing another
/// request.
///
/// This makes it possible to cancel requests and provides clear ordering
/// guarantees but significantly hurts performance particularly when the
/// VM Service and DevTools are not running on the same machine.
final bool oneRequestAtATime;
/// Whether to disable breakpoints triggered while evaluating expressions.
final bool disableBreakpoints;
/// An ID unique to this instance, so that [asyncEval] keeps working even if
/// the devtool is opened on multiple tabs at the same time.
final int _clientId;
/// The service manager to use for this instance of [EvalOnDartLibrary].
final ServiceManager serviceManager;
void _init(IsolateRef? isolateRef) {
if (_isolateRef == isolateRef) return;
_currentRequestId++;
_isolateRef = isolateRef;
if (_libraryRef.isCompleted) {
_libraryRef = Completer();
}
if (isolateRef != null) {
unawaited(_initialize(isolateRef, _currentRequestId));
}
}
bool get disposed => _disposed;
bool _disposed = false;
@override
void dispose() {
_dartDeveloperEvalCache?.dispose();
_widgetInspectorEvalCache?.dispose();
_disposed = true;
super.dispose();
}
final String libraryName;
final VmService service;
IsolateRef? get isolateRef => _isolateRef;
IsolateRef? _isolateRef;
int _currentRequestId = 0;
late Completer<LibraryRef> _libraryRef;
Completer<void>? allPendingRequestsDone;
Isolate? get isolate => _isolate;
Isolate? _isolate;
Future<void> _initialize(IsolateRef isolateRef, int requestId) async {
if (_currentRequestId != requestId) {
// The initialize request is obsolete.
return;
}
try {
final Isolate? isolate =
await serviceManager.isolateManager.isolateState(isolateRef).isolate;
if (_currentRequestId != requestId) {
// The initialize request is obsolete.
return;
}
_isolate = isolate;
for (LibraryRef library in isolate?.libraries ?? []) {
if (libraryName == library.uri) {
assert(!_libraryRef.isCompleted);
_libraryRef.complete(library);
return;
}
}
assert(!_libraryRef.isCompleted);
_libraryRef.completeError(LibraryNotFound(libraryName));
} catch (e, stack) {
_handleError(e, stack);
}
}
Future<InstanceRef?> eval(
String expression, {
required Disposable? isAlive,
Map<String, String>? scope,
bool shouldLogError = true,
}) async {
if ((scope?.isNotEmpty ?? false) &&
serviceManager.connectedApp!.isDartWebAppNow!) {
final result = await eval(
'(${scope!.keys.join(',')}) => $expression',
isAlive: isAlive,
shouldLogError: shouldLogError,
);
if (result == null || (isAlive?.disposed ?? true)) return null;
return await invoke(
result,
'call',
scope.values.toList(),
isAlive: isAlive,
shouldLogError: shouldLogError,
);
}
return await addRequest<InstanceRef?>(
isAlive,
() => _eval(
expression,
scope: scope,
shouldLogError: shouldLogError,
),
);
}
Future<InstanceRef?> invoke(
InstanceRef instanceRef,
String name,
List<String> argRefs, {
required Disposable? isAlive,
bool shouldLogError = true,
}) {
return addRequest(
isAlive,
() => _invoke(
instanceRef,
name,
argRefs,
shouldLogError: shouldLogError,
).then((value) => value!),
);
}
Future<LibraryRef> _waitForLibraryRef() async {
while (true) {
final id = _currentRequestId;
final libraryRef = await _libraryRef.future;
if (_libraryRef.isCompleted && _currentRequestId == id) {
// Avoid race condition where a new isolate loaded
// while we were waiting for the library ref.
// TODO(jacobr): checking the isolateRef matches the isolateRef when the method started.
return libraryRef;
}
}
}
Future<InstanceRef?> _eval(
String expression, {
required Map<String, String>? scope,
bool shouldLogError = true,
}) async {
if (_disposed) return null;
try {
final libraryRef = await _waitForLibraryRef();
final result = await service.evaluate(
_isolateRef!.id!,
libraryRef.id!,
expression,
scope: scope,
disableBreakpoints: disableBreakpoints,
);
if (result is Sentinel) {
return null;
}
if (result is ErrorRef) {
throw result;
}
return result as FutureOr<InstanceRef?>;
} catch (e, stack) {
if (shouldLogError) {
_handleError('$e - $expression', stack);
}
}
return null;
}
Future<InstanceRef?> _invoke(
InstanceRef instanceRef,
String name,
List<String> argRefs, {
bool shouldLogError = true,
}) async {
if (_disposed) return null;
try {
final result = await service.invoke(
_isolateRef!.id!,
instanceRef.id!,
name,
argRefs,
disableBreakpoints: disableBreakpoints,
);
if (result is Sentinel) {
return null;
}
if (result is ErrorRef) {
throw result;
}
return result as FutureOr<InstanceRef?>;
} catch (e, stack) {
if (shouldLogError) {
_handleError('$e - $name', stack);
}
}
return null;
}
void _handleError(Object e, StackTrace stack) {
if (_disposed) return;
if (e is RPCError) {
_log.shout('RPCError: $e', e, stack);
} else if (e is vm_service.Error) {
_log.shout('${e.kind}: ${e.message}', e, stack);
} else {
_log.shout('Unrecognized error: $e', e, stack);
}
_log.shout(stack.toString(), e, stack);
}
T _verifySaneValue<T>(T? value, Disposable? isAlive) {
/// Throwing when the request is cancelled instead of returning `null`
/// allows easily chaining eval calls, without having to check "disposed"
/// between each request.
/// It also removes the need for using `!` once the devtool is migrated to NNBD
if (isAlive?.disposed ?? true) {
// throw before _handleError as we don't want to log cancellations.
throw CancelledException();
}
if (value == null) {
throw StateError('Expected an instance of $T but received null');
}
return value;
}
Future<Class?> getClass(ClassRef instance, Disposable isAlive) {
return getObjHelper(instance, isAlive);
}
Future<Class> safeGetClass(ClassRef instance, Disposable isAlive) async {
final value = await getObjHelper<Class>(instance, isAlive);
return _verifySaneValue(value, isAlive);
}
Future<Func?> getFunc(FuncRef instance, Disposable isAlive) {
return getObjHelper(instance, isAlive);
}
Future<Instance?> getInstance(
FutureOr<InstanceRef> instanceRefFuture,
Disposable? isAlive,
) async {
return await getObjHelper(await instanceRefFuture, isAlive);
}
Future<Instance> safeGetInstance(
FutureOr<InstanceRef> instanceRefFuture,
Disposable? isAlive,
) async {
final instanceRef = await instanceRefFuture;
final value = await getObjHelper<Instance>(instanceRef, isAlive);
return _verifySaneValue(value, isAlive);
}
Future<int> getHashCode(
InstanceRef instance, {
required Disposable? isAlive,
}) async {
// identityHashCode will be -1 if the Flutter SDK is not recent enough
if (instance.identityHashCode != -1 && instance.identityHashCode != null) {
return instance.identityHashCode!;
}
final hash = await evalInstance(
'instance.hashCode',
isAlive: isAlive,
scope: {'instance': instance.id!},
);
return int.parse(hash.valueAsString!);
}
/// Eval an expression and immediately obtain its [Instance].
Future<Instance> evalInstance(
String expression, {
required Disposable? isAlive,
Map<String, String>? scope,
}) {
return safeGetInstance(
// This is safe to do because `safeEval` will throw instead of returning `null`
// when the request is cancelled, so `getInstance` will not receive `null`
// as parameter.
safeEval(expression, isAlive: isAlive, scope: scope),
isAlive,
);
}
static int _nextAsyncEvalId = 0;
EvalOnDartLibrary? _dartDeveloperEvalCache;
EvalOnDartLibrary get _dartDeveloperEval {
return _dartDeveloperEvalCache ??= EvalOnDartLibrary(
'dart:developer',
service,
serviceManager: serviceManager,
);
}
EvalOnDartLibrary? _widgetInspectorEvalCache;
EvalOnDartLibrary get _widgetInspectorEval {
return _widgetInspectorEvalCache ??= EvalOnDartLibrary(
'package:flutter/src/widgets/widget_inspector.dart',
service,
serviceManager: serviceManager,
);
}
/// A [safeEval] variant that can use `await`.
///
/// This is useful to obtain the value emitted by a future, by potentially doing:
///
/// ```dart
/// final result = await asyncEval('await Future.value(42)');
/// ```
///
/// where `result` will be an [InstanceRef] that points to `42`.
///
/// If the [FutureOr] awaited threw, [asyncEval] will throw a [FutureFailedException],
/// which can be caught to access the [StackTrace] and error.
Future<InstanceRef?> asyncEval(
String expression, {
required Disposable? isAlive,
Map<String, String>? scope,
}) async {
final futureId = _nextAsyncEvalId++;
// start awaiting the event before starting the evaluation, in case the
// event is received before the eval function completes.
final future = serviceManager.service!.onExtensionEvent.firstWhere((event) {
return event.extensionKind == 'future_completed' &&
event.extensionData!.data['future_id'] == futureId &&
// Using `_clientId` here as if two chrome tabs open the devtool, it is
// possible to have conflicts on `future_id`
event.extensionData!.data['client_id'] == _clientId;
});
final readerGroup = 'asyncEval-$futureId';
/// Workaround to not being able to import libraries directly from an evaluation
final postEventRef = await _dartDeveloperEval.safeEval(
'postEvent',
isAlive: isAlive,
);
final widgetInspectorServiceRef = await _widgetInspectorEval.safeEval(
'WidgetInspectorService.instance',
isAlive: isAlive,
);
final readerId = await safeEval(
// since we are awaiting the Future, we need to make sure that during the awaiting,
// the "reader" is not GCed
'widgetInspectorService.toId(<dynamic>[], "$readerGroup")',
isAlive: isAlive,
scope: {'widgetInspectorService': widgetInspectorServiceRef.id!},
).then((ref) => ref.valueAsString!);
await safeEval(
'() async {'
' final reader = widgetInspectorService.toObject("$readerId", "$readerGroup") as List;'
' try {'
// Cast as dynamic so that it is possible to await Future<void>
' dynamic result = ($expression) as dynamic;'
' reader.add(result);'
' } catch (err, stack) {'
' reader.add(err);'
' reader.add(stack);'
' } finally {'
' postEvent("future_completed", {"future_id": $futureId, "client_id": $_clientId});'
' }'
'}()',
isAlive: isAlive,
scope: {
...?scope,
'postEvent': postEventRef.id!,
'widgetInspectorService': widgetInspectorServiceRef.id!,
},
);
await future;
final resultRef = await evalInstance(
'() {'
' final result = widgetInspectorService.toObject("$readerId", "$readerGroup") as List;'
' widgetInspectorService.disposeGroup("$readerGroup");'
' return result;'
'}()',
isAlive: isAlive,
scope: {'widgetInspectorService': widgetInspectorServiceRef.id!},
);
assert(resultRef.length == 1 || resultRef.length == 2);
if (resultRef.length == 2) {
throw FutureFailedException(
expression,
resultRef.elements![0],
resultRef.elements![1],
);
}
return resultRef.elements![0];
}
/// An [eval] that throws when a [Sentinel]/error occurs or if [isAlive] was
/// disposed while the request was pending.
///
/// If `isAlive` was disposed while the request was pending, will throw a [CancelledException].
Future<InstanceRef> safeEval(
String expression, {
required Disposable? isAlive,
Map<String, String>? scope,
}) async {
Object? result;
try {
if (disposed) {
throw StateError(
'Called `safeEval` on a disposed `EvalOnDartLibrary` instance',
);
}
result = await addRequest(isAlive, () async {
final libraryRef = await _waitForLibraryRef();
return await service.evaluate(
isolateRef!.id!,
libraryRef.id!,
expression,
scope: scope,
disableBreakpoints: disableBreakpoints,
);
});
if (result is! InstanceRef) {
if (result is ErrorRef) {
throw EvalErrorException(
expression: expression,
scope: scope,
errorRef: result,
);
}
if (result is Sentinel) {
throw EvalSentinelException(
expression: expression,
scope: scope,
sentinel: result,
);
}
throw UnknownEvalException(
expression: expression,
scope: scope,
exception: result,
);
}
} catch (err, stack) {
/// Throwing when the request is cancelled instead of returning `null`
/// allows easily chaining eval calls, without having to check "disposed"
/// between each request.
/// It also removes the need for using `!` once the devtool is migrated to NNBD
if (isAlive?.disposed ?? true) {
// throw before _handleError as we don't want to log cancellations.
core.Error.throwWithStackTrace(CancelledException(), stack);
}
_handleError(err, stack);
rethrow;
}
return result;
}
/// Public so that other related classes such as InspectorService can ensure
/// their requests are in a consistent order with existing requests.
///
/// When [oneRequestAtATime] is true, using this method
/// eliminates otherwise surprising timing bugs, such as if a request to
/// dispose an InspectorService.ObjectGroup was issued after a request to read
/// properties from an object in a group, but the request to dispose the
/// object group occurred first.
///
/// With this design, we have at most 1 pending request at a time. This
/// sacrifices some throughput, but we gain the advantage of predictable
/// semantics and the ability to skip large numbers of requests from object
/// groups that should no longer be kept alive.
///
/// The optional ObjectGroup specified by [isAlive] indicates whether the
/// request is still relevant or should be cancelled. This is an optimization
/// for the Inspector so that it does not overload the service with stale requests.
/// Stale requests will be generated if the user is quickly navigating through the
/// UI to view specific details subtrees.
Future<T?> addRequest<T>(
Disposable? isAlive,
Future<T?> Function() request,
) async {
if (isAlive != null && isAlive.disposed) return null;
if (!oneRequestAtATime) {
return request();
}
// Future that completes when the request has finished.
final Completer<T?> response = Completer();
// This is an optimization to avoid sending stale requests across the wire.
void wrappedRequest() async {
if (isAlive != null && isAlive.disposed || _disposed) {
response.complete(null);
return;
}
try {
final value = await request();
if (!_disposed && value is! Sentinel) {
response.complete(value);
} else {
response.complete(null);
}
} catch (e) {
if (_disposed || isAlive?.disposed == true) {
response.complete(null);
} else {
response.completeError(e);
}
}
}
if (allPendingRequestsDone == null || allPendingRequestsDone!.isCompleted) {
allPendingRequestsDone = response;
wrappedRequest();
} else {
if (isAlive != null && isAlive.disposed || _disposed) {
response.complete(null);
return response.future;
}
final Future<void> previousDone = allPendingRequestsDone!.future;
allPendingRequestsDone = response;
// Schedule this request only after the previous request completes.
try {
await previousDone;
} catch (e, st) {
if (!_disposed) {
_log.shout(e, e, st);
}
}
wrappedRequest();
}
return response.future;
}
Future<T?> getObjHelper<T extends Obj>(
ObjRef instance,
Disposable? isAlive, {
int? offset,
int? count,
}) {
return addRequest<T>(isAlive, () async {
final T value = await service.getObject(
_isolateRef!.id!,
instance.id!,
offset: offset,
count: count,
) as T;
return value;
});
}
}
final class LibraryNotFound implements Exception {
LibraryNotFound(this.name);
final String name;
String get message => 'Library matching $name not found';
@override
String toString() => message;
}
final class FutureFailedException implements Exception {
FutureFailedException(this.expression, this.errorRef, this.stacktraceRef);
final String expression;
final InstanceRef errorRef;
final InstanceRef stacktraceRef;
@override
String toString() {
return 'The future from the expression `$expression` failed.';
}
}
final class CancelledException implements Exception {}
final class UnknownEvalException implements Exception {
UnknownEvalException({
required this.expression,
required this.scope,
required this.exception,
});
final String expression;
final Object? exception;
final Map<String, String?>? scope;
@override
String toString() {
return 'Unknown error during the evaluation of `$expression`: $exception for scope: $scope';
}
}
final class SentinelException implements Exception {
SentinelException(this.sentinel);
final Sentinel sentinel;
@override
String toString() {
return 'SentinelException(sentinel: $sentinel)';
}
}
final class EvalSentinelException extends SentinelException {
EvalSentinelException({
required this.expression,
required this.scope,
required Sentinel sentinel,
}) : super(sentinel);
final String expression;
final Map<String, String?>? scope;
@override
String toString() {
return 'Evaluation `$expression` returned the Sentinel $sentinel for scope: $scope';
}
}
final class EvalErrorException implements Exception {
EvalErrorException({
required this.expression,
required this.scope,
required this.errorRef,
});
final ErrorRef errorRef;
final String expression;
final Map<String, String?>? scope;
@override
String toString() {
return 'Evaluation `$expression` failed with $errorRef for scope: $scope';
}
}
| devtools/packages/devtools_app_shared/lib/src/service/eval_on_dart_library.dart/0 | {
"file_path": "devtools/packages/devtools_app_shared/lib/src/service/eval_on_dart_library.dart",
"repo_id": "devtools",
"token_count": 7725
} | 131 |
// 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 '../ui_utils.dart';
import 'ide_theme.dart';
// TODO(kenz): try to eliminate as many custom colors as possible, and pull
// colors only from the [lightColorScheme] and the [darkColorScheme].
/// Whether dark theme should be used as the default theme if none has been
/// explicitly set.
const useDarkThemeAsDefault = true;
/// Constructs the light or dark theme for the app taking into account
/// IDE-supplied theming.
ThemeData themeFor({
required bool isDarkTheme,
required IdeTheme ideTheme,
required ThemeData theme,
}) {
final colorTheme = isDarkTheme
? _darkTheme(ideTheme: ideTheme, theme: theme)
: _lightTheme(ideTheme: ideTheme, theme: theme);
return colorTheme.copyWith(
primaryTextTheme: theme.primaryTextTheme
.merge(colorTheme.primaryTextTheme)
.apply(fontSizeFactor: ideTheme.fontSizeFactor),
textTheme: theme.textTheme
.merge(colorTheme.textTheme)
.apply(fontSizeFactor: ideTheme.fontSizeFactor),
);
}
ThemeData _darkTheme({
required IdeTheme ideTheme,
required ThemeData theme,
}) {
final background = isValidDarkColor(ideTheme.backgroundColor)
? ideTheme.backgroundColor!
: theme.colorScheme.surface;
return _baseTheme(
theme: theme,
backgroundColor: background,
);
}
ThemeData _lightTheme({
required IdeTheme ideTheme,
required ThemeData theme,
}) {
final background = isValidLightColor(ideTheme.backgroundColor)
? ideTheme.backgroundColor!
: theme.colorScheme.surface;
return _baseTheme(
theme: theme,
backgroundColor: background,
);
}
ThemeData _baseTheme({
required ThemeData theme,
required Color backgroundColor,
}) {
// TODO(kenz): do we need to pass in the foreground color from the [IdeTheme]
// as well as the background color?
return theme.copyWith(
tabBarTheme: theme.tabBarTheme.copyWith(
tabAlignment: TabAlignment.start,
dividerColor: Colors.transparent,
labelPadding:
const EdgeInsets.symmetric(horizontal: defaultTabBarPadding),
),
canvasColor: backgroundColor,
scaffoldBackgroundColor: backgroundColor,
iconButtonTheme: IconButtonThemeData(
style: IconButton.styleFrom(
padding: const EdgeInsets.all(densePadding),
minimumSize: Size(defaultButtonHeight, defaultButtonHeight),
fixedSize: Size(defaultButtonHeight, defaultButtonHeight),
),
),
outlinedButtonTheme: OutlinedButtonThemeData(
style: OutlinedButton.styleFrom(
minimumSize: Size(buttonMinWidth, defaultButtonHeight),
fixedSize: Size.fromHeight(defaultButtonHeight),
foregroundColor: theme.colorScheme.onSurface,
padding: const EdgeInsets.symmetric(horizontal: denseSpacing),
),
),
textButtonTheme: TextButtonThemeData(
style: TextButton.styleFrom(
padding: const EdgeInsets.all(densePadding),
minimumSize: Size(buttonMinWidth, defaultButtonHeight),
fixedSize: Size.fromHeight(defaultButtonHeight),
),
),
elevatedButtonTheme: ElevatedButtonThemeData(
style: ElevatedButton.styleFrom(
minimumSize: Size(buttonMinWidth, defaultButtonHeight),
fixedSize: Size.fromHeight(defaultButtonHeight),
backgroundColor: theme.colorScheme.primary,
foregroundColor: theme.colorScheme.onPrimary,
padding: const EdgeInsets.symmetric(horizontal: denseSpacing),
),
),
menuButtonTheme: MenuButtonThemeData(
style: ButtonStyle(
textStyle: MaterialStatePropertyAll<TextStyle>(theme.regularTextStyle),
fixedSize: const MaterialStatePropertyAll<Size>(Size.fromHeight(24.0)),
),
),
dropdownMenuTheme: DropdownMenuThemeData(
textStyle: theme.regularTextStyle,
),
progressIndicatorTheme: ProgressIndicatorThemeData(
linearMinHeight: defaultLinearProgressIndicatorHeight,
),
textTheme: theme.textTheme.copyWith(
bodySmall: theme.regularTextStyle,
bodyMedium: theme.regularTextStyle,
titleSmall: theme.regularTextStyle.copyWith(fontWeight: FontWeight.w400),
),
);
}
/// Light theme color scheme generated from DevTools Figma file.
///
/// Do not manually change these values.
const lightColorScheme = ColorScheme(
brightness: Brightness.light,
primary: Color(0xFF195BB9),
onPrimary: Color(0xFFFFFFFF),
primaryContainer: Color(0xFFD8E2FF),
onPrimaryContainer: Color(0xFF001A41),
secondary: Color(0xFF575E71),
onSecondary: Color(0xFFFFFFFF),
secondaryContainer: Color(0xFFDBE2F9),
onSecondaryContainer: Color(0xFF141B2C),
tertiary: Color(0xFF815600),
onTertiary: Color(0xFFFFFFFF),
tertiaryContainer: Color(0xFFFFDDB1),
onTertiaryContainer: Color(0xFF291800),
error: Color(0xFFBA1A1A),
errorContainer: Color(0xFFFFDAD5),
onError: Color(0xFFFFFFFF),
onErrorContainer: Color(0xFF410002),
surface: Color(0xFFFFFFFF),
onSurface: Color(0xFF1B1B1F),
surfaceContainerHighest: Color(0xFFE1E2EC),
onSurfaceVariant: Color(0xFF44474F),
outline: Color(0xFF75777F),
onInverseSurface: Color(0xFFF2F0F4),
inverseSurface: Color(0xFF303033),
inversePrimary: Color(0xFFADC6FF),
shadow: Color(0xFF000000),
surfaceTint: Color(0xFF195BB9),
outlineVariant: Color(0xFFC4C6D0),
scrim: Color(0xFF000000),
);
/// Dark theme color scheme generated from DevTools Figma file.
///
/// Do not manually change these values.
const darkColorScheme = ColorScheme(
brightness: Brightness.dark,
primary: Color(0xFFADC6FF),
onPrimary: Color(0xFF002E69),
primaryContainer: Color(0xFF004494),
onPrimaryContainer: Color(0xFFD8E2FF),
secondary: Color(0xFFBFC6DC),
onSecondary: Color(0xFF293041),
secondaryContainer: Color(0xFF3F4759),
onSecondaryContainer: Color(0xFFDBE2F9),
tertiary: Color(0xFFFEBA4B),
onTertiary: Color(0xFF442B00),
tertiaryContainer: Color(0xFF624000),
onTertiaryContainer: Color(0xFFFFDDB1),
error: Color(0xFFFFB4AB),
errorContainer: Color(0xFF930009),
onError: Color(0xFF690004),
onErrorContainer: Color(0xFFFFDAD5),
surface: Color(0xFF1B1B1F),
onSurface: Color(0xFFC7C6CA),
surfaceContainerHighest: Color(0xFF44474F),
onSurfaceVariant: Color(0xFFC4C6D0),
outline: Color(0xFF8E9099),
onInverseSurface: Color(0xFF1B1B1F),
inverseSurface: Color(0xFFE3E2E6),
inversePrimary: Color(0xFF195BB9),
shadow: Color(0xFF000000),
surfaceTint: Color(0xFFADC6FF),
outlineVariant: Color(0xFF44474F),
scrim: Color(0xFF000000),
);
const searchMatchColor = Colors.yellow;
final searchMatchColorOpaque = Colors.yellow.withOpacity(0.5);
const activeSearchMatchColor = Colors.orangeAccent;
final activeSearchMatchColorOpaque = Colors.orangeAccent.withOpacity(0.5);
/// Gets an alternating color to use for indexed UI elements.
Color alternatingColorForIndex(int index, ColorScheme colorScheme) {
return index % 2 == 1
? colorScheme.alternatingBackgroundColor1
: colorScheme.alternatingBackgroundColor2;
}
/// Threshold used to determine whether a colour is light/dark enough for us to
/// override the default DevTools themes with.
///
/// A value of 0.5 would result in all colours being considered light/dark, and
/// a value of 0.12 allowing around only the 12% darkest/lightest colours by
/// Flutter's luminance calculation.
/// 12% was chosen because VS Code's default light background color is #f3f3f3
/// which is a little under 11%.
const _lightDarkLuminanceThreshold = 0.12;
bool isValidDarkColor(Color? color) {
if (color == null) {
return false;
}
return color.computeLuminance() <= _lightDarkLuminanceThreshold;
}
bool isValidLightColor(Color? color) {
if (color == null) {
return false;
}
return color.computeLuminance() >= 1 - _lightDarkLuminanceThreshold;
}
// Size constants:
double get defaultToolbarHeight => scaleByFontFactor(32.0);
double get defaultHeaderHeight => scaleByFontFactor(28.0);
double get defaultButtonHeight => scaleByFontFactor(26.0);
double get defaultRowHeight => scaleByFontFactor(24.0);
double get defaultLinearProgressIndicatorHeight => scaleByFontFactor(4.0);
double get buttonMinWidth => scaleByFontFactor(26.0);
const defaultIconSizeBeforeScaling = 14.0;
const defaultActionsIconSizeBeforeScaling = 18.0;
double get defaultIconSize => scaleByFontFactor(defaultIconSizeBeforeScaling);
double get actionsIconSize =>
scaleByFontFactor(defaultActionsIconSizeBeforeScaling);
double get tooltipIconSize => scaleByFontFactor(12.0);
double get tableIconSize => scaleByFontFactor(12.0);
double get defaultListItemHeight => scaleByFontFactor(24.0);
double get defaultDialogWidth => scaleByFontFactor(700.0);
const extraWideSearchFieldWidth = 600.0;
const wideSearchFieldWidth = 400.0;
const defaultSearchFieldWidth = 200.0;
double get defaultTextFieldHeight => scaleByFontFactor(26.0);
double get defaultTextFieldNumberWidth => scaleByFontFactor(100.0);
// TODO(jacobr) define a more sophisticated formula for chart height.
// The chart height does need to increase somewhat to leave room for the legend
// and tick marks but does not need to scale linearly with the font factor.
double get defaultChartHeight => scaleByFontFactor(110.0);
double get actionWidgetSize => scaleByFontFactor(48.0);
double get statusLineHeight => scaleByFontFactor(20.0);
double get inputDecorationElementHeight => scaleByFontFactor(20.0);
// Padding / spacing constants:
const extraLargeSpacing = 32.0;
const largeSpacing = 16.0;
const defaultSpacing = 12.0;
const intermediateSpacing = 10.0;
const denseSpacing = 8.0;
const defaultTabBarPadding = 14.0;
const tabBarSpacing = 8.0;
const denseRowSpacing = 6.0;
const hoverCardBorderSize = 2.0;
const borderPadding = 2.0;
const densePadding = 4.0;
const noPadding = 0.0;
const defaultScrollBarOffset = 10.0;
// Other UI related constants:
final defaultBorderRadius = BorderRadius.circular(_defaultBorderRadiusValue);
const defaultRadius = Radius.circular(_defaultBorderRadiusValue);
const _defaultBorderRadiusValue = 16.0;
const defaultElevation = 4.0;
double get smallProgressSize => scaleByFontFactor(12.0);
double get mediumProgressSize => scaleByFontFactor(24.0);
const defaultTabBarViewPhysics = NeverScrollableScrollPhysics();
// Font size constants:
double get defaultFontSize => scaleByFontFactor(unscaledDefaultFontSize);
const unscaledDefaultFontSize = 12.0;
double get smallFontSize => scaleByFontFactor(unscaledSmallFontSize);
const unscaledSmallFontSize = 10.0;
extension DevToolsSharedColorScheme on ColorScheme {
bool get isLight => brightness == Brightness.light;
bool get isDark => brightness == Brightness.dark;
Color get warningContainer => tertiaryContainer;
Color get onWarningContainer => onTertiaryContainer;
Color get onWarningContainerLink =>
isLight ? tertiary : const Color(0xFFDF9F32);
Color get onErrorContainerLink => isLight ? error : const Color(0xFFFF897D);
Color get subtleTextColor => const Color(0xFF919094);
Color get _devtoolsLink =>
isLight ? const Color(0xFF1976D2) : Colors.lightBlueAccent;
Color get alternatingBackgroundColor1 =>
isLight ? Colors.white : const Color(0xFF1B1B1F);
Color get alternatingBackgroundColor2 =>
isLight ? const Color(0xFFF2F0F4) : const Color(0xFF303033);
Color get selectedRowBackgroundColor =>
isLight ? const Color(0xFFC7C6CA) : const Color(0xFF5E5E62);
Color get chartAccentColor =>
isLight ? const Color(0xFFCCCCCC) : const Color(0xFF585858);
Color get contrastTextColor => isLight ? Colors.black : Colors.white;
Color get _chartSubtleColor =>
isLight ? const Color(0xFF999999) : const Color(0xFF8A8A8A);
Color get tooltipTextColor => isLight ? Colors.white : Colors.black;
}
/// Utility extension methods to the [ThemeData] class.
extension ThemeDataExtension on ThemeData {
/// Returns whether we are currently using a dark theme.
bool get isDarkTheme => brightness == Brightness.dark;
TextStyle get regularTextStyle => fixBlurryText(
textTheme.bodySmall!.copyWith(
color: colorScheme.onSurface,
fontSize: defaultFontSize,
),
);
TextStyle regularTextStyleWithColor(Color? color) =>
regularTextStyle.copyWith(color: color);
TextStyle get errorTextStyle => regularTextStyleWithColor(colorScheme.error);
TextStyle get boldTextStyle =>
regularTextStyle.copyWith(fontWeight: FontWeight.bold);
TextStyle get subtleTextStyle =>
regularTextStyle.copyWith(color: colorScheme.subtleTextColor);
TextStyle get fixedFontStyle => fixBlurryText(
regularTextStyle.copyWith(
fontFamily: 'RobotoMono',
// Slightly smaller for fixes font text since it will appear larger
// to begin with.
fontSize: defaultFontSize - 1,
),
);
TextStyle get subtleFixedFontStyle => fixedFontStyle.copyWith(
color: colorScheme.subtleTextColor,
);
TextStyle get selectedSubtleTextStyle =>
subtleTextStyle.copyWith(color: colorScheme.onSurface);
TextStyle get tooltipFixedFontStyle => fixedFontStyle.copyWith(
color: colorScheme.tooltipTextColor,
);
TextStyle get fixedFontLinkStyle => fixedFontStyle.copyWith(
color: colorScheme._devtoolsLink,
decoration: TextDecoration.underline,
);
TextStyle get linkTextStyle => fixBlurryText(
TextStyle(
color: colorScheme._devtoolsLink,
decoration: TextDecoration.underline,
fontSize: defaultFontSize,
),
);
TextStyle get subtleChartTextStyle => fixBlurryText(
TextStyle(
color: colorScheme._chartSubtleColor,
fontSize: smallFontSize,
),
);
TextStyle get searchMatchHighlightStyle => fixBlurryText(
const TextStyle(
color: Colors.black,
backgroundColor: activeSearchMatchColor,
),
);
TextStyle get searchMatchHighlightStyleFocused => fixBlurryText(
const TextStyle(
color: Colors.black,
backgroundColor: searchMatchColor,
),
);
TextStyle get legendTextStyle => fixBlurryText(
TextStyle(
fontWeight: FontWeight.normal,
fontSize: smallFontSize,
decoration: TextDecoration.none,
),
);
}
/// Returns a [TextStyle] with [FontFeature.proportionalFigures] applied to
/// fix blurry text.
TextStyle fixBlurryText(TextStyle style) {
return style.copyWith(
fontFeatures: [const FontFeature.proportionalFigures()],
);
}
// Duration and animation constants:
/// A short duration to use for animations.
///
/// Use this when you want less emphasis on the animation and more on the
/// animation result, or when you have multiple animations running in sequence
/// For example, in the timeline we use this when we are zooming the flame chart
/// and scrolling to an offset immediately after.
const shortDuration = Duration(milliseconds: 50);
/// A longer duration than [shortDuration] but quicker than [defaultDuration].
///
/// Use this for thinks that would show a bit of animation, but that we want to
/// effectively seem immediate to users.
const rapidDuration = Duration(milliseconds: 100);
/// The default duration to use for animations.
const defaultDuration = Duration(milliseconds: 200);
/// A long duration to use for animations.
///
/// Use this rarely, only when you want added emphasis to an animation.
const longDuration = Duration(milliseconds: 400);
/// Builds a [defaultDuration] animation controller.
///
/// This is the standard duration to use for animations.
AnimationController defaultAnimationController(
TickerProvider vsync, {
double? value,
}) {
return AnimationController(
duration: defaultDuration,
vsync: vsync,
value: value,
);
}
/// Builds a [longDuration] animation controller.
///
/// This is the standard duration to use for slow animations.
AnimationController longAnimationController(
TickerProvider vsync, {
double? value,
}) {
return AnimationController(
duration: longDuration,
vsync: vsync,
value: value,
);
}
/// The default curve we use for animations.
///
/// Inspector animations benefit from a symmetric animation curve which makes
/// it easier to reverse animations.
const defaultCurve = Curves.easeInOutCubic;
/// Builds a [CurvedAnimation] with [defaultCurve].
///
/// This is the standard curve for animations in DevTools.
CurvedAnimation defaultCurvedAnimation(AnimationController parent) =>
CurvedAnimation(curve: defaultCurve, parent: parent);
/// Measures the screen size to determine whether it is strictly larger
/// than [width], scaled to the current font factor.
bool isScreenWiderThan(
BuildContext context,
double? width,
) {
return width == null ||
MediaQuery.of(context).size.width > scaleByFontFactor(width);
}
ButtonStyle denseAwareOutlinedButtonStyle(
BuildContext context,
double? minScreenWidthForTextBeforeScaling,
) {
final buttonStyle =
Theme.of(context).outlinedButtonTheme.style ?? const ButtonStyle();
return _generateButtonStyle(
context: context,
buttonStyle: buttonStyle,
minScreenWidthForTextBeforeScaling: minScreenWidthForTextBeforeScaling,
);
}
ButtonStyle denseAwareTextButtonStyle(
BuildContext context, {
double? minScreenWidthForTextBeforeScaling,
}) {
final buttonStyle =
Theme.of(context).textButtonTheme.style ?? const ButtonStyle();
return _generateButtonStyle(
context: context,
buttonStyle: buttonStyle,
minScreenWidthForTextBeforeScaling: minScreenWidthForTextBeforeScaling,
);
}
ButtonStyle _generateButtonStyle({
required BuildContext context,
required ButtonStyle buttonStyle,
double? minScreenWidthForTextBeforeScaling,
}) {
if (!isScreenWiderThan(context, minScreenWidthForTextBeforeScaling)) {
buttonStyle = buttonStyle.copyWith(
padding: MaterialStateProperty.resolveWith<EdgeInsets>((_) {
return EdgeInsets.zero;
}),
);
}
return buttonStyle;
}
| devtools/packages/devtools_app_shared/lib/src/ui/theme/theme.dart/0 | {
"file_path": "devtools/packages/devtools_app_shared/lib/src/ui/theme/theme.dart",
"repo_id": "devtools",
"token_count": 6005
} | 132 |
// Copyright 2023 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_shared/ui.dart';
import 'package:devtools_app_shared/utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import '../test_utils.dart';
void main() {
setUp(() {
setGlobal(IdeTheme, IdeTheme());
});
group('AreaPaneHeader', () {
const titleText = 'The title';
testWidgets(
'actions do not take up space when not present',
(WidgetTester tester) async {
await tester.pumpWidget(
wrap(
const AreaPaneHeader(
title: Text(titleText),
),
),
);
final Row row = tester.widget(find.byType(Row)) as Row;
expect(
row.children.length,
equals(1),
);
expect(
find.text(titleText),
findsOneWidget,
);
},
);
testWidgets('shows actions', (WidgetTester tester) async {
const actionText = 'The Action Text';
const action = Text(actionText);
await tester.pumpWidget(
wrap(
const AreaPaneHeader(
title: Text(titleText),
actions: [action],
),
),
);
final Row row = tester.widget(find.byType(Row)) as Row;
expect(
row.children.length,
equals(2),
);
expect(find.text(actionText), findsOneWidget);
expect(
find.text(titleText),
findsOneWidget,
);
});
});
}
| devtools/packages/devtools_app_shared/test/ui/common_test.dart/0 | {
"file_path": "devtools/packages/devtools_app_shared/test/ui/common_test.dart",
"repo_id": "devtools",
"token_count": 741
} | 133 |
// Copyright 2023 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:io';
import 'package:args/command_runner.dart';
import 'package:io/io.dart';
import 'package:path/path.dart' as path;
/// Command that builds a DevTools extension and copies the built output to
/// the parent package extension location.
///
/// Example usage:
///
/// dart run devtools_extensions build_and_copy \
/// --source=path/to/your_extension_web_app \
/// --dest=path/to/your_pub_package/extension/devtools
class BuildExtensionCommand extends Command {
BuildExtensionCommand() {
argParser
..addOption(
_sourceKey,
help: 'The source location for the extension flutter web app (can be '
'relative or absolute)',
valueHelp: 'path/to/foo/packages/foo_devtools_extension',
mandatory: true,
)
..addOption(
_destinationKey,
help: 'The destination location for the extension build output (can be '
'relative or absolute)',
valueHelp: 'path/to/foo/packages/foo/extension/devtools',
mandatory: true,
);
}
static const _sourceKey = 'source';
static const _destinationKey = 'dest';
@override
String get name => 'build_and_copy';
@override
String get description =>
'Command that builds a DevTools extension from source and copies the '
'built output to the parent package extension location.';
@override
Future<void> run() async {
final source = argResults?[_sourceKey]! as String;
final destination = argResults?[_destinationKey]! as String;
final processManager = ProcessManager();
_log('Building the extension Flutter web app...');
await _runProcess(
processManager,
Platform.isWindows ? 'flutter.bat' : 'flutter',
[
'build',
'web',
'--web-renderer',
'canvaskit',
'--pwa-strategy=offline-first',
'--release',
'--no-tree-shake-icons',
],
workingDirectory: source,
);
// TODO(kenz): investigate if we need to perform a windows equivalent of
// `chmod` or if we even need to perform `chmod` for linux / mac anymore.
if (!Platform.isWindows) {
_log('Setting canvaskit permissions...');
await _runProcess(
processManager,
'chmod',
[
'0755',
// Note: using a wildcard `canvaskit.*` throws.
'build/web/canvaskit/canvaskit.js',
'build/web/canvaskit/canvaskit.wasm',
],
workingDirectory: source,
);
}
_log('Copying built output to the extension destination...');
await _copyBuildToDestination(source: source, dest: destination);
}
Future<void> _copyBuildToDestination({
required String source,
required String dest,
}) async {
_log('Replacing the existing extension build with the new one...');
final sourceBuildPath = path.join(source, 'build', 'web');
final destinationBuildPath = path.join(dest, 'build');
final destinationDirectory = Directory(destinationBuildPath);
if (destinationDirectory.existsSync()) {
destinationDirectory.deleteSync(recursive: true);
}
Directory(destinationBuildPath).createSync(recursive: true);
await copyPath(
sourceBuildPath,
destinationBuildPath,
);
_log(
'Successfully copied extension assets from '
'"${Directory(source).resolveSymbolicLinksSync()}" to'
'"${Directory(dest).resolveSymbolicLinksSync()}"',
);
}
void _log(String message) => stdout.writeln('[$name] $message');
Future<void> _runProcess(
ProcessManager processManager,
String exe,
List<String> args, {
String? workingDirectory,
}) async {
final buildProcess = await processManager.spawn(
exe,
args,
workingDirectory: workingDirectory,
);
final code = await buildProcess.exitCode;
if (code != 0) {
throw ProcessException(exe, args, 'Failed with exit code: $code', code);
}
}
}
| devtools/packages/devtools_extensions/bin/_build_and_copy.dart/0 | {
"file_path": "devtools/packages/devtools_extensions/bin/_build_and_copy.dart",
"repo_id": "devtools",
"token_count": 1514
} | 134 |
// Copyright 2023 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:dart_foo/dart_foo.dart';
import 'package:flutter/material.dart';
import 'package:foo/foo.dart';
void main() {
runApp(const MyAppThatUsesFoo());
}
class MyAppThatUsesFoo extends StatelessWidget {
const MyAppThatUsesFoo({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Foo Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepOrange),
useMaterial3: true,
),
home: const HomePage(title: 'App that uses package:foo'),
);
}
}
class HomePage extends StatefulWidget {
const HomePage({super.key, required this.title});
final String title;
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
late final FooController fooController;
late final dartFoo = DartFoo();
@override
void initState() {
super.initState();
fooController = FooController.instance;
dartFoo.foo();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body: Center(
child: FooWidget(
fooController: fooController,
),
),
);
}
}
| devtools/packages/devtools_extensions/example/app_that_uses_foo/lib/main.dart/0 | {
"file_path": "devtools/packages/devtools_extensions/example/app_that_uses_foo/lib/main.dart",
"repo_id": "devtools",
"token_count": 552
} | 135 |
// Copyright 2024 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.
class DartFoo {
Future<void> loop() async {
for (var i = 0; i < 10000; i++) {
// ignore: avoid_print, used in an example
print('Looping from DartFoo.loop(): $i');
await Future.delayed(const Duration(seconds: 10));
}
}
void foo() {}
}
| devtools/packages/devtools_extensions/example/packages_with_extensions/dart_foo/packages/dart_foo/lib/dart_foo.dart/0 | {
"file_path": "devtools/packages/devtools_extensions/example/packages_with_extensions/dart_foo/packages/dart_foo/lib/dart_foo.dart",
"repo_id": "devtools",
"token_count": 148
} | 136 |
!build
| devtools/packages/devtools_extensions/example/packages_with_extensions/foo/packages/foo/extension/devtools/.pubignore/0 | {
"file_path": "devtools/packages/devtools_extensions/example/packages_with_extensions/foo/packages/foo/extension/devtools/.pubignore",
"repo_id": "devtools",
"token_count": 3
} | 137 |
# foo_devtools_extension
An example DevTools extension for `package:foo`. This Flutter web app, `foo_devtools_extension`,
is included with the parent `package:foo` by including its pre-compiled build output in the
`foo/extension/devtools/build` directory.
Then, when using DevTools to debugging an app that imports the parent `package:foo`
(see `devtools_extensions/example/app_that_uses_foo`), the Flutter web app
`foo_devtools_extension` will be embedded in DevTools in its own screen.
The full instructions for building DevTools extensions can be found in the main
[README.md](https://github.com/flutter/devtools/blob/master/packages/devtools_extensions/README.md) for the `devtools_extensions` package.
| devtools/packages/devtools_extensions/example/packages_with_extensions/foo/packages/foo_devtools_extension/README.md/0 | {
"file_path": "devtools/packages/devtools_extensions/example/packages_with_extensions/foo/packages/foo_devtools_extension/README.md",
"repo_id": "devtools",
"token_count": 205
} | 138 |
// Copyright 2023 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_test_utils.dart';
// To run integration tests, run the following from `devtools_extensions/`:
// `dart run integration_test/run_tests.dart`
//
// To see a list of arguments that you can pass to this test script, please run
// the above command with the '-h' flag.
const _testDirectory = 'integration_test/test';
bool debugTestScript = true;
void main(List<String> args) async {
final testRunnerArgs = IntegrationTestRunnerArgs(
args,
verifyValidTarget: false,
);
await runOneOrManyTests(
testDirectoryPath: _testDirectory,
testRunnerArgs: testRunnerArgs,
runTest: _runIntegrationTest,
newArgsGenerator: (args) => IntegrationTestRunnerArgs(args),
debugLogging: debugTestScript,
);
}
Future<void> _runIntegrationTest(
IntegrationTestRunnerArgs testRunnerArgs,
) async {
final testRunner = IntegrationTestRunner();
try {
await testRunner.run(
testRunnerArgs.testTarget!,
testDriver: 'test_driver/integration_test.dart',
headless: testRunnerArgs.headless,
dartDefineArgs: ['use_simulated_environment=true'],
debugLogging: debugTestScript,
);
} finally {
await testRunner.cancelAllStreamSubscriptions();
}
}
| devtools/packages/devtools_extensions/integration_test/run_tests.dart/0 | {
"file_path": "devtools/packages/devtools_extensions/integration_test/run_tests.dart",
"repo_id": "devtools",
"token_count": 455
} | 139 |
// 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 'package:vm_service/vm_service.dart';
import 'heap_sample.dart';
abstract class DecodeEncode<T> {
int get version;
String encode(T sample);
/// More than one Encoded entry, add a comma and the Encoded entry.
String encodeAnother(T sample);
T fromJson(Map<String, dynamic> json);
}
abstract class MemoryJson<T> implements DecodeEncode<T> {
MemoryJson();
/// Given a JSON string representing an array of HeapSample, decode to a
/// List of HeapSample.
MemoryJson.decode(
String payloadName, {
required String argJsonString,
Map<String, dynamic>? argDecodedMap,
}) {
final Map<String, dynamic> decodedMap =
argDecodedMap ?? jsonDecode(argJsonString);
Map<String, dynamic> payload = decodedMap[payloadName];
int payloadVersion = payload[jsonVersionField];
final payloadDevToolsScreen = payload[jsonDevToolsScreenField];
if (payloadVersion != version) {
payload = upgradeToVersion(payload, payloadVersion);
payloadVersion = version;
}
_memoryPayload = payloadDevToolsScreen == devToolsScreenValueMemory;
_payloadVersion = payloadVersion;
// Any problem return (data is empty).
if (!isMatchedVersion || !isMemoryPayload) return;
final List dynamicList = payload[jsonDataField];
for (var index = 0; index < dynamicList.length; index++) {
final sample = fromJson(dynamicList[index] as Map<String, dynamic>);
data.add(sample);
}
}
Map<String, dynamic> upgradeToVersion(
Map<String, dynamic> payload,
int oldVersion,
);
late final int _payloadVersion;
int get payloadVersion => _payloadVersion;
/// Imported JSON data loaded and converted, if necessary, to the latest version.
bool get isMatchedVersion => _payloadVersion == version;
late final bool _memoryPayload;
/// JSON payload field "dart<T>DevToolsScreen" has a value of "memory" e.g.,
/// "dartDevToolsScreen": "memory"
bool get isMemoryPayload => _memoryPayload;
/// If data is empty check isMatchedVersion and isMemoryPayload to ensure the
/// JSON file loaded is a memory file.
final data = <T>[];
static const String jsonDevToolsScreenField = 'dartDevToolsScreen';
// TODO(terry): Expose Timeline.
// const String _devToolsScreenValueTimeline = 'timeline';
static const String devToolsScreenValueMemory = 'memory';
static const String jsonVersionField = 'version';
static const String jsonDataField = 'data';
/// Trailer portion:
static String get trailer => '\n]\n}}';
}
class SamplesMemoryJson extends MemoryJson<HeapSample> {
SamplesMemoryJson();
/// Given a JSON string representing an array of HeapSample, decode to a
/// List of HeapSample.
SamplesMemoryJson.decode({
required String argJsonString,
Map<String, dynamic>? argDecodedMap,
}) : super.decode(
_jsonMemoryPayloadField,
argJsonString: argJsonString,
argDecodedMap: argDecodedMap,
);
/// Exported JSON payload of collected memory statistics.
static const String _jsonMemoryPayloadField = 'samples';
/// Structure of the memory JSON file:
///
/// {
/// "samples": {
/// "version": 1,
/// "dartDevToolsScreen": "memory"
/// "data": [
/// Encoded Heap Sample see section below.
/// ]
/// }
/// }
/// Header portion (memoryJsonHeader) e.g.,
/// =======================================
/// {
/// "samples": {
/// "version": 1,
/// "dartDevToolsScreen": "memory"
/// "data": [
///
/// Encoded Allocations entry (SamplesMemoryJson),
/// ==============================================================================
/// {
/// "timestamp":1581540967479,
/// "rss":211419136,
/// "capacity":50956576,
/// "used":41384952,
/// "external":166176,
/// "gc":false,
/// "adb_memoryInfo":{
/// "Realtime":450147758,
/// "Java Heap":7416,
/// "Native Heap":41712,
/// "Code":12644,
/// "Stack":52,
/// "Graphics":0,
/// "Private Other":94420,
/// "System":6178,
/// "Total":162422
/// }
/// },
///
/// Trailer portion (memoryJsonTrailer) e.g.,
/// =========================================
/// ]
/// }
/// }
@override
int get version => HeapSample.version;
/// Encoded Heap Sample
@override
String encode(HeapSample sample) => jsonEncode(sample);
/// More than one Encoded Heap Sample, add a comma and the Encoded Heap Sample.
@override
String encodeAnother(HeapSample sample) => ',\n${jsonEncode(sample)}';
@override
HeapSample fromJson(Map<String, dynamic> json) => HeapSample.fromJson(json);
@override
Map<String, dynamic> upgradeToVersion(
Map<String, dynamic> payload,
int oldVersion,
) =>
throw UnimplementedError(
'${HeapSample.version} is the only valid HeapSample version',
);
/// Given a list of HeapSample, encode as a Json string.
static String encodeList(List<HeapSample> data) {
final samplesJson = SamplesMemoryJson();
final result = StringBuffer();
// Iterate over all HeapSamples collected.
data.map((f) {
final encodedValue = result.isNotEmpty
? samplesJson.encodeAnother(f)
: samplesJson.encode(f);
result.write(encodedValue);
}).toList();
return '$header$result${MemoryJson.trailer}';
}
static String get header => '{"$_jsonMemoryPayloadField": {'
'"${MemoryJson.jsonVersionField}": ${HeapSample.version}, '
'"${MemoryJson.jsonDevToolsScreenField}": "${MemoryJson.devToolsScreenValueMemory}", '
'"${MemoryJson.jsonDataField}": [\n';
}
/// Structure of the memory JSON file:
///
/// {
/// "allocations": {
/// "version": 2,
/// "dartDevToolsScreen": "memory"
/// "data": [
/// Encoded ClassHeapStats see section below.
/// ]
/// }
/// }
/// Header portion (memoryJsonHeader) e.g.,
/// =======================================
/// {
/// "allocations": {
/// "version": 2,
/// "dartDevToolsScreen": "memory"
/// "data": [
///
/// Encoded Allocations entry (AllocationMemoryJson),
/// ==============================================================================
/// {
/// "class" : {
/// id: "classes/1"
/// name: "AClassName"
/// },
/// "instancesCurrent": 100,
/// "instancesAccumulated": 0,
/// "bytesCurrent": 55,
/// "accumulatedSize": 5,
/// "_new": [
/// 100,
/// 50,
/// 5
/// ],
/// "_old": [
/// 0,
/// 0,
/// 0
/// ]
/// },
///
/// Trailer portion (memoryJsonTrailer) e.g.,
/// =========================================
/// ]
/// }
/// }
class AllocationMemoryJson extends MemoryJson<ClassHeapStats> {
AllocationMemoryJson();
/// Given a JSON string representing an array of HeapSample, decode to a
/// List of HeapSample.
AllocationMemoryJson.decode({
required String argJsonString,
Map<String, dynamic>? argDecodedMap,
}) : super.decode(
_jsonAllocationPayloadField,
argJsonString: argJsonString,
argDecodedMap: argDecodedMap,
);
/// Exported JSON payload of collected memory statistics.
static const String _jsonAllocationPayloadField = 'allocations';
/// Encoded ClassHeapDetailStats
@override
String encode(ClassHeapStats sample) => jsonEncode(sample.json);
/// More than one Encoded ClassHeapDetailStats, add a comma and the Encoded ClassHeapDetailStats entry.
@override
String encodeAnother(ClassHeapStats sample) =>
',\n${jsonEncode(sample.json)}';
@override
ClassHeapStats fromJson(Map<String, dynamic> json) =>
ClassHeapStats.parse(json)!;
@override
Map<String, dynamic> upgradeToVersion(
Map<String, dynamic> payload,
int oldVersion,
) {
assert(oldVersion < version);
assert(oldVersion == 1);
final updatedPayload = Map<String, dynamic>.of(payload);
updatedPayload['version'] = version;
final oldData = (payload['data'] as List).map((e) => _OldData(e));
updatedPayload['data'] = [
for (final data in oldData)
{
'type': 'ClassHeapStats',
'class': <String, dynamic>{
'type': '@Class',
...data.class_,
},
'bytesCurrent': data.bytesCurrent,
'accumulatedSize': data.bytesDelta,
'instancesCurrent': data.instancesCurrent,
'instancesAccumulated': data.instancesDelta,
// new and old space data is just reported as a list of ints
'_new': <int>[
// # of instances in new space.
data.instancesCurrent,
// shallow memory consumption in new space.
data.bytesCurrent,
// external memory consumption.
0,
],
// We'll just fudge the old space numbers.
'_old': const <int>[0, 0, 0],
},
];
return updatedPayload;
}
@override
int get version => allocationFormatVersion;
static const int allocationFormatVersion = 2;
/// Given a list of HeapSample, encode as a Json string.
static String encodeList(List<ClassHeapStats> data) {
final allocationJson = AllocationMemoryJson();
final result = StringBuffer();
// Iterate over all ClassHeapDetailStats collected.
data.map((f) {
final encodedValue = result.isNotEmpty
? allocationJson.encodeAnother(f)
: allocationJson.encode(f);
result.write(encodedValue);
}).toList();
return '$header$result${MemoryJson.trailer}';
}
/// Allocations Header portion:
static String get header => '{"$_jsonAllocationPayloadField": {'
'"${MemoryJson.jsonVersionField}": $allocationFormatVersion, '
'"${MemoryJson.jsonDevToolsScreenField}": "${MemoryJson.devToolsScreenValueMemory}", '
'"${MemoryJson.jsonDataField}": [\n';
}
extension type _OldData(Map<String, dynamic> data) {
Map<String, dynamic> get class_ => data['class'];
int get bytesCurrent => data['bytesCurrent'];
int get bytesDelta => data['bytesDelta'];
int get instancesCurrent => data['instancesCurrent'];
int get instancesDelta => data['instancesDelta'];
}
| devtools/packages/devtools_shared/lib/src/memory/memory_json.dart/0 | {
"file_path": "devtools/packages/devtools_shared/lib/src/memory/memory_json.dart",
"repo_id": "devtools",
"token_count": 3870
} | 140 |
// Copyright 2022 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: avoid_print
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:path/path.dart' as path;
/// The directory used to store per-user settings for Dart tooling.
Directory getDartPrefsDirectory() {
return Directory(path.join(getUserHomeDir(), '.dart'));
}
/// Return the user's home directory.
String getUserHomeDir() {
final String envKey =
Platform.operatingSystem == 'windows' ? 'APPDATA' : 'HOME';
final String? value = Platform.environment[envKey];
return value ?? '.';
}
Stream<String> transformToLines(Stream<List<int>> byteStream) {
return byteStream
.transform<String>(utf8.decoder)
.transform<String>(const LineSplitter());
}
mixin IOMixin {
static const killTimeout = Duration(seconds: 10);
final stdoutController = StreamController<String>.broadcast();
final stderrController = StreamController<String>.broadcast();
final streamSubscriptions = <StreamSubscription<String>>[];
void listenToProcessOutput(
Process process, {
void Function(String)? onStdout,
void Function(String)? onStderr,
void Function(String)? printCallback,
String printTag = '',
}) {
printCallback =
printCallback ?? (line) => _defaultPrintCallback(line, tag: printTag);
streamSubscriptions.addAll([
transformToLines(process.stdout).listen((String line) {
onStdout?.call(line);
stdoutController.add(line);
}),
transformToLines(process.stderr).listen((String line) {
onStderr?.call(line);
stderrController.add(line);
}),
// This is just debug printing to aid running/debugging tests locally.
stdoutController.stream.listen(printCallback),
stderrController.stream.listen(printCallback),
]);
}
Future<void> cancelAllStreamSubscriptions() async {
await Future.wait(streamSubscriptions.map((s) => s.cancel()));
await Future.wait([
stdoutController.close(),
stderrController.close(),
]);
streamSubscriptions.clear();
}
static void _defaultPrintCallback(String line, {String tag = ''}) {
print(tag.isNotEmpty ? '$tag - $line' : line);
}
Future<int> killGracefully(
Process process, {
bool debugLogging = false,
}) async {
final processId = process.pid;
if (debugLogging) {
print('Sending SIGTERM to $processId..');
}
await cancelAllStreamSubscriptions();
Process.killPid(processId);
return process.exitCode.timeout(
killTimeout,
onTimeout: () => killForcefully(process, debugLogging: debugLogging),
);
}
Future<int> killForcefully(
Process process, {
bool debugLogging = false,
}) {
final processId = process.pid;
// Use sigint here instead of sigkill. See
// https://github.com/flutter/flutter/issues/117415.
if (debugLogging) {
print('Sending SIGINT to $processId..');
}
Process.killPid(processId, ProcessSignal.sigint);
return process.exitCode;
}
}
| devtools/packages/devtools_shared/lib/src/test/io_utils.dart/0 | {
"file_path": "devtools/packages/devtools_shared/lib/src/test/io_utils.dart",
"repo_id": "devtools",
"token_count": 1116
} | 141 |
// Copyright 2022 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/src/service_utils.dart';
import 'package:test/test.dart';
void main() {
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);
});
});
}
| devtools/packages/devtools_shared/test/service_utils_test.dart/0 | {
"file_path": "devtools/packages/devtools_shared/test/service_utils_test.dart",
"repo_id": "devtools",
"token_count": 1311
} | 142 |
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: invalid_use_of_visible_for_testing_member, devtools_test is only used in test code.
import 'package:devtools_app_shared/service.dart';
// ignore: implementation_imports, intentional import from src/
import 'package:devtools_app_shared/src/service/isolate_manager.dart';
import 'package:flutter/foundation.dart';
import 'package:mockito/mockito.dart';
import 'package:vm_service/vm_service.dart';
import 'generated.mocks.dart';
base class FakeIsolateManager extends Fake with TestIsolateManager {
FakeIsolateManager({
this.rootLibrary = 'package:my_app/main.dart',
});
final String? rootLibrary;
@override
ValueListenable<IsolateRef?> get selectedIsolate => _selectedIsolate;
final _selectedIsolate = ValueNotifier(
IsolateRef.parse({
'id': 'fake_isolate_id',
'name': 'selected-isolate',
}),
);
@override
ValueListenable<IsolateRef?> get mainIsolate => _mainIsolate;
final _mainIsolate =
ValueNotifier(IsolateRef.parse({'id': 'fake_main_isolate_id'}));
@override
ValueNotifier<List<IsolateRef>> get isolates {
final value = _selectedIsolate.value;
_isolates ??= ValueNotifier([if (value != null) value]);
return _isolates!;
}
final _pausedState = ValueNotifier<bool>(false);
@visibleForTesting
void setMainIsolatePausedState(bool paused) {
_pausedState.value = paused;
}
@override
IsolateState? get mainIsolateState => isolateState(null);
ValueNotifier<List<IsolateRef>>? _isolates;
@override
IsolateState isolateState(IsolateRef? isolate) {
final state = MockIsolateState();
final mockIsolate = MockIsolate();
final rootLib = LibraryRef(id: '0', uri: rootLibrary);
when(mockIsolate.libraries).thenReturn(
[
rootLib,
LibraryRef(id: '1', uri: 'dart:io'),
],
);
when(mockIsolate.rootLib).thenReturn(rootLib);
when(mockIsolate.id).thenReturn('mock-isolate-id');
when(state.isolateNow).thenReturn(mockIsolate);
when(state.isPaused).thenReturn(_pausedState);
when(state.isolate).thenAnswer((_) => Future.value(mockIsolate));
return state;
}
}
| devtools/packages/devtools_test/lib/src/mocks/fake_isolate_manager.dart/0 | {
"file_path": "devtools/packages/devtools_test/lib/src/mocks/fake_isolate_manager.dart",
"repo_id": "devtools",
"token_count": 818
} | 143 |
# 0.0.1
* Initial commit for package:perfetto_compiled sources.
| devtools/third_party/packages/perfetto_ui_compiled/CHANGELOG.md/0 | {
"file_path": "devtools/third_party/packages/perfetto_ui_compiled/CHANGELOG.md",
"repo_id": "devtools",
"token_count": 22
} | 144 |
A set of icons representing Flutter widgets. | devtools/third_party/packages/widget_icons/README.md/0 | {
"file_path": "devtools/third_party/packages/widget_icons/README.md",
"repo_id": "devtools",
"token_count": 9
} | 145 |
#!/bin/bash -e
SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
if [ ! -z "$DEVTOOLS_TOOL_FLUTTER_FROM_PATH" ]
then
echo Running devtools_tool using Dart/Flutter from PATH because DEVTOOLS_TOOL_FLUTTER_FROM_PATH is set
dart run "$SCRIPT_DIR/devtools_tool.dart" "$@"
else
if [ ! -d $SCRIPT_DIR/../flutter-sdk ]
then
# If the `devtools/tool/flutter-sdk` directory does not exist yet, use whatever Dart
# is on the user's path to update it before proceeding.
echo "Running devtools_tool using the Dart SDK from `which dart` to create the Flutter SDK in tool/flutter-sdk."
dart run "$SCRIPT_DIR/devtools_tool.dart" update-flutter-sdk
fi
"$SCRIPT_DIR/../flutter-sdk/bin/dart" run "$SCRIPT_DIR/devtools_tool.dart" "$@"
fi
| devtools/tool/bin/devtools_tool/0 | {
"file_path": "devtools/tool/bin/devtools_tool",
"repo_id": "devtools",
"token_count": 300
} | 146 |
#!/bin/bash
# Copyright 2022 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.
# Any subsequent commands failure will cause this script to exit immediately
set -e
# To determine the most recent candidate available on g3 find the largest
# tag that matches the version X.Y.Z-M.N.pre, where Z=0 and N=0.(i.e. X.Y.0-M.0.pre)
LATEST_FLUTTER_CANDIDATE=$(git ls-remote --tags --sort='-v:refname' https://flutter.googlesource.com/mirrors/flutter/ \
| grep -E "refs/tags/[0-9]+.[0-9]+.0-[0-9]+.0.pre" \
| cut -f2 \
| sort --version-sort \
| tail -n1 \
| sed 's/^.*\(flutter.*\)$/\1/'\
)
echo $LATEST_FLUTTER_CANDIDATE
| devtools/tool/latest_flutter_candidate.sh/0 | {
"file_path": "devtools/tool/latest_flutter_candidate.sh",
"repo_id": "devtools",
"token_count": 276
} | 147 |
// Copyright 2023 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:io';
import 'package:args/command_runner.dart';
import 'package:devtools_tool/model.dart';
import 'package:io/io.dart';
import 'package:path/path.dart' as path;
import '../utils.dart';
import 'shared.dart';
const _buildFlag = 'build';
class UpdatePerfettoCommand extends Command {
UpdatePerfettoCommand() {
argParser.addOption(
_buildFlag,
abbr: 'b',
help: 'The build location of the Perfetto assets. When this is not '
'specified, the Perfetto assets will be fetched from the latest '
'source code at "android.googlesource.com".',
valueHelp: '/Users/me/path/to/perfetto/out/ui/ui/dist',
);
}
@override
String get name => 'update-perfetto';
@override
String get description =>
'Updates the Perfetto assets that are included in the DevTools app bundle.';
@override
Future run() async {
if (Platform.isWindows) {
// In tools/install-build-deps in Perfetto:
// "Building the UI on Windows is unsupported".
throw 'Updating Perfetto is not currently supported on Windows';
}
final processManager = ProcessManager();
final perfettoUiCompiledLibPath = pathFromRepoRoot(
path.join('third_party', 'packages', 'perfetto_ui_compiled', 'lib'),
);
final perfettoUiCompiledBuildPath =
path.join(perfettoUiCompiledLibPath, 'dist');
final perfettoDevToolsPath =
path.join(perfettoUiCompiledBuildPath, 'devtools');
logStatus(
'moving DevTools-Perfetto integration files to a temp directory.',
);
final tempPerfettoDevTools =
Directory.systemTemp.createTempSync('perfetto_devtools');
await copyPath(perfettoDevToolsPath, tempPerfettoDevTools.path);
logStatus('deleting existing Perfetto build');
final existingBuild = Directory(perfettoUiCompiledBuildPath);
existingBuild.deleteSync(recursive: true);
logStatus('updating Perfetto build');
final buildLocation = argResults![_buildFlag] as String?;
if (buildLocation != null) {
logStatus('using Perfetto build from $buildLocation');
logStatus(
'copying content from $buildLocation to $perfettoUiCompiledLibPath',
);
await copyPath(buildLocation, perfettoUiCompiledBuildPath);
} else {
logStatus('cloning Perfetto from HEAD and building from source');
final tempPerfettoClone =
Directory.systemTemp.createTempSync('perfetto_clone');
await processManager.runProcess(
CliCommand.git(
[
'clone',
'https://android.googlesource.com/platform/external/perfetto',
],
),
workingDirectory: tempPerfettoClone.path,
);
logStatus('installing build deps and building the Perfetto UI');
await processManager.runAll(
commands: [
CliCommand(path.join('tools', 'install-build-deps'), ['--ui']),
CliCommand(path.join('ui', 'build'), []),
],
workingDirectory: path.join(tempPerfettoClone.path, 'perfetto'),
);
final buildOutputPath = path.join(
tempPerfettoClone.path,
'perfetto',
'out',
'ui',
'ui',
'dist',
);
logStatus(
'copying content from $buildOutputPath to $perfettoUiCompiledLibPath',
);
await copyPath(buildOutputPath, perfettoUiCompiledLibPath);
logStatus('deleting perfetto clone');
tempPerfettoClone.deleteSync(recursive: true);
}
logStatus('deleting unnecessary js source map files from build');
final deleteMatchers = [
RegExp(r'\.js\.map'),
RegExp(r'\.css\.map'),
RegExp(r'traceconv\.wasm'),
RegExp(r'traceconv_bundle\.js'),
RegExp(r'catapult_trace_viewer\..*'),
RegExp(r'rec_.*\.png'),
];
final libDirectory = Directory(perfettoUiCompiledLibPath);
final libFiles = libDirectory.listSync(recursive: true);
for (final file in libFiles) {
if (deleteMatchers.any((matcher) => matcher.hasMatch(file.path))) {
logStatus('deleting ${file.path}');
file.deleteSync();
}
}
logStatus(
'moving DevTools-Perfetto integration files back from the temp directory',
);
Directory(perfettoDevToolsPath).createSync(recursive: true);
await copyPath(tempPerfettoDevTools.path, perfettoDevToolsPath);
logStatus('deleting temporary directory');
tempPerfettoDevTools.deleteSync(recursive: true);
_updateIndexFileForDevToolsEmbedding(
path.join(perfettoUiCompiledBuildPath, 'index.html'),
);
_updatePerfettoAssetsInPubspec();
}
void _updateIndexFileForDevToolsEmbedding(String indexFilePath) {
logStatus(
'updating index.html headers to include DevTools-Perfetto integration files',
);
final indexFile = File(indexFilePath);
final fileLines = indexFile.readAsLinesSync();
final fileLinesCopy = <String>[];
for (final line in fileLines) {
if (line == '</head>') {
fileLinesCopy.addAll([
' <link id="devtools-style" rel="stylesheet" href="devtools/devtools_dark.css">',
' <script src="devtools/devtools_theme_handler.js"></script>',
]);
}
fileLinesCopy.add(line);
}
indexFile.writeAsStringSync(fileLinesCopy.joinWithNewLine());
}
void _updatePerfettoAssetsInPubspec() {
logStatus('updating perfetto assets in the devtools_app pubspec.yaml file');
final repo = DevToolsRepo.getInstance();
final perfettoDistDir = Directory(
path.join(
repo.repoPath,
'third_party',
'packages',
'perfetto_ui_compiled',
'lib',
'dist',
),
);
// Find the new perfetto version number.
String newVersionNumber = '';
final versionRegExp = RegExp(r'v\d+[.]\d+-[0-9a-fA-F]+');
final entities = perfettoDistDir.listSync();
for (FileSystemEntity entity in entities) {
final path = entity.path;
final match = versionRegExp.firstMatch(path);
if (match != null) {
newVersionNumber = path.split('/').last;
logStatus('new Perfetto version: $newVersionNumber');
break;
}
}
if (newVersionNumber.isEmpty) {
throw Exception(
'Error updating Perfetto assets: could not find Perfetto version number '
'from entities: ${entities.map((e) => e.path).toList()}',
);
}
final pubspec = File(
path.join(repo.devtoolsAppDirectoryPath, 'pubspec.yaml'),
);
// TODO(kenz): Ensure the pubspec.yaml contains an entry for each file in
// [perfettoDistDir].
final perfettoAssetRegExp = RegExp(
r'(?<prefix>^.*packages\/perfetto_ui_compiled\/dist\/)(?<version>v\d+[.]\d+-[0-9a-fA-F]+)(?<suffix>\/.*$)',
);
final lines = pubspec.readAsLinesSync();
for (int i = 0; i < lines.length; i++) {
final line = lines[i];
final match = perfettoAssetRegExp.firstMatch(line);
if (match != null) {
final prefix = match.namedGroup('prefix')!;
final suffix = match.namedGroup('suffix')!;
lines[i] = '$prefix$newVersionNumber$suffix';
}
}
logStatus(
'updating devtools_app/pubspec.yaml for new Perfetto version'
'$newVersionNumber',
);
final pubspecLinesAsString = '${lines.join('\n')}\n';
pubspec.writeAsStringSync(pubspecLinesAsString);
}
}
| devtools/tool/lib/commands/update_perfetto.dart/0 | {
"file_path": "devtools/tool/lib/commands/update_perfetto.dart",
"repo_id": "devtools",
"token_count": 3015
} | 148 |
# Below is a list of people and organizations that have contributed
# to the Sky project. Names should be added to the list like so:
#
# Name/Organization <email address>
Google Inc.
The Chromium Authors
The Fuchsia Authors
Jim Simon <[email protected]>
Ali Bitek <[email protected]>
Jacob Greenfield <[email protected]>
Dan Field <[email protected]>
Victor Choueiri <[email protected]>
Simon Lightfoot <[email protected]>
Dwayne Slater <[email protected]>
Tetsuhiro Ueda <[email protected]>
shoryukenn <[email protected]>
SOTEC GmbH & Co. KG <[email protected]>
Hidenori Matsubayashi <[email protected]>
Sarbagya Dhaubanjar <[email protected]>
Callum Moffat <[email protected]>
Koutaro Mori <[email protected]>
TheOneWithTheBraid <[email protected]>
Twin Sun, LLC <[email protected]>
Qixing Cao <[email protected]>
LinXunFeng <[email protected]>
Amir Panahandeh <[email protected]>
Rulong Chen(陈汝龙)<[email protected]>
| engine/AUTHORS/0 | {
"file_path": "engine/AUTHORS",
"repo_id": "engine",
"token_count": 433
} | 149 |
// 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.
#include "benchmarking.h"
#include "flutter/fml/backtrace.h"
#include "flutter/fml/build_config.h"
#include "flutter/fml/command_line.h"
#include "flutter/fml/icu_util.h"
namespace benchmarking {
int Main(int argc, char** argv) {
fml::InstallCrashHandler();
#if !defined(FML_OS_ANDROID)
fml::CommandLine cmd = fml::CommandLineFromPlatformOrArgcArgv(argc, argv);
std::string icudtl_path =
cmd.GetOptionValueWithDefault("icu-data-file-path", "icudtl.dat");
fml::icu::InitializeICU(icudtl_path);
#endif
benchmark::Initialize(&argc, argv);
::benchmark::RunSpecifiedBenchmarks();
return 0;
}
} // namespace benchmarking
int main(int argc, char** argv) {
return benchmarking::Main(argc, argv);
}
| engine/benchmarking/benchmarking.cc/0 | {
"file_path": "engine/benchmarking/benchmarking.cc",
"repo_id": "engine",
"token_count": 320
} | 150 |
#!/usr/bin/env python3
#
# 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 sys
import subprocess
import os
import argparse
import errno
import shutil
def get_llvm_bin_directory():
buildtool_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../buildtools')
platform_dir = ''
if sys.platform.startswith('linux'):
platform_dir = 'linux-x64'
elif sys.platform == 'darwin':
platform_dir = 'mac-x64'
else:
raise Exception('Unknown/Unsupported platform.')
llvm_bin_dir = os.path.abspath(os.path.join(buildtool_dir, platform_dir, 'clang/bin'))
if not os.path.exists(llvm_bin_dir):
raise Exception('LLVM directory %s double not be located.' % llvm_bin_dir)
return llvm_bin_dir
def make_dirs(new_dir):
"""A wrapper around os.makedirs() that emulates "mkdir -p"."""
try:
os.makedirs(new_dir)
except OSError as err:
if err.errno != errno.EEXIST:
raise
def remove_if_exists(path):
if os.path.isdir(path) and not os.path.islink(path):
shutil.rmtree(path)
elif os.path.exists(path):
os.remove(path)
def collect_profiles(args):
raw_profiles = []
binaries = []
# Run all unit tests and collect raw profiles.
for test in args.tests:
absolute_test_path = os.path.abspath(test)
absolute_test_dir = os.path.dirname(absolute_test_path)
test_name = os.path.basename(absolute_test_path)
if not os.path.exists(absolute_test_path):
print('Path %s does not exist.' % absolute_test_path)
return -1
unstripped_test_path = os.path.join(absolute_test_dir, 'exe.unstripped', test_name)
if os.path.exists(unstripped_test_path):
binaries.append(unstripped_test_path)
else:
binaries.append(absolute_test_path)
raw_profile = absolute_test_path + '.rawprofile'
remove_if_exists(raw_profile)
print('Running test %s to gather profile.' % os.path.basename(absolute_test_path))
test_command = [absolute_test_path]
test_args = ' '.join(args.test_args).split()
if test_args is not None:
test_command += test_args
subprocess.check_call(test_command, env={'LLVM_PROFILE_FILE': raw_profile})
if not os.path.exists(raw_profile):
print('Could not find raw profile data for unit test run %s.' % test)
print('Did you build with the --coverage flag?')
return -1
raw_profiles.append(raw_profile)
return (binaries, raw_profiles)
def merge_profiles(llvm_bin_dir, raw_profiles, output):
# Merge all raw profiles into a single profile.
profdata_binary = os.path.join(llvm_bin_dir, 'llvm-profdata')
print('Merging %d raw profile(s) into single profile.' % len(raw_profiles))
merged_profile_path = os.path.join(output, 'all.profile')
remove_if_exists(merged_profile_path)
merge_command = [profdata_binary, 'merge', '-sparse'] + raw_profiles + ['-o', merged_profile_path]
subprocess.check_call(merge_command)
print('Done.')
return merged_profile_path
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
'-t',
'--tests',
nargs='+',
dest='tests',
required=True,
help='The unit tests to run and gather coverage data on.'
)
parser.add_argument(
'-o',
'--output',
dest='output',
required=True,
help='The output directory for coverage results.'
)
parser.add_argument(
'-f',
'--format',
type=str,
choices=['all', 'html', 'summary', 'lcov'],
required=True,
help='The type of coverage information to be displayed.'
)
parser.add_argument(
'-a',
'--args',
nargs='+',
dest='test_args',
required=False,
help='The arguments to pass to the unit test executable being run.'
)
args = parser.parse_args()
output = os.path.abspath(args.output)
make_dirs(output)
generate_all_reports = args.format == 'all'
binaries, raw_profiles = collect_profiles(args)
if len(raw_profiles) == 0:
print('No raw profiles could be generated.')
return -1
binaries_flag = []
for binary in binaries:
binaries_flag.append('-object')
binaries_flag.append(binary)
llvm_bin_dir = get_llvm_bin_directory()
merged_profile_path = merge_profiles(llvm_bin_dir, raw_profiles, output)
if not os.path.exists(merged_profile_path):
print('Could not generate or find merged profile %s.' % merged_profile_path)
return -1
llvm_cov_binary = os.path.join(llvm_bin_dir, 'llvm-cov')
instr_profile_flag = '-instr-profile=%s' % merged_profile_path
ignore_flags = '-ignore-filename-regex=third_party|unittest|fixture'
# Generate the HTML report if specified.
if generate_all_reports or args.format == 'html':
print('Generating HTML report.')
subprocess.check_call([llvm_cov_binary, 'show'] + binaries_flag + [
instr_profile_flag,
'-format=html',
'-output-dir=%s' % output,
'-tab-size=2',
ignore_flags,
])
print('Done.')
# Generate a report summary if specified.
if generate_all_reports or args.format == 'summary':
print('Generating a summary report.')
subprocess.check_call([llvm_cov_binary, 'report'] + binaries_flag + [
instr_profile_flag,
ignore_flags,
])
print('Done.')
# Generate a lcov summary if specified.
if generate_all_reports or args.format == 'lcov':
print('Generating LCOV report.')
lcov_file = os.path.join(output, 'coverage.lcov')
remove_if_exists(lcov_file)
with open(lcov_file, 'w') as lcov_redirect:
subprocess.check_call([llvm_cov_binary, 'export'] + binaries_flag + [
instr_profile_flag,
ignore_flags,
'-format=lcov',
],
stdout=lcov_redirect)
print('Done.')
return 0
if __name__ == '__main__':
sys.exit(main())
| engine/build/generate_coverage.py/0 | {
"file_path": "engine/build/generate_coverage.py",
"repo_id": "engine",
"token_count": 2318
} | 151 |
# Copyright 2021 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# TODO(flutter/flutter#85356): This file was originally generated by the
# fuchsia.git script: `package_importer.py`. The generated `BUILD.gn` files were
# copied to the flutter repo to support `dart_library` targets used for
# Flutter-Fuchsia integration tests. This file can be maintained by hand, but it
# would be better to implement a script for Flutter, to either generate these
# BUILD.gn files or dynamically generate the GN targets.
import("//flutter/tools/fuchsia/dart/dart_library.gni")
dart_library("args") {
package_name = "args"
language_version = "2.12"
deps = []
sources = [
"args.dart",
"command_runner.dart",
"src/allow_anything_parser.dart",
"src/arg_parser.dart",
"src/arg_parser_exception.dart",
"src/arg_results.dart",
"src/help_command.dart",
"src/option.dart",
"src/parser.dart",
"src/usage.dart",
"src/usage_exception.dart",
"src/utils.dart",
]
}
| engine/build/secondary/third_party/dart/third_party/pkg/args/BUILD.gn/0 | {
"file_path": "engine/build/secondary/third_party/dart/third_party/pkg/args/BUILD.gn",
"repo_id": "engine",
"token_count": 392
} | 152 |
# Copyright 2014 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.
declare_args() {
use_system_libsrtp = false
use_srtp_boringssl = true
}
config("libsrtp_config") {
defines = [
"HAVE_CONFIG_H",
"HAVE_STDLIB_H",
"HAVE_STRING_H",
"TESTAPP_SOURCE",
]
include_dirs = [
"config",
"srtp/include",
"srtp/crypto/include",
]
if (use_srtp_boringssl) {
defines += [ "OPENSSL" ]
}
if (is_posix) {
defines += [
"HAVE_INT16_T",
"HAVE_INT32_T",
"HAVE_INT8_T",
"HAVE_UINT16_T",
"HAVE_UINT32_T",
"HAVE_UINT64_T",
"HAVE_UINT8_T",
"HAVE_STDINT_H",
"HAVE_INTTYPES_H",
"HAVE_NETINET_IN_H",
"HAVE_ARPA_INET_H",
"HAVE_UNISTD_H",
]
cflags = [ "-Wno-unused-variable" ]
}
if (is_win) {
defines += [
"HAVE_BYTESWAP_METHODS_H",
# All Windows architectures are this way.
"SIZEOF_UNSIGNED_LONG=4",
"SIZEOF_UNSIGNED_LONG_LONG=8",
]
}
if (current_cpu == "x64" || current_cpu == "x86" || current_cpu == "arm") {
defines += [
# TODO(leozwang): CPU_RISC doesn"t work properly on android/arm
# platform for unknown reasons, need to investigate the root cause
# of it. CPU_RISC is used for optimization only, and CPU_CISC should
# just work just fine, it has been tested on android/arm with srtp
# test applications and libjingle.
"CPU_CISC",
]
}
}
config("system_libsrtp_config") {
defines = [ "USE_SYSTEM_LIBSRTP" ]
include_dirs = [ "/usr/include/srtp" ]
}
if (use_system_libsrtp) {
group("libsrtp") {
public_configs = [
":libsrtp_config",
":system_libsrtp_config",
]
libs = [ "-lsrtp" ]
}
} else {
static_library("libsrtp") {
configs -= [ "//build/config/compiler:chromium_code" ]
configs += [ "//build/config/compiler:no_chromium_code" ]
public_configs = [ ":libsrtp_config" ]
sources = [
# includes
"srtp/include/ekt.h",
"srtp/include/getopt_s.h",
"srtp/include/rtp.h",
"srtp/include/rtp_priv.h",
"srtp/include/srtp.h",
"srtp/include/srtp_priv.h",
"srtp/include/ut_sim.h",
# headers
"srtp/crypto/include/aes.h",
"srtp/crypto/include/aes_cbc.h",
"srtp/crypto/include/aes_icm.h",
"srtp/crypto/include/alloc.h",
"srtp/crypto/include/auth.h",
"srtp/crypto/include/cipher.h",
"srtp/crypto/include/crypto.h",
"srtp/crypto/include/crypto_kernel.h",
"srtp/crypto/include/crypto_math.h",
"srtp/crypto/include/crypto_types.h",
"srtp/crypto/include/cryptoalg.h",
"srtp/crypto/include/datatypes.h",
"srtp/crypto/include/err.h",
"srtp/crypto/include/gf2_8.h",
"srtp/crypto/include/hmac.h",
"srtp/crypto/include/integers.h",
"srtp/crypto/include/kernel_compat.h",
"srtp/crypto/include/key.h",
"srtp/crypto/include/null_auth.h",
"srtp/crypto/include/null_cipher.h",
"srtp/crypto/include/prng.h",
"srtp/crypto/include/rand_source.h",
"srtp/crypto/include/rdb.h",
"srtp/crypto/include/rdbx.h",
"srtp/crypto/include/sha1.h",
"srtp/crypto/include/stat.h",
"srtp/crypto/include/xfm.h",
# sources
"srtp/crypto/cipher/aes.c",
"srtp/crypto/cipher/aes_cbc.c",
"srtp/crypto/cipher/aes_icm.c",
"srtp/crypto/cipher/cipher.c",
"srtp/crypto/cipher/null_cipher.c",
"srtp/crypto/hash/auth.c",
"srtp/crypto/hash/hmac.c",
"srtp/crypto/hash/null_auth.c",
"srtp/crypto/hash/sha1.c",
"srtp/crypto/kernel/alloc.c",
"srtp/crypto/kernel/crypto_kernel.c",
"srtp/crypto/kernel/err.c",
"srtp/crypto/kernel/key.c",
"srtp/crypto/math/datatypes.c",
"srtp/crypto/math/gf2_8.c",
"srtp/crypto/math/stat.c",
"srtp/crypto/replay/rdb.c",
"srtp/crypto/replay/rdbx.c",
"srtp/crypto/replay/ut_sim.c",
"srtp/crypto/rng/ctr_prng.c",
"srtp/crypto/rng/prng.c",
"srtp/crypto/rng/rand_source.c",
"srtp/srtp/ekt.c",
"srtp/srtp/srtp.c",
]
if (is_clang) {
cflags = [ "-Wno-implicit-function-declaration" ]
}
if (use_srtp_boringssl) {
deps = [ "//flutter/third_party/boringssl:boringssl" ]
public_deps = [ "//flutter/third_party/boringssl:boringssl" ]
sources -= [
"srtp/crypto/cipher/aes_cbc.c",
"srtp/crypto/cipher/aes_icm.c",
"srtp/crypto/hash/hmac.c",
"srtp/crypto/hash/sha1.c",
"srtp/crypto/rng/ctr_prng.c",
"srtp/crypto/rng/prng.c",
]
sources += [
"srtp/crypto/cipher/aes_gcm_ossl.c",
"srtp/crypto/cipher/aes_icm_ossl.c",
"srtp/crypto/hash/hmac_ossl.c",
"srtp/crypto/include/aes_gcm_ossl.h",
"srtp/crypto/include/aes_icm_ossl.h",
]
}
}
# TODO(GYP): A bunch of these tests don't compile (in gyp either). They're
# not very broken, so could probably be made to work if it's useful.
if (!is_win) {
executable("rdbx_driver") {
configs -= [ "//build/config/compiler:chromium_code" ]
configs += [ "//build/config/compiler:no_chromium_code" ]
deps = [ ":libsrtp" ]
sources = [
"srtp/include/getopt_s.h",
"srtp/test/getopt_s.c",
"srtp/test/rdbx_driver.c",
]
}
executable("srtp_driver") {
configs -= [ "//build/config/compiler:chromium_code" ]
configs += [ "//build/config/compiler:no_chromium_code" ]
deps = [ ":libsrtp" ]
sources = [
"srtp/include/getopt_s.h",
"srtp/include/srtp_priv.h",
"srtp/test/getopt_s.c",
"srtp/test/srtp_driver.c",
]
}
executable("roc_driver") {
configs -= [ "//build/config/compiler:chromium_code" ]
configs += [ "//build/config/compiler:no_chromium_code" ]
deps = [ ":libsrtp" ]
sources = [
"srtp/crypto/include/rdbx.h",
"srtp/include/ut_sim.h",
"srtp/test/roc_driver.c",
]
}
executable("replay_driver") {
configs -= [ "//build/config/compiler:chromium_code" ]
configs += [ "//build/config/compiler:no_chromium_code" ]
deps = [ ":libsrtp" ]
sources = [
"srtp/crypto/include/rdbx.h",
"srtp/include/ut_sim.h",
"srtp/test/replay_driver.c",
]
}
executable("rtpw") {
configs -= [ "//build/config/compiler:chromium_code" ]
configs += [ "//build/config/compiler:no_chromium_code" ]
deps = [ ":libsrtp" ]
sources = [
"srtp/crypto/include/datatypes.h",
"srtp/include/getopt_s.h",
"srtp/include/rtp.h",
"srtp/include/srtp.h",
"srtp/test/getopt_s.c",
"srtp/test/rtp.c",
"srtp/test/rtpw.c",
]
if (is_android) {
defines = [ "HAVE_SYS_SOCKET_H" ]
}
if (is_clang) {
cflags = [ "-Wno-implicit-function-declaration" ]
}
}
executable("srtp_test_cipher_driver") {
configs -= [ "//build/config/compiler:chromium_code" ]
configs += [ "//build/config/compiler:no_chromium_code" ]
deps = [ ":libsrtp" ]
sources = [
"srtp/crypto/test/cipher_driver.c",
"srtp/include/getopt_s.h",
"srtp/test/getopt_s.c",
]
}
executable("srtp_test_datatypes_driver") {
configs -= [ "//build/config/compiler:chromium_code" ]
configs += [ "//build/config/compiler:no_chromium_code" ]
deps = [ ":libsrtp" ]
sources = [ "srtp/crypto/test/datatypes_driver.c" ]
}
executable("srtp_test_stat_driver") {
configs -= [ "//build/config/compiler:chromium_code" ]
configs += [ "//build/config/compiler:no_chromium_code" ]
deps = [ ":libsrtp" ]
sources = [ "srtp/crypto/test/stat_driver.c" ]
}
executable("srtp_test_sha1_driver") {
configs -= [ "//build/config/compiler:chromium_code" ]
configs += [ "//build/config/compiler:no_chromium_code" ]
deps = [ ":libsrtp" ]
sources = [ "srtp/crypto/test/sha1_driver.c" ]
}
executable("srtp_test_kernel_driver") {
configs -= [ "//build/config/compiler:chromium_code" ]
configs += [ "//build/config/compiler:no_chromium_code" ]
deps = [ ":libsrtp" ]
sources = [
"srtp/crypto/test/kernel_driver.c",
"srtp/include/getopt_s.h",
"srtp/test/getopt_s.c",
]
}
executable("srtp_test_aes_calc") {
configs -= [ "//build/config/compiler:chromium_code" ]
configs += [ "//build/config/compiler:no_chromium_code" ]
deps = [ ":libsrtp" ]
sources = [ "srtp/crypto/test/aes_calc.c" ]
}
executable("srtp_test_rand_gen") {
configs -= [ "//build/config/compiler:chromium_code" ]
configs += [ "//build/config/compiler:no_chromium_code" ]
deps = [ ":libsrtp" ]
sources = [
"srtp/crypto/test/rand_gen.c",
"srtp/include/getopt_s.h",
"srtp/test/getopt_s.c",
]
}
executable("srtp_test_rand_gen_soak") {
configs -= [ "//build/config/compiler:chromium_code" ]
configs += [ "//build/config/compiler:no_chromium_code" ]
deps = [ ":libsrtp" ]
sources = [
"srtp/crypto/test/rand_gen_soak.c",
"srtp/include/getopt_s.h",
"srtp/test/getopt_s.c",
]
}
executable("srtp_test_env") {
configs -= [ "//build/config/compiler:chromium_code" ]
configs += [ "//build/config/compiler:no_chromium_code" ]
deps = [ ":libsrtp" ]
sources = [ "srtp/crypto/test/env.c" ]
}
group("srtp_runtest") {
deps = [
":rdbx_driver",
":replay_driver",
":roc_driver",
":rtpw",
":srtp_driver",
":srtp_test_aes_calc",
":srtp_test_cipher_driver",
":srtp_test_datatypes_driver",
":srtp_test_env",
":srtp_test_kernel_driver",
":srtp_test_rand_gen",
":srtp_test_rand_gen_soak",
":srtp_test_sha1_driver",
":srtp_test_stat_driver",
]
}
}
}
| engine/build/secondary/third_party/libsrtp/BUILD.gn/0 | {
"file_path": "engine/build/secondary/third_party/libsrtp/BUILD.gn",
"repo_id": "engine",
"token_count": 5398
} | 153 |
#!/bin/bash
#
# 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.
set -e
# Needed because if it is set, cd may print the path it changed to.
unset CDPATH
# On Mac OS, readlink -f doesn't work, so follow_links traverses the path one
# link at a time, and then cds into the link destination and find out where it
# ends up.
#
# The function is enclosed in a subshell to avoid changing the working directory
# of the caller.
function follow_links() (
cd -P "$(dirname -- "$1")"
file="$PWD/$(basename -- "$1")"
while [[ -L "$file" ]]; do
cd -P "$(dirname -- "$file")"
file="$(readlink -- "$file")"
cd -P "$(dirname -- "$file")"
file="$PWD/$(basename -- "$file")"
done
echo "$file"
)
SCRIPT_DIR=$(follow_links "$(dirname -- "${BASH_SOURCE[0]}")")
SRC_DIR="$(cd "$SCRIPT_DIR/../.."; pwd -P)"
FLUTTER_DIR="$SRC_DIR/flutter"
# This shell script takes one optional argument, the path to a dart-sdk/bin
# directory. If not specified, we default to the build output for
# host_debug_unopt.
if [[ $# -eq 0 ]] ; then
DART_BIN="$SRC_DIR/out/host_debug_unopt/dart-sdk/bin"
else
DART_BIN="$1"
fi
DART="$DART_BIN/dart"
if [[ ! -f "$DART" ]]; then
echo "'$DART' not found"
echo ""
echo "To build the Dart SDK, run:"
echo " flutter/tools/gn --unoptimized --runtime-mode=debug"
echo " ninja -C out/host_debug_unopt"
exit 1
fi
echo "Using dart from $DART_BIN"
"$DART" --version
echo ""
"$DART" analyze --suppress-analytics --fatal-infos --fatal-warnings "$FLUTTER_DIR/ci"
"$DART" analyze --suppress-analytics --fatal-infos --fatal-warnings "$FLUTTER_DIR/flutter_frontend_server"
"$DART" analyze --suppress-analytics --fatal-infos --fatal-warnings "$FLUTTER_DIR/impeller/tessellator/dart"
"$DART" analyze --suppress-analytics --fatal-infos --fatal-warnings "$FLUTTER_DIR/lib/gpu"
"$DART" analyze --suppress-analytics --fatal-infos --fatal-warnings "$FLUTTER_DIR/lib/ui"
"$DART" analyze --suppress-analytics --fatal-infos --fatal-warnings "$FLUTTER_DIR/testing"
"$DART" analyze --suppress-analytics --fatal-infos --fatal-warnings "$FLUTTER_DIR/tools"
echo ""
# Check that dart libraries conform.
echo "Checking the integrity of the Web SDK"
(cd "$FLUTTER_DIR/web_sdk"; "$DART" pub --suppress-analytics get)
(cd "$FLUTTER_DIR/web_sdk/web_test_utils"; "$DART" pub --suppress-analytics get)
(cd "$FLUTTER_DIR/web_sdk/web_engine_tester"; "$DART" pub --suppress-analytics get)
"$DART" analyze --suppress-analytics --fatal-infos --fatal-warnings "$FLUTTER_DIR/web_sdk"
WEB_SDK_TEST_FILES="$FLUTTER_DIR/web_sdk/test/*"
for testFile in $WEB_SDK_TEST_FILES
do
echo "Running $testFile"
(cd "$FLUTTER_DIR"; FLUTTER_DIR="$FLUTTER_DIR" "$DART" --disable-dart-dev --enable-asserts $testFile)
done
| engine/ci/analyze.sh/0 | {
"file_path": "engine/ci/analyze.sh",
"repo_id": "engine",
"token_count": 1092
} | 154 |
{
"builds": [
{
"drone_dimensions": [
"device_type=none",
"os=Linux",
"cores=32"
],
"gclient_variables": {
"use_rbe": true
},
"gn": [
"--runtime-mode",
"debug",
"--unoptimized",
"--prebuilt-dart-sdk",
"--asan",
"--lsan",
"--dart-debug",
"--rbe",
"--no-goma"
],
"name": "host_debug_unopt",
"ninja": {
"config": "host_debug_unopt",
"targets": [
"flutter/tools/font_subset",
"flutter:unittests",
"flutter/build/dart:copy_dart_sdk",
"flutter/shell/platform/common/client_wrapper:client_wrapper_unittests",
"flutter/shell/platform/common:common_cpp_core_unittests",
"flutter/shell/platform/common:common_cpp_unittests",
"flutter/shell/platform/glfw/client_wrapper:client_wrapper_glfw_unittests",
"flutter/shell/testing",
"sky_engine"
]
},
"tests": [
{
"name": "test: Check formatting",
"script": "flutter/bin/et",
"parameters": [
"format",
"--dry-run",
"--all"
]
},
{
"name": "ban GeneratedPluginRegistrant.java",
"script": "flutter/ci/ban_generated_plugin_registrant_java.sh"
},
{
"name": "ban_test GeneratedPluginRegistrant.java",
"script": "flutter/ci/test/ban_generated_plugin_registrant_java_test.sh"
},
{
"language": "python3",
"name": "test: Host_Tests_for_host_debug_unopt",
"script": "flutter/testing/run_tests.py",
"parameters": [
"--quiet",
"--logs-dir",
"${FLUTTER_LOGS_DIR}",
"--variant",
"host_debug_unopt",
"--type",
"dart,dart-host,engine",
"--engine-capture-core-dump",
"--use-sanitizer-suppressions"
]
},
{
"name": "analyze_dart_ui",
"script": "flutter/ci/analyze.sh"
},
{
"name": "pylint",
"script": "flutter/ci/pylint.sh"
},
{
"language": "dart",
"name": "test: observatory and service protocol",
"script": "flutter/shell/testing/observatory/test.dart",
"parameters": [
"out/host_debug_unopt/flutter_tester",
"flutter/shell/testing/observatory/empty_main.dart"
]
},
{
"language": "dart",
"name": "test: Lint android host",
"script": "flutter/tools/android_lint/bin/main.dart"
},
{
"name": "Check build configs",
"script": "flutter/ci/check_build_configs.sh"
},
{
"name": "Tests of tools/gn",
"language": "python3",
"script": "flutter/tools/gn_test.py"
}
]
},
{
"archives": [],
"drone_dimensions": [
"device_type=none",
"os=Linux",
"cores=32"
],
"gclient_variables": {
"download_android_deps": false,
"use_rbe": true
},
"gn": [
"--runtime-mode",
"debug",
"--unoptimized",
"--prebuilt-dart-sdk",
"--target-dir",
"host_debug_unopt_impeller_tests",
"--rbe",
"--no-goma",
"--use-glfw-swiftshader"
],
"name": "host_debug_unopt_impeller_tests",
"ninja": {
"config": "host_debug_unopt_impeller_tests",
"targets": [
"flutter",
"flutter/sky/packages"
]
},
"tests": [
{
"language": "python3",
"name": "Host Tests for host_debug_unopt_impeller_tests",
"script": "flutter/testing/run_tests.py",
"parameters": [
"--variant",
"host_debug_unopt_impeller_tests",
"--type",
"impeller",
"--engine-capture-core-dump"
]
}
]
},
{
"cas_archive": false,
"drone_dimensions": [
"device_type=none",
"os=Linux"
],
"dependencies": [],
"gclient_variables": {
"use_rbe": true
},
"gn": [
"--android",
"--embedder-for-target",
"--target-dir",
"android_embedder_debug_unopt",
"--unoptimized",
"--rbe",
"--no-goma"
],
"name": "android_embedder_debug_unopt",
"ninja": {
"config": "android_embedder_debug_unopt",
"targets": [
"flutter/shell/platform/embedder:flutter_engine"
]
}
},
{
"cas_archive": false,
"drone_dimensions": [
"device_type=none",
"os=Linux"
],
"gclient_variables": {
"use_rbe": true
},
"gn": [
"--android",
"--android-cpu=arm64",
"--no-lto",
"--enable-vulkan-validation-layers",
"--rbe",
"--no-goma"
],
"name": "android_debug_arm64_validation_layers",
"ninja": {
"config": "android_debug_arm64",
"targets": [
"flutter",
"flutter/shell/platform/android:abi_jars"
]
}
},
{
"drone_dimensions": [
"device_type=none",
"os=Linux"
],
"dependencies": [
{
"dependency": "arm_tools",
"version": "last_updated:2023-02-03T15:32:01-0800"
}
],
"gclient_variables": {
"use_rbe": true
},
"gn": [
"--android",
"--unoptimized",
"--rbe",
"--no-goma"
],
"name": "android_debug_unopt",
"ninja": {
"config": "android_debug_unopt",
"targets": [
"flutter/impeller",
"flutter/shell/platform/android:android_jar",
"flutter/shell/platform/android:robolectric_tests"
]
},
"tests": [
{
"language": "python3",
"name": "test: Host Tests for android_debug_unopt",
"script": "flutter/testing/run_tests.py",
"parameters": [
"--variant",
"android_debug_unopt",
"--type",
"java",
"--engine-capture-core-dump",
"--android-variant",
"android_debug_unopt"
]
},
{
"language": "python3",
"name": "malioc diff",
"script": "flutter/impeller/tools/malioc_diff.py",
"parameters": [
"--before-relative-to-src",
"flutter/impeller/tools/malioc.json",
"--after-relative-to-src",
"out/android_debug_unopt/gen/malioc",
"--print-diff"
]
}
]
}
]
}
| engine/ci/builders/linux_unopt.json/0 | {
"file_path": "engine/ci/builders/linux_unopt.json",
"repo_id": "engine",
"token_count": 6101
} | 155 |
#!/bin/bash
#
# 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.
set -e
# Needed because if it is set, cd may print the path it changed to.
unset CDPATH
# On Mac OS, readlink -f doesn't work, so follow_links traverses the path one
# link at a time, and then cds into the link destination and find out where it
# ends up.
#
# The function is enclosed in a subshell to avoid changing the working directory
# of the caller.
function follow_links() (
cd -P "$(dirname -- "$1")"
file="$PWD/$(basename -- "$1")"
while [[ -h "$file" ]]; do
cd -P "$(dirname -- "$file")"
file="$(readlink -- "$file")"
cd -P "$(dirname -- "$file")"
file="$PWD/$(basename -- "$file")"
done
echo "$file"
)
function dart_bin() {
dart_path="$1/flutter/third_party/dart/tools/sdks/dart-sdk/bin"
if [[ ! -e "$dart_path" ]]; then
dart_path="$1/third_party/dart/tools/sdks/dart-sdk/bin"
fi
echo "$dart_path"
}
SCRIPT_DIR=$(follow_links "$(dirname -- "${BASH_SOURCE[0]}")")
SRC_DIR="$(cd "$SCRIPT_DIR/../.."; pwd -P)"
FLUTTER_DIR="$(cd "$SCRIPT_DIR/.."; pwd -P)"
DART_BIN=$(dart_bin "$SRC_DIR")
DART="${DART_BIN}/dart"
# FLUTTER_LINT_PRINT_FIX will make it so that fix is executed and the generated
# diff is printed to stdout if clang-tidy fails. This is helpful for enabling
# new lints.
# To run on CI, just uncomment the following line:
# FLUTTER_LINT_PRINT_FIX=1
if [[ -z "${FLUTTER_LINT_PRINT_FIX}" ]]; then
fix_flag=""
else
fix_flag="--fix --lint-all"
fi
# Determine wether to use x64 or arm64.
if command -v arch &> /dev/null && [[ $(arch) == "arm64" ]]; then
CLANG_TIDY_PATH="buildtools/mac-arm64/clang/bin/clang-tidy"
fi
COMPILE_COMMANDS="$SRC_DIR/out/host_debug/compile_commands.json"
if [ ! -f "$COMPILE_COMMANDS" ]; then
(cd "$SRC_DIR"; ./flutter/tools/gn)
fi
echo "$(date +%T) Running clang_tidy"
cd "$SCRIPT_DIR"
"$DART" \
--disable-dart-dev \
"$SRC_DIR/flutter/tools/clang_tidy/bin/main.dart" \
--src-dir="$SRC_DIR" \
${CLANG_TIDY_PATH:+--clang-tidy="$SRC_DIR/$CLANG_TIDY_PATH"} \
$fix_flag \
"$@" && true # errors ignored
clang_tidy_return=$?
if [ $clang_tidy_return -ne 0 ]; then
if [ -n "$fix_flag" ]; then
echo "###################################################"
echo "# Attempted to fix issues with the following patch:"
echo "###################################################"
git --no-pager diff
fi
exit $clang_tidy_return
fi
| engine/ci/clang_tidy.sh/0 | {
"file_path": "engine/ci/clang_tidy.sh",
"repo_id": "engine",
"token_count": 992
} | 156 |
#!/bin/bash
#
# 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.
set -e
# Needed because if it is set, cd may print the path it changed to.
unset CDPATH
# On Mac OS, readlink -f doesn't work, so follow_links traverses the path one
# link at a time, and then cds into the link destination and find out where it
# ends up.
#
# The function is enclosed in a subshell to avoid changing the working directory
# of the caller.
function follow_links() (
cd -P "$(dirname -- "$1")"
file="$PWD/$(basename -- "$1")"
while [[ -h "$file" ]]; do
cd -P "$(dirname -- "$file")"
file="$(readlink -- "$file")"
cd -P "$(dirname -- "$file")"
file="$PWD/$(basename -- "$file")"
done
echo "$file"
)
SCRIPT_DIR=$(follow_links "$(dirname -- "${BASH_SOURCE[0]}")")
FLUTTER_DIR="$(cd "$SCRIPT_DIR/.."; pwd -P)"
echo "$(date +%T) Running pylint"
cd "$FLUTTER_DIR"
pylint-2.7 --rcfile=.pylintrc \
"ci/" \
"impeller/" \
"sky/" \
"tools/gn" \
"tools/pub_get_offline.py" \
"testing/"
echo "$(date +%T) Linting complete"
| engine/ci/pylint.sh/0 | {
"file_path": "engine/ci/pylint.sh",
"repo_id": "engine",
"token_count": 434
} | 157 |
// 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.
#ifndef FLUTTER_COMMON_GRAPHICS_MSAA_SAMPLE_COUNT_H_
#define FLUTTER_COMMON_GRAPHICS_MSAA_SAMPLE_COUNT_H_
// Supported MSAA sample count values.
enum class MsaaSampleCount {
kNone = 1,
kTwo = 2,
kFour = 4,
kEight = 8,
kSixteen = 16,
};
#endif // FLUTTER_COMMON_GRAPHICS_MSAA_SAMPLE_COUNT_H_
| engine/common/graphics/msaa_sample_count.h/0 | {
"file_path": "engine/common/graphics/msaa_sample_count.h",
"repo_id": "engine",
"token_count": 178
} | 158 |
// 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.
#ifndef FLUTTER_DISPLAY_LIST_BENCHMARKING_DL_COMPLEXITY_GL_H_
#define FLUTTER_DISPLAY_LIST_BENCHMARKING_DL_COMPLEXITY_GL_H_
#include "flutter/display_list/benchmarking/dl_complexity_helper.h"
namespace flutter {
class DisplayListGLComplexityCalculator
: public DisplayListComplexityCalculator {
public:
static DisplayListGLComplexityCalculator* GetInstance();
unsigned int Compute(const DisplayList* display_list) override {
GLHelper helper(ceiling_);
display_list->Dispatch(helper);
return helper.ComplexityScore();
}
bool ShouldBeCached(unsigned int complexity_score) override {
// Set cache threshold at 1ms
return complexity_score > 200000u;
}
void SetComplexityCeiling(unsigned int ceiling) override {
ceiling_ = ceiling;
}
private:
class GLHelper : public ComplexityCalculatorHelper {
public:
explicit GLHelper(unsigned int ceiling)
: ComplexityCalculatorHelper(ceiling) {}
void saveLayer(const SkRect& bounds,
const SaveLayerOptions options,
const DlImageFilter* backdrop) override;
void drawLine(const SkPoint& p0, const SkPoint& p1) override;
void drawRect(const SkRect& rect) override;
void drawOval(const SkRect& bounds) override;
void drawCircle(const SkPoint& center, SkScalar radius) override;
void drawRRect(const SkRRect& rrect) override;
void drawDRRect(const SkRRect& outer, const SkRRect& inner) override;
void drawPath(const SkPath& path) override;
void drawArc(const SkRect& oval_bounds,
SkScalar start_degrees,
SkScalar sweep_degrees,
bool use_center) override;
void drawPoints(DlCanvas::PointMode mode,
uint32_t count,
const SkPoint points[]) override;
void drawVertices(const DlVertices* vertices, DlBlendMode mode) override;
void drawImage(const sk_sp<DlImage> image,
const SkPoint point,
DlImageSampling sampling,
bool render_with_attributes) override;
void drawImageNine(const sk_sp<DlImage> image,
const SkIRect& center,
const SkRect& dst,
DlFilterMode filter,
bool render_with_attributes) override;
void drawDisplayList(const sk_sp<DisplayList> display_list,
SkScalar opacity) override;
void drawTextBlob(const sk_sp<SkTextBlob> blob,
SkScalar x,
SkScalar y) override;
void drawTextFrame(const std::shared_ptr<impeller::TextFrame>& text_frame,
SkScalar x,
SkScalar y) override;
void drawShadow(const SkPath& path,
const DlColor color,
const SkScalar elevation,
bool transparent_occluder,
SkScalar dpr) override;
protected:
void ImageRect(const SkISize& size,
bool texture_backed,
bool render_with_attributes,
bool enforce_src_edges) override;
unsigned int BatchedComplexity() override;
private:
unsigned int save_layer_count_ = 0;
unsigned int draw_text_blob_count_ = 0;
};
DisplayListGLComplexityCalculator()
: ceiling_(std::numeric_limits<unsigned int>::max()) {}
static DisplayListGLComplexityCalculator* instance_;
unsigned int ceiling_;
};
} // namespace flutter
#endif // FLUTTER_DISPLAY_LIST_BENCHMARKING_DL_COMPLEXITY_GL_H_
| engine/display_list/benchmarking/dl_complexity_gl.h/0 | {
"file_path": "engine/display_list/benchmarking/dl_complexity_gl.h",
"repo_id": "engine",
"token_count": 1602
} | 159 |
// 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.
#ifndef FLUTTER_DISPLAY_LIST_DL_CANVAS_H_
#define FLUTTER_DISPLAY_LIST_DL_CANVAS_H_
#include "flutter/display_list/dl_blend_mode.h"
#include "flutter/display_list/dl_paint.h"
#include "flutter/display_list/dl_vertices.h"
#include "flutter/display_list/image/dl_image.h"
#include "third_party/skia/include/core/SkM44.h"
#include "third_party/skia/include/core/SkMatrix.h"
#include "third_party/skia/include/core/SkPath.h"
#include "third_party/skia/include/core/SkRRect.h"
#include "third_party/skia/include/core/SkRSXform.h"
#include "third_party/skia/include/core/SkRect.h"
#include "third_party/skia/include/core/SkTextBlob.h"
#include "impeller/typographer/text_frame.h"
namespace flutter {
//------------------------------------------------------------------------------
/// @brief Developer-facing API for rendering anything *within* the engine.
///
/// |DlCanvas| should be used to render anything in the framework classes (i.e.
/// `lib/ui`), flow and flow layers, embedders, shell, and elsewhere.
///
/// The only state carried by implementations of this interface are the clip
/// and transform which are saved and restored by the |save|, |saveLayer|, and
/// |restore| calls.
///
/// @note The interface resembles closely the familiar |SkCanvas| interface
/// used throughout the engine.
class DlCanvas {
public:
enum class ClipOp {
kDifference,
kIntersect,
};
enum class PointMode {
kPoints, //!< draw each point separately
kLines, //!< draw each separate pair of points as a line segment
kPolygon, //!< draw each pair of overlapping points as a line segment
};
enum class SrcRectConstraint {
kStrict,
kFast,
};
virtual ~DlCanvas() = default;
virtual SkISize GetBaseLayerSize() const = 0;
virtual SkImageInfo GetImageInfo() const = 0;
virtual void Save() = 0;
virtual void SaveLayer(const SkRect* bounds,
const DlPaint* paint = nullptr,
const DlImageFilter* backdrop = nullptr) = 0;
virtual void Restore() = 0;
virtual int GetSaveCount() const = 0;
virtual void RestoreToCount(int restore_count) = 0;
virtual void Translate(SkScalar tx, SkScalar ty) = 0;
virtual void Scale(SkScalar sx, SkScalar sy) = 0;
virtual void Rotate(SkScalar degrees) = 0;
virtual void Skew(SkScalar sx, SkScalar sy) = 0;
// clang-format off
// 2x3 2D affine subset of a 4x4 transform in row major order
virtual void Transform2DAffine(SkScalar mxx, SkScalar mxy, SkScalar mxt,
SkScalar myx, SkScalar myy, SkScalar myt) = 0;
// full 4x4 transform in row major order
virtual void TransformFullPerspective(
SkScalar mxx, SkScalar mxy, SkScalar mxz, SkScalar mxt,
SkScalar myx, SkScalar myy, SkScalar myz, SkScalar myt,
SkScalar mzx, SkScalar mzy, SkScalar mzz, SkScalar mzt,
SkScalar mwx, SkScalar mwy, SkScalar mwz, SkScalar mwt) = 0;
// clang-format on
virtual void TransformReset() = 0;
virtual void Transform(const SkMatrix* matrix) = 0;
virtual void Transform(const SkM44* matrix44) = 0;
void Transform(const SkMatrix& matrix) { Transform(&matrix); }
void Transform(const SkM44& matrix44) { Transform(&matrix44); }
virtual void SetTransform(const SkMatrix* matrix) = 0;
virtual void SetTransform(const SkM44* matrix44) = 0;
virtual void SetTransform(const SkMatrix& matrix) { SetTransform(&matrix); }
virtual void SetTransform(const SkM44& matrix44) { SetTransform(&matrix44); }
/// Returns the 4x4 full perspective transform representing all transform
/// operations executed so far in this DisplayList within the enclosing
/// save stack.
virtual SkM44 GetTransformFullPerspective() const = 0;
/// Returns the 3x3 partial perspective transform representing all transform
/// operations executed so far in this DisplayList within the enclosing
/// save stack.
virtual SkMatrix GetTransform() const = 0;
virtual void ClipRect(const SkRect& rect,
ClipOp clip_op = ClipOp::kIntersect,
bool is_aa = false) = 0;
virtual void ClipRRect(const SkRRect& rrect,
ClipOp clip_op = ClipOp::kIntersect,
bool is_aa = false) = 0;
virtual void ClipPath(const SkPath& path,
ClipOp clip_op = ClipOp::kIntersect,
bool is_aa = false) = 0;
/// Conservative estimate of the bounds of all outstanding clip operations
/// measured in the coordinate space within which this DisplayList will
/// be rendered.
virtual SkRect GetDestinationClipBounds() const = 0;
/// Conservative estimate of the bounds of all outstanding clip operations
/// transformed into the local coordinate space in which currently
/// recorded rendering operations are interpreted.
virtual SkRect GetLocalClipBounds() const = 0;
/// Return true iff the supplied bounds are easily shown to be outside
/// of the current clip bounds. This method may conservatively return
/// false if it cannot make the determination.
virtual bool QuickReject(const SkRect& bounds) const = 0;
virtual void DrawPaint(const DlPaint& paint) = 0;
virtual void DrawColor(DlColor color,
DlBlendMode mode = DlBlendMode::kSrcOver) = 0;
void Clear(DlColor color) { DrawColor(color, DlBlendMode::kSrc); }
virtual void DrawLine(const SkPoint& p0,
const SkPoint& p1,
const DlPaint& paint) = 0;
virtual void DrawRect(const SkRect& rect, const DlPaint& paint) = 0;
virtual void DrawOval(const SkRect& bounds, const DlPaint& paint) = 0;
virtual void DrawCircle(const SkPoint& center,
SkScalar radius,
const DlPaint& paint) = 0;
virtual void DrawRRect(const SkRRect& rrect, const DlPaint& paint) = 0;
virtual void DrawDRRect(const SkRRect& outer,
const SkRRect& inner,
const DlPaint& paint) = 0;
virtual void DrawPath(const SkPath& path, const DlPaint& paint) = 0;
virtual void DrawArc(const SkRect& bounds,
SkScalar start,
SkScalar sweep,
bool useCenter,
const DlPaint& paint) = 0;
virtual void DrawPoints(PointMode mode,
uint32_t count,
const SkPoint pts[],
const DlPaint& paint) = 0;
virtual void DrawVertices(const DlVertices* vertices,
DlBlendMode mode,
const DlPaint& paint) = 0;
void DrawVertices(const std::shared_ptr<const DlVertices>& vertices,
DlBlendMode mode,
const DlPaint& paint) {
DrawVertices(vertices.get(), mode, paint);
}
virtual void DrawImage(const sk_sp<DlImage>& image,
const SkPoint point,
DlImageSampling sampling,
const DlPaint* paint = nullptr) = 0;
virtual void DrawImageRect(
const sk_sp<DlImage>& image,
const SkRect& src,
const SkRect& dst,
DlImageSampling sampling,
const DlPaint* paint = nullptr,
SrcRectConstraint constraint = SrcRectConstraint::kFast) = 0;
virtual void DrawImageRect(
const sk_sp<DlImage>& image,
const SkIRect& src,
const SkRect& dst,
DlImageSampling sampling,
const DlPaint* paint = nullptr,
SrcRectConstraint constraint = SrcRectConstraint::kFast) {
DrawImageRect(image, SkRect::Make(src), dst, sampling, paint, constraint);
}
void DrawImageRect(const sk_sp<DlImage>& image,
const SkRect& dst,
DlImageSampling sampling,
const DlPaint* paint = nullptr,
SrcRectConstraint constraint = SrcRectConstraint::kFast) {
DrawImageRect(image, image->bounds(), dst, sampling, paint, constraint);
}
virtual void DrawImageNine(const sk_sp<DlImage>& image,
const SkIRect& center,
const SkRect& dst,
DlFilterMode filter,
const DlPaint* paint = nullptr) = 0;
virtual void DrawAtlas(const sk_sp<DlImage>& atlas,
const SkRSXform xform[],
const SkRect tex[],
const DlColor colors[],
int count,
DlBlendMode mode,
DlImageSampling sampling,
const SkRect* cullRect,
const DlPaint* paint = nullptr) = 0;
virtual void DrawDisplayList(const sk_sp<DisplayList> display_list,
SkScalar opacity = SK_Scalar1) = 0;
virtual void DrawTextFrame(
const std::shared_ptr<impeller::TextFrame>& text_frame,
SkScalar x,
SkScalar y,
const DlPaint& paint) = 0;
virtual void DrawTextBlob(const sk_sp<SkTextBlob>& blob,
SkScalar x,
SkScalar y,
const DlPaint& paint) = 0;
virtual void DrawShadow(const SkPath& path,
const DlColor color,
const SkScalar elevation,
bool transparent_occluder,
SkScalar dpr) = 0;
virtual void Flush() = 0;
static constexpr SkScalar kShadowLightHeight = 600;
static constexpr SkScalar kShadowLightRadius = 800;
static SkRect ComputeShadowBounds(const SkPath& path,
float elevation,
SkScalar dpr,
const SkMatrix& ctm);
};
class DlAutoCanvasRestore {
public:
DlAutoCanvasRestore(DlCanvas* canvas, bool do_save) : canvas_(canvas) {
if (canvas) {
canvas_ = canvas;
restore_count_ = canvas->GetSaveCount();
if (do_save) {
canvas_->Save();
}
} else {
canvas_ = nullptr;
restore_count_ = 0;
}
}
~DlAutoCanvasRestore() { Restore(); }
void Restore() {
if (canvas_) {
canvas_->RestoreToCount(restore_count_);
canvas_ = nullptr;
}
}
private:
DlCanvas* canvas_;
int restore_count_;
FML_DISALLOW_COPY_ASSIGN_AND_MOVE(DlAutoCanvasRestore);
};
} // namespace flutter
#endif // FLUTTER_DISPLAY_LIST_DL_CANVAS_H_
| engine/display_list/dl_canvas.h/0 | {
"file_path": "engine/display_list/dl_canvas.h",
"repo_id": "engine",
"token_count": 4634
} | 160 |
// 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.
#include "flutter/display_list/dl_builder.h"
#include "flutter/display_list/dl_vertices.h"
#include "flutter/display_list/testing/dl_test_equality.h"
#include "flutter/display_list/utils/dl_comparable.h"
#include "gtest/gtest.h"
namespace flutter {
namespace testing {
TEST(DisplayListVertices, MakeWithZeroAndNegativeVerticesAndIndices) {
std::shared_ptr<const DlVertices> vertices1 = DlVertices::Make(
DlVertexMode::kTriangles, 0, nullptr, nullptr, nullptr, 0, nullptr);
EXPECT_NE(vertices1, nullptr);
EXPECT_EQ(vertices1->vertex_count(), 0);
EXPECT_EQ(vertices1->vertices(), nullptr);
EXPECT_EQ(vertices1->texture_coordinates(), nullptr);
EXPECT_EQ(vertices1->colors(), nullptr);
EXPECT_EQ(vertices1->index_count(), 0);
EXPECT_EQ(vertices1->indices(), nullptr);
std::shared_ptr<const DlVertices> vertices2 = DlVertices::Make(
DlVertexMode::kTriangles, -1, nullptr, nullptr, nullptr, -1, nullptr);
EXPECT_NE(vertices2, nullptr);
EXPECT_EQ(vertices2->vertex_count(), 0);
EXPECT_EQ(vertices2->vertices(), nullptr);
EXPECT_EQ(vertices2->texture_coordinates(), nullptr);
EXPECT_EQ(vertices2->colors(), nullptr);
EXPECT_EQ(vertices2->index_count(), 0);
EXPECT_EQ(vertices2->indices(), nullptr);
TestEquals(*vertices1, *vertices2);
}
TEST(DisplayListVertices, MakeWithTexAndColorAndIndices) {
SkPoint coords[3] = {
SkPoint::Make(2, 3),
SkPoint::Make(5, 6),
SkPoint::Make(15, 20),
};
SkPoint texture_coords[3] = {
SkPoint::Make(102, 103),
SkPoint::Make(105, 106),
SkPoint::Make(115, 120),
};
DlColor colors[3] = {
DlColor::kRed(),
DlColor::kCyan(),
DlColor::kGreen(),
};
uint16_t indices[6] = {
2, 1, 0, //
1, 2, 0,
};
std::shared_ptr<const DlVertices> vertices = DlVertices::Make(
DlVertexMode::kTriangles, 3, coords, texture_coords, colors, 6, indices);
ASSERT_NE(vertices, nullptr);
ASSERT_NE(vertices->vertices(), nullptr);
ASSERT_NE(vertices->texture_coordinates(), nullptr);
ASSERT_NE(vertices->colors(), nullptr);
ASSERT_NE(vertices->indices(), nullptr);
ASSERT_EQ(vertices->bounds(), SkRect::MakeLTRB(2, 3, 15, 20));
ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles);
ASSERT_EQ(vertices->vertex_count(), 3);
for (int i = 0; i < 3; i++) {
ASSERT_EQ(vertices->vertices()[i], coords[i]);
ASSERT_EQ(vertices->texture_coordinates()[i], texture_coords[i]);
ASSERT_EQ(vertices->colors()[i], colors[i]);
}
ASSERT_EQ(vertices->index_count(), 6);
for (int i = 0; i < 6; i++) {
ASSERT_EQ(vertices->indices()[i], indices[i]);
}
}
TEST(DisplayListVertices, MakeWithTexAndColor) {
SkPoint coords[3] = {
SkPoint::Make(2, 3),
SkPoint::Make(5, 6),
SkPoint::Make(15, 20),
};
SkPoint texture_coords[3] = {
SkPoint::Make(102, 103),
SkPoint::Make(105, 106),
SkPoint::Make(115, 120),
};
DlColor colors[3] = {
DlColor::kRed(),
DlColor::kCyan(),
DlColor::kGreen(),
};
std::shared_ptr<const DlVertices> vertices = DlVertices::Make(
DlVertexMode::kTriangles, 3, coords, texture_coords, colors, 6, nullptr);
ASSERT_NE(vertices, nullptr);
ASSERT_NE(vertices->vertices(), nullptr);
ASSERT_NE(vertices->texture_coordinates(), nullptr);
ASSERT_NE(vertices->colors(), nullptr);
ASSERT_EQ(vertices->indices(), nullptr);
ASSERT_EQ(vertices->bounds(), SkRect::MakeLTRB(2, 3, 15, 20));
ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles);
ASSERT_EQ(vertices->vertex_count(), 3);
for (int i = 0; i < 3; i++) {
ASSERT_EQ(vertices->vertices()[i], coords[i]);
ASSERT_EQ(vertices->texture_coordinates()[i], texture_coords[i]);
ASSERT_EQ(vertices->colors()[i], colors[i]);
}
ASSERT_EQ(vertices->index_count(), 0);
}
TEST(DisplayListVertices, MakeWithTexAndIndices) {
SkPoint coords[3] = {
SkPoint::Make(2, 3),
SkPoint::Make(5, 6),
SkPoint::Make(15, 20),
};
SkPoint texture_coords[3] = {
SkPoint::Make(102, 103),
SkPoint::Make(105, 106),
SkPoint::Make(115, 120),
};
uint16_t indices[6] = {
2, 1, 0, //
1, 2, 0,
};
std::shared_ptr<const DlVertices> vertices = DlVertices::Make(
DlVertexMode::kTriangles, 3, coords, texture_coords, nullptr, 6, indices);
ASSERT_NE(vertices, nullptr);
ASSERT_NE(vertices->vertices(), nullptr);
ASSERT_NE(vertices->texture_coordinates(), nullptr);
ASSERT_EQ(vertices->colors(), nullptr);
ASSERT_NE(vertices->indices(), nullptr);
ASSERT_EQ(vertices->bounds(), SkRect::MakeLTRB(2, 3, 15, 20));
ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles);
ASSERT_EQ(vertices->vertex_count(), 3);
for (int i = 0; i < 3; i++) {
ASSERT_EQ(vertices->vertices()[i], coords[i]);
ASSERT_EQ(vertices->texture_coordinates()[i], texture_coords[i]);
}
ASSERT_EQ(vertices->index_count(), 6);
for (int i = 0; i < 6; i++) {
ASSERT_EQ(vertices->indices()[i], indices[i]);
}
}
TEST(DisplayListVertices, MakeWithColorAndIndices) {
SkPoint coords[3] = {
SkPoint::Make(2, 3),
SkPoint::Make(5, 6),
SkPoint::Make(15, 20),
};
DlColor colors[3] = {
DlColor::kRed(),
DlColor::kCyan(),
DlColor::kGreen(),
};
uint16_t indices[6] = {
2, 1, 0, //
1, 2, 0,
};
std::shared_ptr<const DlVertices> vertices = DlVertices::Make(
DlVertexMode::kTriangles, 3, coords, nullptr, colors, 6, indices);
ASSERT_NE(vertices, nullptr);
ASSERT_NE(vertices->vertices(), nullptr);
ASSERT_EQ(vertices->texture_coordinates(), nullptr);
ASSERT_NE(vertices->colors(), nullptr);
ASSERT_NE(vertices->indices(), nullptr);
ASSERT_EQ(vertices->bounds(), SkRect::MakeLTRB(2, 3, 15, 20));
ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles);
ASSERT_EQ(vertices->vertex_count(), 3);
for (int i = 0; i < 3; i++) {
ASSERT_EQ(vertices->vertices()[i], coords[i]);
ASSERT_EQ(vertices->colors()[i], colors[i]);
}
ASSERT_EQ(vertices->index_count(), 6);
for (int i = 0; i < 6; i++) {
ASSERT_EQ(vertices->indices()[i], indices[i]);
}
}
TEST(DisplayListVertices, MakeWithTex) {
SkPoint coords[3] = {
SkPoint::Make(2, 3),
SkPoint::Make(5, 6),
SkPoint::Make(15, 20),
};
SkPoint texture_coords[3] = {
SkPoint::Make(102, 103),
SkPoint::Make(105, 106),
SkPoint::Make(115, 120),
};
std::shared_ptr<const DlVertices> vertices = DlVertices::Make(
DlVertexMode::kTriangles, 3, coords, texture_coords, nullptr, 6, nullptr);
ASSERT_NE(vertices, nullptr);
ASSERT_NE(vertices->vertices(), nullptr);
ASSERT_NE(vertices->texture_coordinates(), nullptr);
ASSERT_EQ(vertices->colors(), nullptr);
ASSERT_EQ(vertices->indices(), nullptr);
ASSERT_EQ(vertices->bounds(), SkRect::MakeLTRB(2, 3, 15, 20));
ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles);
ASSERT_EQ(vertices->vertex_count(), 3);
for (int i = 0; i < 3; i++) {
ASSERT_EQ(vertices->vertices()[i], coords[i]);
ASSERT_EQ(vertices->texture_coordinates()[i], texture_coords[i]);
}
ASSERT_EQ(vertices->index_count(), 0);
}
TEST(DisplayListVertices, MakeWithColor) {
SkPoint coords[3] = {
SkPoint::Make(2, 3),
SkPoint::Make(5, 6),
SkPoint::Make(15, 20),
};
DlColor colors[3] = {
DlColor::kRed(),
DlColor::kCyan(),
DlColor::kGreen(),
};
std::shared_ptr<const DlVertices> vertices = DlVertices::Make(
DlVertexMode::kTriangles, 3, coords, nullptr, colors, 6, nullptr);
ASSERT_NE(vertices, nullptr);
ASSERT_NE(vertices->vertices(), nullptr);
ASSERT_EQ(vertices->texture_coordinates(), nullptr);
ASSERT_NE(vertices->colors(), nullptr);
ASSERT_EQ(vertices->indices(), nullptr);
ASSERT_EQ(vertices->bounds(), SkRect::MakeLTRB(2, 3, 15, 20));
ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles);
ASSERT_EQ(vertices->vertex_count(), 3);
for (int i = 0; i < 3; i++) {
ASSERT_EQ(vertices->vertices()[i], coords[i]);
ASSERT_EQ(vertices->colors()[i], colors[i]);
}
ASSERT_EQ(vertices->index_count(), 0);
}
TEST(DisplayListVertices, MakeWithIndices) {
SkPoint coords[3] = {
SkPoint::Make(2, 3),
SkPoint::Make(5, 6),
SkPoint::Make(15, 20),
};
uint16_t indices[6] = {
2, 1, 0, //
1, 2, 0,
};
std::shared_ptr<const DlVertices> vertices = DlVertices::Make(
DlVertexMode::kTriangles, 3, coords, nullptr, nullptr, 6, indices);
ASSERT_NE(vertices, nullptr);
ASSERT_NE(vertices->vertices(), nullptr);
ASSERT_EQ(vertices->texture_coordinates(), nullptr);
ASSERT_EQ(vertices->colors(), nullptr);
ASSERT_NE(vertices->indices(), nullptr);
ASSERT_EQ(vertices->bounds(), SkRect::MakeLTRB(2, 3, 15, 20));
ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles);
ASSERT_EQ(vertices->vertex_count(), 3);
for (int i = 0; i < 3; i++) {
ASSERT_EQ(vertices->vertices()[i], coords[i]);
}
ASSERT_EQ(vertices->index_count(), 6);
for (int i = 0; i < 6; i++) {
ASSERT_EQ(vertices->indices()[i], indices[i]);
}
}
TEST(DisplayListVertices, MakeWithNoOptionalData) {
SkPoint coords[3] = {
SkPoint::Make(2, 3),
SkPoint::Make(5, 6),
SkPoint::Make(15, 20),
};
std::shared_ptr<const DlVertices> vertices = DlVertices::Make(
DlVertexMode::kTriangles, 3, coords, nullptr, nullptr, 6, nullptr);
ASSERT_NE(vertices, nullptr);
ASSERT_NE(vertices->vertices(), nullptr);
ASSERT_EQ(vertices->texture_coordinates(), nullptr);
ASSERT_EQ(vertices->colors(), nullptr);
ASSERT_EQ(vertices->indices(), nullptr);
ASSERT_EQ(vertices->bounds(), SkRect::MakeLTRB(2, 3, 15, 20));
ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles);
ASSERT_EQ(vertices->vertex_count(), 3);
for (int i = 0; i < 3; i++) {
ASSERT_EQ(vertices->vertices()[i], coords[i]);
}
ASSERT_EQ(vertices->index_count(), 0);
}
TEST(DisplayListVertices, MakeWithIndicesButZeroIndexCount) {
SkPoint coords[3] = {
SkPoint::Make(2, 3),
SkPoint::Make(5, 6),
SkPoint::Make(15, 20),
};
uint16_t indices[6] = {
2, 1, 0, //
1, 2, 0,
};
std::shared_ptr<const DlVertices> vertices = DlVertices::Make(
DlVertexMode::kTriangles, 3, coords, nullptr, nullptr, 0, indices);
ASSERT_NE(vertices, nullptr);
ASSERT_NE(vertices->vertices(), nullptr);
ASSERT_EQ(vertices->texture_coordinates(), nullptr);
ASSERT_EQ(vertices->colors(), nullptr);
ASSERT_EQ(vertices->indices(), nullptr);
ASSERT_EQ(vertices->bounds(), SkRect::MakeLTRB(2, 3, 15, 20));
ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles);
ASSERT_EQ(vertices->vertex_count(), 3);
for (int i = 0; i < 3; i++) {
ASSERT_EQ(vertices->vertices()[i], coords[i]);
}
ASSERT_EQ(vertices->index_count(), 0);
}
TEST(DisplayListVertices, MakeWithIndicesButNegativeIndexCount) {
SkPoint coords[3] = {
SkPoint::Make(2, 3),
SkPoint::Make(5, 6),
SkPoint::Make(15, 20),
};
uint16_t indices[6] = {
2, 1, 0, //
1, 2, 0,
};
std::shared_ptr<const DlVertices> vertices = DlVertices::Make(
DlVertexMode::kTriangles, 3, coords, nullptr, nullptr, -5, indices);
ASSERT_NE(vertices, nullptr);
ASSERT_NE(vertices->vertices(), nullptr);
ASSERT_EQ(vertices->texture_coordinates(), nullptr);
ASSERT_EQ(vertices->colors(), nullptr);
ASSERT_EQ(vertices->indices(), nullptr);
ASSERT_EQ(vertices->bounds(), SkRect::MakeLTRB(2, 3, 15, 20));
ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles);
ASSERT_EQ(vertices->vertex_count(), 3);
for (int i = 0; i < 3; i++) {
ASSERT_EQ(vertices->vertices()[i], coords[i]);
}
ASSERT_EQ(vertices->index_count(), 0);
}
using Builder = DlVertices::Builder;
TEST(DisplayListVertices, BuilderFlags) {
Builder::Flags flags;
EXPECT_FALSE(flags.has_texture_coordinates);
EXPECT_FALSE(flags.has_colors);
flags |= Builder::kHasTextureCoordinates;
EXPECT_TRUE(flags.has_texture_coordinates);
EXPECT_FALSE(flags.has_colors);
flags |= Builder::kHasColors;
EXPECT_TRUE(flags.has_texture_coordinates);
EXPECT_TRUE(flags.has_colors);
flags = Builder::Flags();
EXPECT_FALSE(flags.has_texture_coordinates);
EXPECT_FALSE(flags.has_colors);
flags |= Builder::kHasColors;
EXPECT_FALSE(flags.has_texture_coordinates);
EXPECT_TRUE(flags.has_colors);
flags |= Builder::kHasTextureCoordinates;
EXPECT_TRUE(flags.has_texture_coordinates);
EXPECT_TRUE(flags.has_colors);
EXPECT_FALSE(Builder::kNone.has_texture_coordinates);
EXPECT_FALSE(Builder::kNone.has_colors);
EXPECT_TRUE(Builder::kHasTextureCoordinates.has_texture_coordinates);
EXPECT_FALSE(Builder::kHasTextureCoordinates.has_colors);
EXPECT_FALSE(Builder::kHasColors.has_texture_coordinates);
EXPECT_TRUE(Builder::kHasColors.has_colors);
EXPECT_TRUE((Builder::kHasTextureCoordinates | Builder::kHasColors) //
.has_texture_coordinates);
EXPECT_TRUE((Builder::kHasTextureCoordinates | Builder::kHasColors) //
.has_colors);
}
TEST(DisplayListVertices, BuildWithZeroAndNegativeVerticesAndIndices) {
Builder builder1(DlVertexMode::kTriangles, 0, Builder::kNone, 0);
EXPECT_TRUE(builder1.is_valid());
std::shared_ptr<DlVertices> vertices1 = builder1.build();
EXPECT_NE(vertices1, nullptr);
EXPECT_EQ(vertices1->vertex_count(), 0);
EXPECT_EQ(vertices1->vertices(), nullptr);
EXPECT_EQ(vertices1->texture_coordinates(), nullptr);
EXPECT_EQ(vertices1->colors(), nullptr);
EXPECT_EQ(vertices1->index_count(), 0);
EXPECT_EQ(vertices1->indices(), nullptr);
Builder builder2(DlVertexMode::kTriangles, -1, Builder::kNone, -1);
EXPECT_TRUE(builder2.is_valid());
std::shared_ptr<DlVertices> vertices2 = builder2.build();
EXPECT_NE(vertices2, nullptr);
EXPECT_EQ(vertices2->vertex_count(), 0);
EXPECT_EQ(vertices2->vertices(), nullptr);
EXPECT_EQ(vertices2->texture_coordinates(), nullptr);
EXPECT_EQ(vertices2->colors(), nullptr);
EXPECT_EQ(vertices2->index_count(), 0);
EXPECT_EQ(vertices2->indices(), nullptr);
TestEquals(*vertices1, *vertices2);
}
TEST(DisplayListVertices, BuildWithTexAndColorAndIndices) {
SkPoint coords[3] = {
SkPoint::Make(2, 3),
SkPoint::Make(5, 6),
SkPoint::Make(15, 20),
};
SkPoint texture_coords[3] = {
SkPoint::Make(102, 103),
SkPoint::Make(105, 106),
SkPoint::Make(115, 120),
};
DlColor colors[3] = {
DlColor::kRed(),
DlColor::kCyan(),
DlColor::kGreen(),
};
uint16_t indices[6] = {
2, 1, 0, //
1, 2, 0,
};
Builder builder(DlVertexMode::kTriangles, 3, //
Builder::kHasTextureCoordinates | Builder::kHasColors, 6);
builder.store_vertices(coords);
builder.store_texture_coordinates(texture_coords);
builder.store_colors(colors);
builder.store_indices(indices);
std::shared_ptr<const DlVertices> vertices = builder.build();
ASSERT_NE(vertices, nullptr);
ASSERT_NE(vertices->vertices(), nullptr);
ASSERT_NE(vertices->texture_coordinates(), nullptr);
ASSERT_NE(vertices->colors(), nullptr);
ASSERT_NE(vertices->indices(), nullptr);
ASSERT_EQ(vertices->bounds(), SkRect::MakeLTRB(2, 3, 15, 20));
ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles);
ASSERT_EQ(vertices->vertex_count(), 3);
for (int i = 0; i < 3; i++) {
ASSERT_EQ(vertices->vertices()[i], coords[i]);
ASSERT_EQ(vertices->texture_coordinates()[i], texture_coords[i]);
ASSERT_EQ(vertices->colors()[i], colors[i]);
}
ASSERT_EQ(vertices->index_count(), 6);
for (int i = 0; i < 6; i++) {
ASSERT_EQ(vertices->indices()[i], indices[i]);
}
Builder builder2(DlVertexMode::kTriangles, 3, //
Builder::kHasTextureCoordinates | Builder::kHasColors, 6);
builder2.store_vertices(coords);
builder2.store_texture_coordinates(texture_coords);
builder2.store_colors(colors);
builder2.store_indices(indices);
std::shared_ptr<const DlVertices> vertices2 = builder2.build();
TestEquals(*vertices, *vertices2);
std::shared_ptr<const DlVertices> vertices3 = DlVertices::Make(
DlVertexMode::kTriangles, 3, coords, texture_coords, colors, 6, indices);
TestEquals(*vertices, *vertices3);
}
TEST(DisplayListVertices, BuildWithTexAndColor) {
SkPoint coords[3] = {
SkPoint::Make(2, 3),
SkPoint::Make(5, 6),
SkPoint::Make(15, 20),
};
SkPoint texture_coords[3] = {
SkPoint::Make(102, 103),
SkPoint::Make(105, 106),
SkPoint::Make(115, 120),
};
DlColor colors[3] = {
DlColor::kRed(),
DlColor::kCyan(),
DlColor::kGreen(),
};
Builder builder(DlVertexMode::kTriangles, 3, //
Builder::kHasTextureCoordinates | Builder::kHasColors, 0);
builder.store_vertices(coords);
builder.store_texture_coordinates(texture_coords);
builder.store_colors(colors);
std::shared_ptr<const DlVertices> vertices = builder.build();
ASSERT_NE(vertices, nullptr);
ASSERT_NE(vertices->vertices(), nullptr);
ASSERT_NE(vertices->texture_coordinates(), nullptr);
ASSERT_NE(vertices->colors(), nullptr);
ASSERT_EQ(vertices->indices(), nullptr);
ASSERT_EQ(vertices->bounds(), SkRect::MakeLTRB(2, 3, 15, 20));
ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles);
ASSERT_EQ(vertices->vertex_count(), 3);
for (int i = 0; i < 3; i++) {
ASSERT_EQ(vertices->vertices()[i], coords[i]);
ASSERT_EQ(vertices->texture_coordinates()[i], texture_coords[i]);
ASSERT_EQ(vertices->colors()[i], colors[i]);
}
ASSERT_EQ(vertices->index_count(), 0);
}
TEST(DisplayListVertices, BuildWithTexAndIndices) {
SkPoint coords[3] = {
SkPoint::Make(2, 3),
SkPoint::Make(5, 6),
SkPoint::Make(15, 20),
};
SkPoint texture_coords[3] = {
SkPoint::Make(102, 103),
SkPoint::Make(105, 106),
SkPoint::Make(115, 120),
};
uint16_t indices[6] = {
2, 1, 0, //
1, 2, 0,
};
Builder builder(DlVertexMode::kTriangles, 3, //
Builder::kHasTextureCoordinates, 6);
builder.store_vertices(coords);
builder.store_texture_coordinates(texture_coords);
builder.store_indices(indices);
std::shared_ptr<const DlVertices> vertices = builder.build();
ASSERT_NE(vertices, nullptr);
ASSERT_NE(vertices->vertices(), nullptr);
ASSERT_NE(vertices->texture_coordinates(), nullptr);
ASSERT_EQ(vertices->colors(), nullptr);
ASSERT_NE(vertices->indices(), nullptr);
ASSERT_EQ(vertices->bounds(), SkRect::MakeLTRB(2, 3, 15, 20));
ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles);
ASSERT_EQ(vertices->vertex_count(), 3);
for (int i = 0; i < 3; i++) {
ASSERT_EQ(vertices->vertices()[i], coords[i]);
ASSERT_EQ(vertices->texture_coordinates()[i], texture_coords[i]);
}
ASSERT_EQ(vertices->index_count(), 6);
for (int i = 0; i < 6; i++) {
ASSERT_EQ(vertices->indices()[i], indices[i]);
}
}
TEST(DisplayListVertices, BuildWithColorAndIndices) {
SkPoint coords[3] = {
SkPoint::Make(2, 3),
SkPoint::Make(5, 6),
SkPoint::Make(15, 20),
};
SkColor colors[3] = {
SK_ColorRED,
SK_ColorCYAN,
SK_ColorGREEN,
};
uint16_t indices[6] = {
2, 1, 0, //
1, 2, 0,
};
Builder builder(DlVertexMode::kTriangles, 3, //
Builder::kHasColors, 6);
builder.store_vertices(coords);
builder.store_colors(colors);
builder.store_indices(indices);
std::shared_ptr<const DlVertices> vertices = builder.build();
ASSERT_NE(vertices, nullptr);
ASSERT_NE(vertices->vertices(), nullptr);
ASSERT_EQ(vertices->texture_coordinates(), nullptr);
ASSERT_NE(vertices->colors(), nullptr);
ASSERT_NE(vertices->indices(), nullptr);
ASSERT_EQ(vertices->bounds(), SkRect::MakeLTRB(2, 3, 15, 20));
ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles);
ASSERT_EQ(vertices->vertex_count(), 3);
for (int i = 0; i < 3; i++) {
ASSERT_EQ(vertices->vertices()[i], coords[i]);
ASSERT_EQ(vertices->colors()[i], colors[i]);
}
ASSERT_EQ(vertices->index_count(), 6);
for (int i = 0; i < 6; i++) {
ASSERT_EQ(vertices->indices()[i], indices[i]);
}
}
TEST(DisplayListVertices, BuildWithTexUsingPoints) {
SkPoint coords[3] = {
SkPoint::Make(2, 3),
SkPoint::Make(5, 6),
SkPoint::Make(15, 20),
};
SkPoint texture_coords[3] = {
SkPoint::Make(102, 103),
SkPoint::Make(105, 106),
SkPoint::Make(115, 120),
};
Builder builder(DlVertexMode::kTriangles, 3, //
Builder::kHasTextureCoordinates, 0);
builder.store_vertices(coords);
builder.store_texture_coordinates(texture_coords);
std::shared_ptr<const DlVertices> vertices = builder.build();
ASSERT_NE(vertices, nullptr);
ASSERT_NE(vertices->vertices(), nullptr);
ASSERT_NE(vertices->texture_coordinates(), nullptr);
ASSERT_EQ(vertices->colors(), nullptr);
ASSERT_EQ(vertices->indices(), nullptr);
ASSERT_EQ(vertices->bounds(), SkRect::MakeLTRB(2, 3, 15, 20));
ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles);
ASSERT_EQ(vertices->vertex_count(), 3);
for (int i = 0; i < 3; i++) {
ASSERT_EQ(vertices->vertices()[i], coords[i]);
ASSERT_EQ(vertices->texture_coordinates()[i], texture_coords[i]);
}
ASSERT_EQ(vertices->index_count(), 0);
}
TEST(DisplayListVertices, BuildWithTexUsingFloats) {
float coords[6] = {
2, 3, //
5, 6, //
15, 20,
};
float texture_coords[6] = {
102, 103, //
105, 106, //
115, 120,
};
Builder builder(DlVertexMode::kTriangles, 3, //
Builder::kHasTextureCoordinates, 0);
builder.store_vertices(coords);
builder.store_texture_coordinates(texture_coords);
std::shared_ptr<const DlVertices> vertices = builder.build();
ASSERT_NE(vertices, nullptr);
ASSERT_NE(vertices->vertices(), nullptr);
ASSERT_NE(vertices->texture_coordinates(), nullptr);
ASSERT_EQ(vertices->colors(), nullptr);
ASSERT_EQ(vertices->indices(), nullptr);
ASSERT_EQ(vertices->bounds(), SkRect::MakeLTRB(2, 3, 15, 20));
ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles);
ASSERT_EQ(vertices->vertex_count(), 3);
for (int i = 0; i < 3; i++) {
ASSERT_EQ(vertices->vertices()[i].fX, coords[i * 2 + 0]);
ASSERT_EQ(vertices->vertices()[i].fY, coords[i * 2 + 1]);
ASSERT_EQ(vertices->texture_coordinates()[i].fX, texture_coords[i * 2 + 0]);
ASSERT_EQ(vertices->texture_coordinates()[i].fY, texture_coords[i * 2 + 1]);
}
ASSERT_EQ(vertices->index_count(), 0);
}
TEST(DisplayListVertices, BuildUsingFloatsSameAsPoints) {
SkPoint coord_points[3] = {
SkPoint::Make(2, 3),
SkPoint::Make(5, 6),
SkPoint::Make(15, 20),
};
SkPoint texture_coord_points[3] = {
SkPoint::Make(102, 103),
SkPoint::Make(105, 106),
SkPoint::Make(115, 120),
};
float coord_floats[6] = {
2, 3, //
5, 6, //
15, 20,
};
float texture_coord_floats[6] = {
102, 103, //
105, 106, //
115, 120,
};
Builder builder_points(DlVertexMode::kTriangles, 3, //
Builder::kHasTextureCoordinates, 0);
builder_points.store_vertices(coord_points);
builder_points.store_texture_coordinates(texture_coord_points);
std::shared_ptr<const DlVertices> vertices_points = builder_points.build();
Builder builder_floats(DlVertexMode::kTriangles, 3, //
Builder::kHasTextureCoordinates, 0);
builder_floats.store_vertices(coord_floats);
builder_floats.store_texture_coordinates(texture_coord_floats);
std::shared_ptr<const DlVertices> vertices_floats = builder_floats.build();
TestEquals(*vertices_points, *vertices_floats);
}
TEST(DisplayListVertices, BuildWithColor) {
SkPoint coords[3] = {
SkPoint::Make(2, 3),
SkPoint::Make(5, 6),
SkPoint::Make(15, 20),
};
SkColor colors[3] = {
SK_ColorRED,
SK_ColorCYAN,
SK_ColorGREEN,
};
Builder builder(DlVertexMode::kTriangles, 3, //
Builder::kHasColors, 0);
builder.store_vertices(coords);
builder.store_colors(colors);
std::shared_ptr<const DlVertices> vertices = builder.build();
ASSERT_NE(vertices, nullptr);
ASSERT_NE(vertices->vertices(), nullptr);
ASSERT_EQ(vertices->texture_coordinates(), nullptr);
ASSERT_NE(vertices->colors(), nullptr);
ASSERT_EQ(vertices->indices(), nullptr);
ASSERT_EQ(vertices->bounds(), SkRect::MakeLTRB(2, 3, 15, 20));
ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles);
ASSERT_EQ(vertices->vertex_count(), 3);
for (int i = 0; i < 3; i++) {
ASSERT_EQ(vertices->vertices()[i], coords[i]);
ASSERT_EQ(vertices->colors()[i], colors[i]);
}
ASSERT_EQ(vertices->index_count(), 0);
}
TEST(DisplayListVertices, BuildWithIndices) {
SkPoint coords[3] = {
SkPoint::Make(2, 3),
SkPoint::Make(5, 6),
SkPoint::Make(15, 20),
};
uint16_t indices[6] = {
2, 1, 0, //
1, 2, 0,
};
Builder builder(DlVertexMode::kTriangles, 3, Builder::kNone, 6);
builder.store_vertices(coords);
builder.store_indices(indices);
std::shared_ptr<const DlVertices> vertices = builder.build();
ASSERT_NE(vertices, nullptr);
ASSERT_NE(vertices->vertices(), nullptr);
ASSERT_EQ(vertices->texture_coordinates(), nullptr);
ASSERT_EQ(vertices->colors(), nullptr);
ASSERT_NE(vertices->indices(), nullptr);
ASSERT_EQ(vertices->bounds(), SkRect::MakeLTRB(2, 3, 15, 20));
ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles);
ASSERT_EQ(vertices->vertex_count(), 3);
for (int i = 0; i < 3; i++) {
ASSERT_EQ(vertices->vertices()[i], coords[i]);
}
ASSERT_EQ(vertices->index_count(), 6);
for (int i = 0; i < 6; i++) {
ASSERT_EQ(vertices->indices()[i], indices[i]);
}
}
TEST(DisplayListVertices, BuildWithNoOptionalData) {
SkPoint coords[3] = {
SkPoint::Make(2, 3),
SkPoint::Make(5, 6),
SkPoint::Make(15, 20),
};
Builder builder(DlVertexMode::kTriangles, 3, Builder::kNone, 0);
builder.store_vertices(coords);
std::shared_ptr<const DlVertices> vertices = builder.build();
ASSERT_NE(vertices, nullptr);
ASSERT_NE(vertices->vertices(), nullptr);
ASSERT_EQ(vertices->texture_coordinates(), nullptr);
ASSERT_EQ(vertices->colors(), nullptr);
ASSERT_EQ(vertices->indices(), nullptr);
ASSERT_EQ(vertices->bounds(), SkRect::MakeLTRB(2, 3, 15, 20));
ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles);
ASSERT_EQ(vertices->vertex_count(), 3);
for (int i = 0; i < 3; i++) {
ASSERT_EQ(vertices->vertices()[i], coords[i]);
}
ASSERT_EQ(vertices->index_count(), 0);
}
TEST(DisplayListVertices, BuildWithNegativeIndexCount) {
SkPoint coords[3] = {
SkPoint::Make(2, 3),
SkPoint::Make(5, 6),
SkPoint::Make(15, 20),
};
Builder builder(DlVertexMode::kTriangles, 3, Builder::kNone, -5);
builder.store_vertices(coords);
std::shared_ptr<const DlVertices> vertices = builder.build();
ASSERT_NE(vertices, nullptr);
ASSERT_NE(vertices->vertices(), nullptr);
ASSERT_EQ(vertices->texture_coordinates(), nullptr);
ASSERT_EQ(vertices->colors(), nullptr);
ASSERT_EQ(vertices->indices(), nullptr);
ASSERT_EQ(vertices->bounds(), SkRect::MakeLTRB(2, 3, 15, 20));
ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles);
ASSERT_EQ(vertices->vertex_count(), 3);
for (int i = 0; i < 3; i++) {
ASSERT_EQ(vertices->vertices()[i], coords[i]);
}
ASSERT_EQ(vertices->index_count(), 0);
}
TEST(DisplayListVertices, TestEquals) {
SkPoint coords[3] = {
SkPoint::Make(2, 3),
SkPoint::Make(5, 6),
SkPoint::Make(15, 20),
};
SkPoint texture_coords[3] = {
SkPoint::Make(102, 103),
SkPoint::Make(105, 106),
SkPoint::Make(115, 120),
};
DlColor colors[3] = {
DlColor::kRed(),
DlColor::kCyan(),
DlColor::kGreen(),
};
uint16_t indices[6] = {
2, 1, 0, //
1, 2, 0,
};
std::shared_ptr<const DlVertices> vertices1 = DlVertices::Make(
DlVertexMode::kTriangles, 3, coords, texture_coords, colors, 6, indices);
std::shared_ptr<const DlVertices> vertices2 = DlVertices::Make(
DlVertexMode::kTriangles, 3, coords, texture_coords, colors, 6, indices);
TestEquals(*vertices1, *vertices2);
}
TEST(DisplayListVertices, TestNotEquals) {
SkPoint coords[4] = {
SkPoint::Make(2, 3),
SkPoint::Make(5, 6),
SkPoint::Make(15, 20),
SkPoint::Make(53, 62),
};
SkPoint wrong_coords[4] = {
SkPoint::Make(2, 3),
SkPoint::Make(5, 6),
SkPoint::Make(15, 20),
SkPoint::Make(57, 62),
};
SkPoint texture_coords[4] = {
SkPoint::Make(102, 103),
SkPoint::Make(105, 106),
SkPoint::Make(115, 120),
SkPoint::Make(153, 162),
};
SkPoint wrong_texture_coords[4] = {
SkPoint::Make(102, 103),
SkPoint::Make(105, 106),
SkPoint::Make(115, 121),
SkPoint::Make(153, 162),
};
DlColor colors[4] = {
DlColor::kRed(),
DlColor::kCyan(),
DlColor::kGreen(),
DlColor::kMagenta(),
};
DlColor wrong_colors[4] = {
DlColor::kRed(),
DlColor::kBlue(),
DlColor::kGreen(),
DlColor::kMagenta(),
};
uint16_t indices[9] = {
2, 1, 0, //
1, 2, 0, //
1, 2, 3,
};
uint16_t wrong_indices[9] = {
2, 1, 0, //
1, 2, 0, //
2, 3, 1,
};
std::shared_ptr<const DlVertices> vertices1 = DlVertices::Make(
DlVertexMode::kTriangles, 4, coords, texture_coords, colors, 9, indices);
{
std::shared_ptr<const DlVertices> vertices2 =
DlVertices::Make(DlVertexMode::kTriangleFan, 4, coords, //
texture_coords, colors, 9, indices);
TestNotEquals(*vertices1, *vertices2, "vertex mode differs");
}
{
std::shared_ptr<const DlVertices> vertices2 =
DlVertices::Make(DlVertexMode::kTriangles, 3, coords, //
texture_coords, colors, 9, indices);
TestNotEquals(*vertices1, *vertices2, "vertex count differs");
}
{
std::shared_ptr<const DlVertices> vertices2 =
DlVertices::Make(DlVertexMode::kTriangles, 4, wrong_coords, //
texture_coords, colors, 9, indices);
TestNotEquals(*vertices1, *vertices2, "vertex coordinates differ");
}
{
std::shared_ptr<const DlVertices> vertices2 =
DlVertices::Make(DlVertexMode::kTriangles, 4, coords, //
wrong_texture_coords, colors, 9, indices);
TestNotEquals(*vertices1, *vertices2, "texture coordinates differ");
}
{
std::shared_ptr<const DlVertices> vertices2 =
DlVertices::Make(DlVertexMode::kTriangles, 4, coords, //
texture_coords, wrong_colors, 9, indices);
TestNotEquals(*vertices1, *vertices2, "colors differ");
}
{
std::shared_ptr<const DlVertices> vertices2 =
DlVertices::Make(DlVertexMode::kTriangles, 4, coords, //
texture_coords, colors, 6, indices);
TestNotEquals(*vertices1, *vertices2, "index count differs");
}
{
std::shared_ptr<const DlVertices> vertices2 =
DlVertices::Make(DlVertexMode::kTriangles, 4, coords, //
texture_coords, colors, 9, wrong_indices);
TestNotEquals(*vertices1, *vertices2, "indices differ");
}
}
} // namespace testing
} // namespace flutter
| engine/display_list/dl_vertices_unittests.cc/0 | {
"file_path": "engine/display_list/dl_vertices_unittests.cc",
"repo_id": "engine",
"token_count": 13537
} | 161 |
// 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.
#include "flutter/display_list/effects/dl_runtime_effect.h"
#include "third_party/skia/include/core/SkRefCnt.h"
namespace flutter {
//------------------------------------------------------------------------------
/// DlRuntimeEffect
///
DlRuntimeEffect::DlRuntimeEffect() = default;
DlRuntimeEffect::~DlRuntimeEffect() = default;
sk_sp<DlRuntimeEffect> DlRuntimeEffect::MakeSkia(
const sk_sp<SkRuntimeEffect>& runtime_effect) {
return sk_make_sp<DlRuntimeEffectSkia>(runtime_effect);
}
sk_sp<DlRuntimeEffect> DlRuntimeEffect::MakeImpeller(
std::shared_ptr<impeller::RuntimeStage> runtime_stage) {
return sk_make_sp<DlRuntimeEffectImpeller>(std::move(runtime_stage));
}
//------------------------------------------------------------------------------
/// DlRuntimeEffectSkia
///
DlRuntimeEffectSkia::~DlRuntimeEffectSkia() = default;
DlRuntimeEffectSkia::DlRuntimeEffectSkia(
const sk_sp<SkRuntimeEffect>& runtime_effect)
: skia_runtime_effect_(runtime_effect) {}
sk_sp<SkRuntimeEffect> DlRuntimeEffectSkia::skia_runtime_effect() const {
return skia_runtime_effect_;
}
std::shared_ptr<impeller::RuntimeStage> DlRuntimeEffectSkia::runtime_stage()
const {
return nullptr;
}
//------------------------------------------------------------------------------
/// DlRuntimeEffectImpeller
///
DlRuntimeEffectImpeller::~DlRuntimeEffectImpeller() = default;
DlRuntimeEffectImpeller::DlRuntimeEffectImpeller(
std::shared_ptr<impeller::RuntimeStage> runtime_stage)
: runtime_stage_(std::move(runtime_stage)){};
sk_sp<SkRuntimeEffect> DlRuntimeEffectImpeller::skia_runtime_effect() const {
return nullptr;
}
std::shared_ptr<impeller::RuntimeStage> DlRuntimeEffectImpeller::runtime_stage()
const {
return runtime_stage_;
}
} // namespace flutter
| engine/display_list/effects/dl_runtime_effect.cc/0 | {
"file_path": "engine/display_list/effects/dl_runtime_effect.cc",
"repo_id": "engine",
"token_count": 614
} | 162 |
// 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.
#include "flutter/display_list/dl_blend_mode.h"
#include "flutter/display_list/dl_paint.h"
#include "flutter/display_list/dl_sampling_options.h"
#include "flutter/display_list/dl_tile_mode.h"
#include "flutter/display_list/dl_vertices.h"
#include "flutter/display_list/effects/dl_color_source.h"
#include "flutter/display_list/skia/dl_sk_conversions.h"
#include "gtest/gtest.h"
#include "third_party/skia/include/core/SkColorSpace.h"
#include "third_party/skia/include/core/SkSamplingOptions.h"
#include "third_party/skia/include/core/SkTileMode.h"
namespace flutter {
namespace testing {
TEST(DisplayListImageFilter, LocalImageSkiaNull) {
auto blur_filter =
std::make_shared<DlBlurImageFilter>(0, 0, DlTileMode::kClamp);
DlLocalMatrixImageFilter dl_local_matrix_filter(SkMatrix::RotateDeg(45),
blur_filter);
// With sigmas set to zero on the blur filter, Skia will return a null filter.
// The local matrix filter should return nullptr instead of crashing.
ASSERT_EQ(ToSk(dl_local_matrix_filter), nullptr);
}
TEST(DisplayListSkConversions, ToSkColor) {
// Red
ASSERT_EQ(ToSk(DlColor::kRed()), SK_ColorRED);
// Green
ASSERT_EQ(ToSk(DlColor::kGreen()), SK_ColorGREEN);
// Blue
ASSERT_EQ(ToSk(DlColor::kBlue()), SK_ColorBLUE);
// Half transparent grey
auto const grey_hex_half_opaque = 0x7F999999;
ASSERT_EQ(ToSk(DlColor(grey_hex_half_opaque)), SkColor(grey_hex_half_opaque));
}
TEST(DisplayListSkConversions, ToSkTileMode) {
ASSERT_EQ(ToSk(DlTileMode::kClamp), SkTileMode::kClamp);
ASSERT_EQ(ToSk(DlTileMode::kRepeat), SkTileMode::kRepeat);
ASSERT_EQ(ToSk(DlTileMode::kMirror), SkTileMode::kMirror);
ASSERT_EQ(ToSk(DlTileMode::kDecal), SkTileMode::kDecal);
}
TEST(DisplayListSkConversions, ToSkBlurStyle) {
ASSERT_EQ(ToSk(DlBlurStyle::kInner), SkBlurStyle::kInner_SkBlurStyle);
ASSERT_EQ(ToSk(DlBlurStyle::kOuter), SkBlurStyle::kOuter_SkBlurStyle);
ASSERT_EQ(ToSk(DlBlurStyle::kSolid), SkBlurStyle::kSolid_SkBlurStyle);
ASSERT_EQ(ToSk(DlBlurStyle::kNormal), SkBlurStyle::kNormal_SkBlurStyle);
}
TEST(DisplayListSkConversions, ToSkDrawStyle) {
ASSERT_EQ(ToSk(DlDrawStyle::kFill), SkPaint::Style::kFill_Style);
ASSERT_EQ(ToSk(DlDrawStyle::kStroke), SkPaint::Style::kStroke_Style);
ASSERT_EQ(ToSk(DlDrawStyle::kStrokeAndFill),
SkPaint::Style::kStrokeAndFill_Style);
}
TEST(DisplayListSkConversions, ToSkStrokeCap) {
ASSERT_EQ(ToSk(DlStrokeCap::kButt), SkPaint::Cap::kButt_Cap);
ASSERT_EQ(ToSk(DlStrokeCap::kRound), SkPaint::Cap::kRound_Cap);
ASSERT_EQ(ToSk(DlStrokeCap::kSquare), SkPaint::Cap::kSquare_Cap);
}
TEST(DisplayListSkConversions, ToSkStrokeJoin) {
ASSERT_EQ(ToSk(DlStrokeJoin::kMiter), SkPaint::Join::kMiter_Join);
ASSERT_EQ(ToSk(DlStrokeJoin::kRound), SkPaint::Join::kRound_Join);
ASSERT_EQ(ToSk(DlStrokeJoin::kBevel), SkPaint::Join::kBevel_Join);
}
TEST(DisplayListSkConversions, ToSkVertexMode) {
ASSERT_EQ(ToSk(DlVertexMode::kTriangles),
SkVertices::VertexMode::kTriangles_VertexMode);
ASSERT_EQ(ToSk(DlVertexMode::kTriangleStrip),
SkVertices::VertexMode::kTriangleStrip_VertexMode);
ASSERT_EQ(ToSk(DlVertexMode::kTriangleFan),
SkVertices::VertexMode::kTriangleFan_VertexMode);
}
TEST(DisplayListSkConversions, ToSkFilterMode) {
ASSERT_EQ(ToSk(DlFilterMode::kLinear), SkFilterMode::kLinear);
ASSERT_EQ(ToSk(DlFilterMode::kNearest), SkFilterMode::kNearest);
ASSERT_EQ(ToSk(DlFilterMode::kLast), SkFilterMode::kLast);
}
TEST(DisplayListSkConversions, ToSkSrcRectConstraint) {
ASSERT_EQ(ToSk(DlCanvas::SrcRectConstraint::kFast),
SkCanvas::SrcRectConstraint::kFast_SrcRectConstraint);
ASSERT_EQ(ToSk(DlCanvas::SrcRectConstraint::kStrict),
SkCanvas::SrcRectConstraint::kStrict_SrcRectConstraint);
}
TEST(DisplayListSkConversions, ToSkSamplingOptions) {
ASSERT_EQ(ToSk(DlImageSampling::kLinear),
SkSamplingOptions(SkFilterMode::kLinear, SkMipmapMode::kNone));
ASSERT_EQ(ToSk(DlImageSampling::kMipmapLinear),
SkSamplingOptions(SkFilterMode::kLinear, SkMipmapMode::kLinear));
ASSERT_EQ(ToSk(DlImageSampling::kNearestNeighbor),
SkSamplingOptions(SkFilterMode::kNearest, SkMipmapMode::kNone));
ASSERT_EQ(ToSk(DlImageSampling::kCubic),
SkSamplingOptions(SkCubicResampler{1 / 3.0f, 1 / 3.0f}));
}
#define FOR_EACH_BLEND_MODE_ENUM(FUNC) \
FUNC(kSrc) \
FUNC(kClear) \
FUNC(kSrc) \
FUNC(kDst) \
FUNC(kSrcOver) \
FUNC(kDstOver) \
FUNC(kSrcIn) \
FUNC(kDstIn) \
FUNC(kSrcOut) \
FUNC(kDstOut) \
FUNC(kSrcATop) \
FUNC(kDstATop) \
FUNC(kXor) \
FUNC(kPlus) \
FUNC(kModulate) \
FUNC(kScreen) \
FUNC(kOverlay) \
FUNC(kDarken) \
FUNC(kLighten) \
FUNC(kColorDodge) \
FUNC(kColorBurn) \
FUNC(kHardLight) \
FUNC(kSoftLight) \
FUNC(kDifference) \
FUNC(kExclusion) \
FUNC(kMultiply) \
FUNC(kHue) \
FUNC(kSaturation) \
FUNC(kColor) \
FUNC(kLuminosity) \
FUNC(kLastCoeffMode) \
FUNC(kLastSeparableMode) \
FUNC(kLastMode)
TEST(DisplayListSkConversions, ToSkBlendMode){
#define CHECK_TO_SKENUM(V) ASSERT_EQ(ToSk(DlBlendMode::V), SkBlendMode::V);
FOR_EACH_BLEND_MODE_ENUM(CHECK_TO_SKENUM)
#undef CHECK_TO_SKENUM
}
TEST(DisplayListSkConversions, BlendColorFilterModifiesTransparency) {
auto test_mode_color = [](DlBlendMode mode, DlColor color) {
std::stringstream desc_str;
desc_str << "blend[" << static_cast<int>(mode) << ", " << color.argb()
<< "]";
std::string desc = desc_str.str();
DlBlendColorFilter filter(color, mode);
auto srgb = SkColorSpace::MakeSRGB();
if (filter.modifies_transparent_black()) {
auto dl_filter = DlBlendColorFilter::Make(color, mode);
auto sk_filter = ToSk(filter);
ASSERT_NE(dl_filter, nullptr) << desc;
ASSERT_NE(sk_filter, nullptr) << desc;
ASSERT_TRUE(sk_filter->filterColor4f(SkColors::kTransparent, srgb.get(),
srgb.get()) !=
SkColors::kTransparent)
<< desc;
} else {
auto dl_filter = DlBlendColorFilter::Make(color, mode);
auto sk_filter = ToSk(filter);
EXPECT_EQ(dl_filter == nullptr, sk_filter == nullptr) << desc;
ASSERT_TRUE(sk_filter == nullptr ||
sk_filter->filterColor4f(SkColors::kTransparent, srgb.get(),
srgb.get()) ==
SkColors::kTransparent)
<< desc;
}
};
auto test_mode = [&test_mode_color](DlBlendMode mode) {
test_mode_color(mode, DlColor::kTransparent());
test_mode_color(mode, DlColor::kWhite());
test_mode_color(mode, DlColor::kWhite().modulateOpacity(0.5));
test_mode_color(mode, DlColor::kBlack());
test_mode_color(mode, DlColor::kBlack().modulateOpacity(0.5));
};
#define TEST_MODE(V) test_mode(DlBlendMode::V);
FOR_EACH_BLEND_MODE_ENUM(TEST_MODE)
#undef TEST_MODE
}
#undef FOR_EACH_BLEND_MODE_ENUM
TEST(DisplayListSkConversions, ConvertWithZeroAndNegativeVerticesAndIndices) {
std::shared_ptr<const DlVertices> vertices1 = DlVertices::Make(
DlVertexMode::kTriangles, 0, nullptr, nullptr, nullptr, 0, nullptr);
EXPECT_NE(vertices1, nullptr);
EXPECT_NE(ToSk(vertices1), nullptr);
std::shared_ptr<const DlVertices> vertices2 = DlVertices::Make(
DlVertexMode::kTriangles, -1, nullptr, nullptr, nullptr, -1, nullptr);
EXPECT_NE(vertices2, nullptr);
EXPECT_NE(ToSk(vertices2), nullptr);
}
TEST(DisplayListVertices, ConvertWithZeroAndNegativeVerticesAndIndices) {
DlVertices::Builder builder1(DlVertexMode::kTriangles, 0,
DlVertices::Builder::kNone, 0);
EXPECT_TRUE(builder1.is_valid());
std::shared_ptr<DlVertices> vertices1 = builder1.build();
EXPECT_NE(vertices1, nullptr);
EXPECT_NE(ToSk(vertices1), nullptr);
DlVertices::Builder builder2(DlVertexMode::kTriangles, -1,
DlVertices::Builder::kNone, -1);
EXPECT_TRUE(builder2.is_valid());
std::shared_ptr<DlVertices> vertices2 = builder2.build();
EXPECT_NE(vertices2, nullptr);
EXPECT_NE(ToSk(vertices2), nullptr);
}
TEST(DisplayListColorSource, ConvertRuntimeEffect) {
const sk_sp<DlRuntimeEffect> kTestRuntimeEffect1 = DlRuntimeEffect::MakeSkia(
SkRuntimeEffect::MakeForShader(
SkString("vec4 main(vec2 p) { return vec4(0); }"))
.effect);
const sk_sp<DlRuntimeEffect> kTestRuntimeEffect2 = DlRuntimeEffect::MakeSkia(
SkRuntimeEffect::MakeForShader(
SkString("vec4 main(vec2 p) { return vec4(1); }"))
.effect);
std::shared_ptr<DlRuntimeEffectColorSource> source1 =
DlColorSource::MakeRuntimeEffect(
kTestRuntimeEffect1, {}, std::make_shared<std::vector<uint8_t>>());
std::shared_ptr<DlRuntimeEffectColorSource> source2 =
DlColorSource::MakeRuntimeEffect(
kTestRuntimeEffect2, {}, std::make_shared<std::vector<uint8_t>>());
std::shared_ptr<DlRuntimeEffectColorSource> source3 =
DlColorSource::MakeRuntimeEffect(
nullptr, {}, std::make_shared<std::vector<uint8_t>>());
ASSERT_NE(ToSk(source1), nullptr);
ASSERT_NE(ToSk(source2), nullptr);
ASSERT_EQ(ToSk(source3), nullptr);
}
TEST(DisplayListColorSource, ConvertRuntimeEffectWithNullSampler) {
const sk_sp<DlRuntimeEffect> kTestRuntimeEffect1 = DlRuntimeEffect::MakeSkia(
SkRuntimeEffect::MakeForShader(
SkString("vec4 main(vec2 p) { return vec4(0); }"))
.effect);
std::shared_ptr<DlRuntimeEffectColorSource> source1 =
DlColorSource::MakeRuntimeEffect(
kTestRuntimeEffect1, {nullptr},
std::make_shared<std::vector<uint8_t>>());
ASSERT_EQ(ToSk(source1), nullptr);
}
TEST(DisplayListSkConversions, MatrixColorFilterModifiesTransparency) {
auto test_matrix = [](int element, SkScalar value) {
// clang-format off
float matrix[] = {
1, 0, 0, 0, 0,
0, 1, 0, 0, 0,
0, 0, 1, 0, 0,
0, 0, 0, 1, 0,
};
// clang-format on
std::string desc =
"matrix[" + std::to_string(element) + "] = " + std::to_string(value);
matrix[element] = value;
DlMatrixColorFilter filter(matrix);
auto dl_filter = DlMatrixColorFilter::Make(matrix);
auto sk_filter = ToSk(filter);
auto srgb = SkColorSpace::MakeSRGB();
EXPECT_EQ(dl_filter == nullptr, sk_filter == nullptr);
EXPECT_EQ(filter.modifies_transparent_black(),
sk_filter && sk_filter->filterColor4f(SkColors::kTransparent,
srgb.get(), srgb.get()) !=
SkColors::kTransparent);
};
// Tests identity (matrix[0] already == 1 in an identity filter)
test_matrix(0, 1);
// test_matrix(19, 1);
for (int i = 0; i < 20; i++) {
test_matrix(i, -0.25);
test_matrix(i, 0);
test_matrix(i, 0.25);
test_matrix(i, 1);
test_matrix(i, 1.25);
test_matrix(i, SK_ScalarNaN);
test_matrix(i, SK_ScalarInfinity);
test_matrix(i, -SK_ScalarInfinity);
}
}
TEST(DisplayListSkConversions, ToSkDitheringEnabledForGradients) {
// Test that when using the utility method "ToSk", the resulting SkPaint
// has "isDither" set to true, if the paint is a gradient, because it's
// a supported feature in the Impeller backend.
DlPaint dl_paint;
// Set the paint to be a gradient.
dl_paint.setColorSource(DlColorSource::MakeLinear(SkPoint::Make(0, 0),
SkPoint::Make(100, 100), 0,
0, 0, DlTileMode::kClamp));
{
SkPaint sk_paint = ToSk(dl_paint);
EXPECT_TRUE(sk_paint.isDither());
}
{
SkPaint sk_paint = ToStrokedSk(dl_paint);
EXPECT_TRUE(sk_paint.isDither());
}
{
SkPaint sk_paint = ToNonShaderSk(dl_paint);
EXPECT_FALSE(sk_paint.isDither());
}
}
} // namespace testing
} // namespace flutter
| engine/display_list/skia/dl_sk_conversions_unittests.cc/0 | {
"file_path": "engine/display_list/skia/dl_sk_conversions_unittests.cc",
"repo_id": "engine",
"token_count": 6127
} | 163 |
// 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.
#include "flutter/display_list/testing/dl_test_surface_provider.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkData.h"
#include "third_party/skia/include/core/SkImage.h"
#include "third_party/skia/include/core/SkSurface.h"
#include "third_party/skia/include/encode/SkPngEncoder.h"
#ifdef ENABLE_SOFTWARE_BENCHMARKS
#include "flutter/display_list/testing/dl_test_surface_software.h"
#endif
#ifdef ENABLE_OPENGL_BENCHMARKS
#include "flutter/display_list/testing/dl_test_surface_gl.h"
#endif
#ifdef ENABLE_METAL_BENCHMARKS
#include "flutter/display_list/testing/dl_test_surface_metal.h"
#endif
namespace flutter {
namespace testing {
std::string DlSurfaceProvider::BackendName(BackendType type) {
switch (type) {
case kMetalBackend:
return "Metal";
case kOpenGlBackend:
return "OpenGL";
case kSoftwareBackend:
return "Software";
}
}
std::unique_ptr<DlSurfaceProvider> DlSurfaceProvider::Create(
BackendType backend_type) {
switch (backend_type) {
#ifdef ENABLE_SOFTWARE_BENCHMARKS
case kSoftwareBackend:
return std::make_unique<DlSoftwareSurfaceProvider>();
#endif
#ifdef ENABLE_OPENGL_BENCHMARKS
case kOpenGLBackend:
return std::make_unique<DlOpenGLSurfaceProvider>();
#endif
#ifdef ENABLE_METAL_BENCHMARKS
case kMetalBackend:
return std::make_unique<DlMetalSurfaceProvider>();
#endif
default:
return nullptr;
}
return nullptr;
}
bool DlSurfaceProvider::Snapshot(std::string& filename) const {
#ifdef BENCHMARKS_NO_SNAPSHOT
return false;
#else
auto image = GetPrimarySurface()->sk_surface()->makeImageSnapshot();
if (!image) {
return false;
}
auto raster = image->makeRasterImage();
if (!raster) {
return false;
}
auto data = SkPngEncoder::Encode(nullptr, raster.get(), {});
if (!data) {
return false;
}
fml::NonOwnedMapping mapping(static_cast<const uint8_t*>(data->data()),
data->size());
return WriteAtomically(OpenFixturesDirectory(), filename.c_str(), mapping);
#endif
}
} // namespace testing
} // namespace flutter
| engine/display_list/testing/dl_test_surface_provider.cc/0 | {
"file_path": "engine/display_list/testing/dl_test_surface_provider.cc",
"repo_id": "engine",
"token_count": 896
} | 164 |
// 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:flutter/material.dart';
import 'package:flutter/foundation.dart'
show debugDefaultTargetPlatformOverride;
import 'package:flutter_spinkit/flutter_spinkit.dart';
void main() {
// This is a hack to make Flutter think you are running on Google Fuchsia,
// otherwise you will get an error about running from an unsupported platform.
debugDefaultTargetPlatformOverride = TargetPlatform.fuchsia;
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key? key, required this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: RepaintBoundary(
child: SpinKitRotatingCircle(color: Colors.blue, size: 50.0),
),
),
);
}
}
| engine/examples/glfw_drm/main.dart/0 | {
"file_path": "engine/examples/glfw_drm/main.dart",
"repo_id": "engine",
"token_count": 946
} | 165 |
// 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.
#ifndef FLUTTER_FLOW_EMBEDDED_VIEWS_H_
#define FLUTTER_FLOW_EMBEDDED_VIEWS_H_
#include <memory>
#include <utility>
#include <vector>
#include "flutter/display_list/dl_builder.h"
#include "flutter/display_list/skia/dl_sk_canvas.h"
#include "flutter/flow/surface_frame.h"
#include "flutter/fml/memory/ref_counted.h"
#include "flutter/fml/raster_thread_merger.h"
#include "third_party/skia/include/core/SkMatrix.h"
#include "third_party/skia/include/core/SkPath.h"
#include "third_party/skia/include/core/SkRRect.h"
#include "third_party/skia/include/core/SkRect.h"
#include "third_party/skia/include/core/SkSize.h"
#if IMPELLER_SUPPORTS_RENDERING
#include "flutter/impeller/aiks/aiks_context.h" // nogncheck
#include "flutter/impeller/renderer/context.h" // nogncheck
#else // IMPELLER_SUPPORTS_RENDERING
namespace impeller {
class Context;
class AiksContext;
} // namespace impeller
#endif // !IMPELLER_SUPPORTS_RENDERING
class GrDirectContext;
namespace flutter {
enum MutatorType {
kClipRect,
kClipRRect,
kClipPath,
kTransform,
kOpacity,
kBackdropFilter
};
// Represents an image filter mutation.
//
// Should be used for image_filter_layer and backdrop_filter_layer.
// TODO(cyanglaz): Refactor this into a ImageFilterMutator class.
// https://github.com/flutter/flutter/issues/108470
class ImageFilterMutation {
public:
ImageFilterMutation(std::shared_ptr<const DlImageFilter> filter,
const SkRect& filter_rect)
: filter_(std::move(filter)), filter_rect_(filter_rect) {}
const DlImageFilter& GetFilter() const { return *filter_; }
const SkRect& GetFilterRect() const { return filter_rect_; }
bool operator==(const ImageFilterMutation& other) const {
return *filter_ == *other.filter_ && filter_rect_ == other.filter_rect_;
}
bool operator!=(const ImageFilterMutation& other) const {
return !operator==(other);
}
private:
std::shared_ptr<const DlImageFilter> filter_;
const SkRect filter_rect_;
};
// Stores mutation information like clipping or kTransform.
//
// The `type` indicates the type of the mutation: kClipRect, kTransform and etc.
// Each `type` is paired with an object that supports the mutation. For example,
// if the `type` is kClipRect, `rect()` is used the represent the rect to be
// clipped. One mutation object must only contain one type of mutation.
class Mutator {
public:
Mutator(const Mutator& other) {
type_ = other.type_;
switch (other.type_) {
case kClipRect:
rect_ = other.rect_;
break;
case kClipRRect:
rrect_ = other.rrect_;
break;
case kClipPath:
path_ = new SkPath(*other.path_);
break;
case kTransform:
matrix_ = other.matrix_;
break;
case kOpacity:
alpha_ = other.alpha_;
break;
case kBackdropFilter:
filter_mutation_ = other.filter_mutation_;
break;
default:
break;
}
}
explicit Mutator(const SkRect& rect) : type_(kClipRect), rect_(rect) {}
explicit Mutator(const SkRRect& rrect) : type_(kClipRRect), rrect_(rrect) {}
explicit Mutator(const SkPath& path)
: type_(kClipPath), path_(new SkPath(path)) {}
explicit Mutator(const SkMatrix& matrix)
: type_(kTransform), matrix_(matrix) {}
explicit Mutator(const int& alpha) : type_(kOpacity), alpha_(alpha) {}
explicit Mutator(const std::shared_ptr<const DlImageFilter>& filter,
const SkRect& filter_rect)
: type_(kBackdropFilter),
filter_mutation_(
std::make_shared<ImageFilterMutation>(filter, filter_rect)) {}
const MutatorType& GetType() const { return type_; }
const SkRect& GetRect() const { return rect_; }
const SkRRect& GetRRect() const { return rrect_; }
const SkPath& GetPath() const { return *path_; }
const SkMatrix& GetMatrix() const { return matrix_; }
const ImageFilterMutation& GetFilterMutation() const {
return *filter_mutation_;
}
const int& GetAlpha() const { return alpha_; }
float GetAlphaFloat() const { return (alpha_ / 255.0f); }
bool operator==(const Mutator& other) const {
if (type_ != other.type_) {
return false;
}
switch (type_) {
case kClipRect:
return rect_ == other.rect_;
case kClipRRect:
return rrect_ == other.rrect_;
case kClipPath:
return *path_ == *other.path_;
case kTransform:
return matrix_ == other.matrix_;
case kOpacity:
return alpha_ == other.alpha_;
case kBackdropFilter:
return *filter_mutation_ == *other.filter_mutation_;
}
return false;
}
bool operator!=(const Mutator& other) const { return !operator==(other); }
bool IsClipType() {
return type_ == kClipRect || type_ == kClipRRect || type_ == kClipPath;
}
~Mutator() {
if (type_ == kClipPath) {
delete path_;
}
};
private:
MutatorType type_;
// TODO(cyanglaz): Remove union.
// https://github.com/flutter/flutter/issues/108470
union {
SkRect rect_;
SkRRect rrect_;
SkMatrix matrix_;
SkPath* path_;
int alpha_;
};
std::shared_ptr<ImageFilterMutation> filter_mutation_;
}; // Mutator
// A stack of mutators that can be applied to an embedded platform view.
//
// The stack may include mutators like transforms and clips, each mutator
// applies to all the mutators that are below it in the stack and to the
// embedded view.
//
// For example consider the following stack: [T1, T2, T3], where T1 is the top
// of the stack and T3 is the bottom of the stack. Applying this mutators stack
// to a platform view P1 will result in T1(T2(T3(P1))).
class MutatorsStack {
public:
MutatorsStack() = default;
void PushClipRect(const SkRect& rect);
void PushClipRRect(const SkRRect& rrect);
void PushClipPath(const SkPath& path);
void PushTransform(const SkMatrix& matrix);
void PushOpacity(const int& alpha);
// `filter_rect` is in global coordinates.
void PushBackdropFilter(const std::shared_ptr<const DlImageFilter>& filter,
const SkRect& filter_rect);
// Removes the `Mutator` on the top of the stack
// and destroys it.
void Pop();
void PopTo(size_t stack_count);
// Returns a reverse iterator pointing to the top of the stack, which is the
// mutator that is furtherest from the leaf node.
const std::vector<std::shared_ptr<Mutator>>::const_reverse_iterator Top()
const;
// Returns a reverse iterator pointing to the bottom of the stack, which is
// the mutator that is closeset from the leaf node.
const std::vector<std::shared_ptr<Mutator>>::const_reverse_iterator Bottom()
const;
// Returns an iterator pointing to the beginning of the mutator vector, which
// is the mutator that is furtherest from the leaf node.
const std::vector<std::shared_ptr<Mutator>>::const_iterator Begin() const;
// Returns an iterator pointing to the end of the mutator vector, which is the
// mutator that is closest from the leaf node.
const std::vector<std::shared_ptr<Mutator>>::const_iterator End() const;
bool is_empty() const { return vector_.empty(); }
size_t stack_count() const { return vector_.size(); }
bool operator==(const MutatorsStack& other) const {
if (vector_.size() != other.vector_.size()) {
return false;
}
for (size_t i = 0; i < vector_.size(); i++) {
if (*vector_[i] != *other.vector_[i]) {
return false;
}
}
return true;
}
bool operator==(const std::vector<Mutator>& other) const {
if (vector_.size() != other.size()) {
return false;
}
for (size_t i = 0; i < vector_.size(); i++) {
if (*vector_[i] != other[i]) {
return false;
}
}
return true;
}
bool operator!=(const MutatorsStack& other) const {
return !operator==(other);
}
bool operator!=(const std::vector<Mutator>& other) const {
return !operator==(other);
}
private:
std::vector<std::shared_ptr<Mutator>> vector_;
}; // MutatorsStack
class EmbeddedViewParams {
public:
EmbeddedViewParams() = default;
EmbeddedViewParams(SkMatrix matrix,
SkSize size_points,
MutatorsStack mutators_stack)
: matrix_(matrix),
size_points_(size_points),
mutators_stack_(std::move(mutators_stack)) {
SkPath path;
SkRect starting_rect = SkRect::MakeSize(size_points);
path.addRect(starting_rect);
path.transform(matrix);
final_bounding_rect_ = path.getBounds();
}
// The transformation Matrix corresponding to the sum of all the
// transformations in the platform view's mutator stack.
const SkMatrix& transformMatrix() const { return matrix_; };
// The original size of the platform view before any mutation matrix is
// applied.
const SkSize& sizePoints() const { return size_points_; };
// The mutators stack contains the detailed step by step mutations for this
// platform view.
const MutatorsStack& mutatorsStack() const { return mutators_stack_; };
// The bounding rect of the platform view after applying all the mutations.
//
// Clippings are ignored.
const SkRect& finalBoundingRect() const { return final_bounding_rect_; }
// Pushes the stored DlImageFilter object to the mutators stack.
//
// `filter_rect` is in global coordinates.
void PushImageFilter(const std::shared_ptr<const DlImageFilter>& filter,
const SkRect& filter_rect) {
mutators_stack_.PushBackdropFilter(filter, filter_rect);
}
bool operator==(const EmbeddedViewParams& other) const {
return size_points_ == other.size_points_ &&
mutators_stack_ == other.mutators_stack_ &&
final_bounding_rect_ == other.final_bounding_rect_ &&
matrix_ == other.matrix_;
}
private:
SkMatrix matrix_;
SkSize size_points_;
MutatorsStack mutators_stack_;
SkRect final_bounding_rect_;
};
enum class PostPrerollResult {
// Frame has successfully rasterized.
kSuccess,
// Frame is submitted twice. This is currently only used when
// thread configuration change occurs.
kResubmitFrame,
// Frame is dropped and a new frame with the same layer tree is
// attempted. This is currently only used when thread configuration
// change occurs.
kSkipAndRetryFrame
};
// The |EmbedderViewSlice| represents the details of recording all of
// the layer tree rendering operations that appear between before, after
// and between the embedded views. The Slice used to abstract away
// implementations that were based on either an SkPicture or a
// DisplayListBuilder but more recently all of the embedder recordings
// have standardized on the DisplayList.
class EmbedderViewSlice {
public:
virtual ~EmbedderViewSlice() = default;
virtual DlCanvas* canvas() = 0;
virtual void end_recording() = 0;
virtual const DlRegion& getRegion() const = 0;
DlRegion region(const SkRect& query) const {
return DlRegion::MakeIntersection(getRegion(), DlRegion(query.roundOut()));
}
virtual void render_into(DlCanvas* canvas) = 0;
};
class DisplayListEmbedderViewSlice : public EmbedderViewSlice {
public:
explicit DisplayListEmbedderViewSlice(SkRect view_bounds);
~DisplayListEmbedderViewSlice() override = default;
DlCanvas* canvas() override;
void end_recording() override;
const DlRegion& getRegion() const override;
void render_into(DlCanvas* canvas) override;
void dispatch(DlOpReceiver& receiver);
bool is_empty();
bool recording_ended();
private:
std::unique_ptr<DisplayListBuilder> builder_;
sk_sp<DisplayList> display_list_;
};
// Facilitates embedding of platform views within the flow layer tree.
//
// Used on iOS, Android (hybrid composite mode), and on embedded platforms
// that provide a system compositor as part of the project arguments.
//
// There are two kinds of "view IDs" in the context of ExternalViewEmbedder, and
// specific names are used to avoid ambiguation:
//
// * ExternalViewEmbedder composites a stack of layers. Each layer's content
// might be from Flutter widgets, or a platform view, which displays platform
// native components. Each platform view is labeled by a view ID, which
// corresponds to the ID from `PlatformViewsRegistry.getNextPlatformViewId`
// from the framework. In the context of `ExternalViewEmbedder`, this ID is
// called platform_view_id.
// * The layers are compositied into a single rectangular surface, displayed by
// taking up an entire native window or part of a window. Each such surface
// is labeled by a view ID, which corresponds to `FlutterView.viewID` from
// dart:ui. In the context of `ExternalViewEmbedder`, this ID is called
// flutter_view_id.
//
// The lifecycle of drawing a frame using ExternalViewEmbedder is:
//
// 1. At the start of a frame, call |BeginFrame|, then |SetUsedThisFrame| to
// true.
// 2. For each view to be drawn, call |PrepareFlutterView|, then
// |SubmitFlutterView|.
// 3. At the end of a frame, if |GetUsedThisFrame| is true, call |EndFrame|.
class ExternalViewEmbedder {
// TODO(cyanglaz): Make embedder own the `EmbeddedViewParams`.
public:
ExternalViewEmbedder() = default;
virtual ~ExternalViewEmbedder() = default;
// Usually, the root canvas is not owned by the view embedder. However, if
// the view embedder wants to provide a canvas to the rasterizer, it may
// return one here. This canvas takes priority over the canvas materialized
// from the on-screen render target.
virtual DlCanvas* GetRootCanvas() = 0;
// Call this in-lieu of |SubmitFlutterView| to clear pre-roll state and
// sets the stage for the next pre-roll.
virtual void CancelFrame() = 0;
// Indicates the beginning of a frame.
//
// The `raster_thread_merger` will be null if |SupportsDynamicThreadMerging|
// returns false.
virtual void BeginFrame(
GrDirectContext* context,
const fml::RefPtr<fml::RasterThreadMerger>& raster_thread_merger) = 0;
virtual void PrerollCompositeEmbeddedView(
int64_t platform_view_id,
std::unique_ptr<EmbeddedViewParams> params) = 0;
// This needs to get called after |Preroll| finishes on the layer tree.
// Returns kResubmitFrame if the frame needs to be processed again, this is
// after it does any requisite tasks needed to bring itself to a valid state.
// Returns kSuccess if the view embedder is already in a valid state.
virtual PostPrerollResult PostPrerollAction(
const fml::RefPtr<fml::RasterThreadMerger>& raster_thread_merger) {
return PostPrerollResult::kSuccess;
}
// Must be called on the UI thread.
virtual DlCanvas* CompositeEmbeddedView(int64_t platform_view_id) = 0;
// Prepare for a view to be drawn.
virtual void PrepareFlutterView(int64_t flutter_view_id,
SkISize frame_size,
double device_pixel_ratio) = 0;
// Implementers must submit the frame by calling frame.Submit().
//
// This method can mutate the root Skia canvas before submitting the frame.
//
// It can also allocate frames for overlay surfaces to compose hybrid views.
virtual void SubmitFlutterView(
GrDirectContext* context,
const std::shared_ptr<impeller::AiksContext>& aiks_context,
std::unique_ptr<SurfaceFrame> frame);
// This method provides the embedder a way to do additional tasks after
// |SubmitFrame|. For example, merge task runners if `should_resubmit_frame`
// is true.
//
// For example on the iOS embedder, threads are merged in this call.
// A new frame on the platform thread starts immediately. If the GPU thread
// still has some task running, there could be two frames being rendered
// concurrently, which causes undefined behaviors.
//
// The `raster_thread_merger` will be null if |SupportsDynamicThreadMerging|
// returns false.
virtual void EndFrame(
bool should_resubmit_frame,
const fml::RefPtr<fml::RasterThreadMerger>& raster_thread_merger) {}
// Whether the embedder should support dynamic thread merging.
//
// Returning `true` results a |RasterThreadMerger| instance to be created.
// * See also |BegineFrame| and |EndFrame| for getting the
// |RasterThreadMerger| instance.
virtual bool SupportsDynamicThreadMerging();
// Called when the rasterizer is being torn down.
// This method provides a way to release resources associated with the current
// embedder.
virtual void Teardown();
// Change the flag about whether it is used in this frame, it will be set to
// true when 'BeginFrame' and false when 'EndFrame'.
void SetUsedThisFrame(bool used_this_frame) {
used_this_frame_ = used_this_frame;
}
// Whether it is used in this frame, returns true between 'BeginFrame' and
// 'EndFrame', otherwise returns false.
bool GetUsedThisFrame() const { return used_this_frame_; }
// Pushes the platform view id of a visited platform view to a list of
// visited platform views.
virtual void PushVisitedPlatformView(int64_t platform_view_id) {}
// Pushes a DlImageFilter object to each platform view within a list of
// visited platform views.
//
// `filter_rect` is in global coordinates.
//
// See also: |PushVisitedPlatformView| for pushing platform view ids to the
// visited platform views list.
virtual void PushFilterToVisitedPlatformViews(
const std::shared_ptr<const DlImageFilter>& filter,
const SkRect& filter_rect) {}
private:
bool used_this_frame_ = false;
FML_DISALLOW_COPY_AND_ASSIGN(ExternalViewEmbedder);
}; // ExternalViewEmbedder
} // namespace flutter
#endif // FLUTTER_FLOW_EMBEDDED_VIEWS_H_
| engine/flow/embedded_views.h/0 | {
"file_path": "engine/flow/embedded_views.h",
"repo_id": "engine",
"token_count": 6084
} | 166 |
// 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.
#include "flutter/flow/layers/clip_path_layer.h"
namespace flutter {
ClipPathLayer::ClipPathLayer(const SkPath& clip_path, Clip clip_behavior)
: ClipShapeLayer(clip_path, clip_behavior) {}
const SkRect& ClipPathLayer::clip_shape_bounds() const {
return clip_shape().getBounds();
}
void ClipPathLayer::ApplyClip(LayerStateStack::MutatorContext& mutator) const {
mutator.clipPath(clip_shape(), clip_behavior() != Clip::kHardEdge);
}
} // namespace flutter
| engine/flow/layers/clip_path_layer.cc/0 | {
"file_path": "engine/flow/layers/clip_path_layer.cc",
"repo_id": "engine",
"token_count": 201
} | 167 |
// 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.
#include "flutter/flow/layers/display_list_layer.h"
#include <utility>
#include "flutter/display_list/dl_builder.h"
#include "flutter/flow/layer_snapshot_store.h"
#include "flutter/flow/layers/cacheable_layer.h"
#include "flutter/flow/layers/offscreen_surface.h"
#include "flutter/flow/raster_cache.h"
#include "flutter/flow/raster_cache_util.h"
namespace flutter {
DisplayListLayer::DisplayListLayer(const SkPoint& offset,
sk_sp<DisplayList> display_list,
bool is_complex,
bool will_change)
: offset_(offset), display_list_(std::move(display_list)) {
if (display_list_) {
bounds_ = display_list_->bounds().makeOffset(offset_.x(), offset_.y());
display_list_raster_cache_item_ = DisplayListRasterCacheItem::Make(
display_list_, offset_, is_complex, will_change);
}
}
bool DisplayListLayer::IsReplacing(DiffContext* context,
const Layer* layer) const {
// Only return true for identical display lists; This way
// ContainerLayer::DiffChildren can detect when a display list layer
// got inserted between other display list layers
auto old_layer = layer->as_display_list_layer();
return old_layer != nullptr && offset_ == old_layer->offset_ &&
Compare(context->statistics(), this, old_layer);
}
void DisplayListLayer::Diff(DiffContext* context, const Layer* old_layer) {
DiffContext::AutoSubtreeRestore subtree(context);
if (!context->IsSubtreeDirty()) {
#ifndef NDEBUG
FML_DCHECK(old_layer);
auto prev = old_layer->as_display_list_layer();
DiffContext::Statistics dummy_statistics;
// IsReplacing has already determined that the display list is same
FML_DCHECK(prev->offset_ == offset_ &&
Compare(dummy_statistics, this, prev));
#endif
}
context->PushTransform(SkMatrix::Translate(offset_.x(), offset_.y()));
if (context->has_raster_cache()) {
context->WillPaintWithIntegralTransform();
}
context->AddLayerBounds(display_list()->bounds());
context->SetLayerPaintRegion(this, context->CurrentSubtreeRegion());
}
bool DisplayListLayer::Compare(DiffContext::Statistics& statistics,
const DisplayListLayer* l1,
const DisplayListLayer* l2) {
const auto& dl1 = l1->display_list_;
const auto& dl2 = l2->display_list_;
if (dl1.get() == dl2.get()) {
statistics.AddSameInstancePicture();
return true;
}
const auto op_cnt_1 = dl1->op_count();
const auto op_cnt_2 = dl2->op_count();
const auto op_bytes_1 = dl1->bytes();
const auto op_bytes_2 = dl2->bytes();
if (op_cnt_1 != op_cnt_2 || op_bytes_1 != op_bytes_2 ||
dl1->bounds() != dl2->bounds()) {
statistics.AddNewPicture();
return false;
}
if (op_bytes_1 > kMaxBytesToCompare) {
statistics.AddPictureTooComplexToCompare();
return false;
}
statistics.AddDeepComparePicture();
auto res = dl1->Equals(*dl2);
if (res) {
statistics.AddDifferentInstanceButEqualPicture();
} else {
statistics.AddNewPicture();
}
return res;
}
void DisplayListLayer::Preroll(PrerollContext* context) {
DisplayList* disp_list = display_list();
AutoCache cache = AutoCache(display_list_raster_cache_item_.get(), context,
context->state_stack.transform_3x3());
if (disp_list->can_apply_group_opacity()) {
context->renderable_state_flags = LayerStateStack::kCallerCanApplyOpacity;
}
set_paint_bounds(bounds_);
}
void DisplayListLayer::Paint(PaintContext& context) const {
FML_DCHECK(display_list_);
FML_DCHECK(needs_painting(context));
auto mutator = context.state_stack.save();
mutator.translate(offset_.x(), offset_.y());
if (context.raster_cache) {
// Always apply the integral transform in the presence of a raster cache
// whether or not we successfully draw from the cache
mutator.integralTransform();
if (display_list_raster_cache_item_) {
DlPaint paint;
if (display_list_raster_cache_item_->Draw(
context, context.state_stack.fill(paint))) {
TRACE_EVENT_INSTANT0("flutter", "raster cache hit");
return;
}
}
}
SkScalar opacity = context.state_stack.outstanding_opacity();
if (context.enable_leaf_layer_tracing) {
const auto canvas_size = context.canvas->GetBaseLayerSize();
auto offscreen_surface =
std::make_unique<OffscreenSurface>(context.gr_context, canvas_size);
const auto& ctm = context.canvas->GetTransform();
const auto start_time = fml::TimePoint::Now();
{
// render display list to offscreen surface.
auto* canvas = offscreen_surface->GetCanvas();
{
DlAutoCanvasRestore save(canvas, true);
canvas->Clear(DlColor::kTransparent());
canvas->SetTransform(ctm);
canvas->DrawDisplayList(display_list_, opacity);
}
canvas->Flush();
}
const fml::TimeDelta offscreen_render_time =
fml::TimePoint::Now() - start_time;
const SkRect device_bounds =
RasterCacheUtil::GetDeviceBounds(paint_bounds(), ctm);
sk_sp<SkData> raster_data = offscreen_surface->GetRasterData(true);
LayerSnapshotData snapshot_data(unique_id(), offscreen_render_time,
raster_data, device_bounds);
context.layer_snapshot_store->Add(snapshot_data);
}
context.canvas->DrawDisplayList(display_list_, opacity);
}
} // namespace flutter
| engine/flow/layers/display_list_layer.cc/0 | {
"file_path": "engine/flow/layers/display_list_layer.cc",
"repo_id": "engine",
"token_count": 2202
} | 168 |
// 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.
#ifndef FLUTTER_FLOW_LAYERS_LAYER_TREE_H_
#define FLUTTER_FLOW_LAYERS_LAYER_TREE_H_
#include <cstdint>
#include <memory>
#include "flutter/common/graphics/texture.h"
#include "flutter/flow/compositor_context.h"
#include "flutter/flow/layers/layer.h"
#include "flutter/flow/raster_cache.h"
#include "flutter/fml/macros.h"
#include "flutter/fml/time/time_delta.h"
class GrDirectContext;
namespace flutter {
class LayerTree {
public:
struct Config {
std::shared_ptr<Layer> root_layer;
uint32_t rasterizer_tracing_threshold = 0;
bool checkerboard_raster_cache_images = false;
bool checkerboard_offscreen_layers = false;
};
LayerTree(const Config& config, const SkISize& frame_size);
// Perform a preroll pass on the tree and return information about
// the tree that affects rendering this frame.
//
// Returns:
// - a boolean indicating whether or not the top level of the
// layer tree performs any operations that require readback
// from the root surface.
bool Preroll(CompositorContext::ScopedFrame& frame,
bool ignore_raster_cache = false,
SkRect cull_rect = kGiantRect);
static void TryToRasterCache(
const std::vector<RasterCacheItem*>& raster_cached_entries,
const PaintContext* paint_context,
bool ignore_raster_cache = false);
void Paint(CompositorContext::ScopedFrame& frame,
bool ignore_raster_cache = false) const;
sk_sp<DisplayList> Flatten(
const SkRect& bounds,
const std::shared_ptr<TextureRegistry>& texture_registry = nullptr,
GrDirectContext* gr_context = nullptr);
Layer* root_layer() const { return root_layer_.get(); }
const SkISize& frame_size() const { return frame_size_; }
const PaintRegionMap& paint_region_map() const { return paint_region_map_; }
PaintRegionMap& paint_region_map() { return paint_region_map_; }
// The number of frame intervals missed after which the compositor must
// trace the rasterized picture to a trace file. 0 stands for disabling all
// tracing.
uint32_t rasterizer_tracing_threshold() const {
return rasterizer_tracing_threshold_;
}
/// When `Paint` is called, if leaf layer tracing is enabled, additional
/// metadata around raterization of leaf layers is collected.
///
/// This is not supported in the Impeller backend.
///
/// See: `LayerSnapshotStore`
void enable_leaf_layer_tracing(bool enable) {
enable_leaf_layer_tracing_ = enable;
}
bool is_leaf_layer_tracing_enabled() const {
return enable_leaf_layer_tracing_;
}
private:
std::shared_ptr<Layer> root_layer_;
SkISize frame_size_ = SkISize::MakeEmpty(); // Physical pixels.
uint32_t rasterizer_tracing_threshold_;
bool checkerboard_raster_cache_images_;
bool checkerboard_offscreen_layers_;
bool enable_leaf_layer_tracing_ = false;
PaintRegionMap paint_region_map_;
std::vector<RasterCacheItem*> raster_cache_items_;
FML_DISALLOW_COPY_AND_ASSIGN(LayerTree);
};
// The information to draw a layer tree to a specified view.
struct LayerTreeTask {
public:
LayerTreeTask(int64_t view_id,
std::unique_ptr<LayerTree> layer_tree,
float device_pixel_ratio)
: view_id(view_id),
layer_tree(std::move(layer_tree)),
device_pixel_ratio(device_pixel_ratio) {}
/// The target view to draw to.
int64_t view_id;
/// The target layer tree to be drawn.
std::unique_ptr<LayerTree> layer_tree;
/// The pixel ratio of the target view.
float device_pixel_ratio;
private:
FML_DISALLOW_COPY_AND_ASSIGN(LayerTreeTask);
};
} // namespace flutter
#endif // FLUTTER_FLOW_LAYERS_LAYER_TREE_H_
| engine/flow/layers/layer_tree.h/0 | {
"file_path": "engine/flow/layers/layer_tree.h",
"repo_id": "engine",
"token_count": 1364
} | 169 |
// 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.
#include "flutter/flow/layers/shader_mask_layer.h"
#include "flutter/flow/layers/layer_tree.h"
#include "flutter/flow/layers/opacity_layer.h"
#include "flutter/flow/raster_cache.h"
#include "flutter/flow/raster_cache_util.h"
#include "flutter/flow/testing/layer_test.h"
#include "flutter/flow/testing/mock_layer.h"
#include "flutter/fml/macros.h"
#include "gtest/gtest.h"
// TODO(zanderso): https://github.com/flutter/flutter/issues/127701
// NOLINTBEGIN(bugprone-unchecked-optional-access)
namespace flutter {
namespace testing {
using ShaderMaskLayerTest = LayerTest;
static std::shared_ptr<DlColorSource> MakeFilter(DlColor color) {
DlColor colors[] = {
color.withAlpha(0x7f),
color,
};
float stops[] = {
0,
1,
};
return DlColorSource::MakeLinear(SkPoint::Make(0, 0), SkPoint::Make(10, 10),
2, colors, stops, DlTileMode::kRepeat);
}
#ifndef NDEBUG
TEST_F(ShaderMaskLayerTest, PaintingEmptyLayerDies) {
auto layer =
std::make_shared<ShaderMaskLayer>(nullptr, kEmptyRect, DlBlendMode::kSrc);
layer->Preroll(preroll_context());
EXPECT_EQ(layer->paint_bounds(), kEmptyRect);
EXPECT_EQ(layer->child_paint_bounds(), kEmptyRect);
EXPECT_FALSE(layer->needs_painting(paint_context()));
EXPECT_DEATH_IF_SUPPORTED(layer->Paint(paint_context()),
"needs_painting\\(context\\)");
}
TEST_F(ShaderMaskLayerTest, PaintBeforePrerollDies) {
const SkRect child_bounds = SkRect::MakeLTRB(5.0f, 6.0f, 20.5f, 21.5f);
const SkPath child_path = SkPath().addRect(child_bounds);
auto mock_layer = std::make_shared<MockLayer>(child_path);
auto layer =
std::make_shared<ShaderMaskLayer>(nullptr, kEmptyRect, DlBlendMode::kSrc);
layer->Add(mock_layer);
EXPECT_EQ(layer->paint_bounds(), kEmptyRect);
EXPECT_EQ(layer->child_paint_bounds(), kEmptyRect);
EXPECT_DEATH_IF_SUPPORTED(layer->Paint(paint_context()),
"needs_painting\\(context\\)");
}
#endif
TEST_F(ShaderMaskLayerTest, EmptyFilter) {
const SkMatrix initial_transform = SkMatrix::Translate(0.5f, 1.0f);
const SkRect child_bounds = SkRect::MakeLTRB(5.0f, 6.0f, 20.5f, 21.5f);
const SkRect layer_bounds = SkRect::MakeLTRB(2.0f, 4.0f, 6.5f, 6.5f);
const SkPath child_path = SkPath().addRect(child_bounds);
const DlPaint child_paint = DlPaint(DlColor::kYellow());
auto mock_layer = std::make_shared<MockLayer>(child_path, child_paint);
auto layer = std::make_shared<ShaderMaskLayer>(nullptr, layer_bounds,
DlBlendMode::kSrc);
layer->Add(mock_layer);
preroll_context()->state_stack.set_preroll_delegate(initial_transform);
layer->Preroll(preroll_context());
EXPECT_EQ(mock_layer->paint_bounds(), child_bounds);
EXPECT_EQ(layer->paint_bounds(), child_bounds);
EXPECT_EQ(layer->child_paint_bounds(), child_bounds);
EXPECT_TRUE(mock_layer->needs_painting(paint_context()));
EXPECT_TRUE(layer->needs_painting(paint_context()));
EXPECT_EQ(mock_layer->parent_matrix(), initial_transform);
DlPaint filter_paint;
filter_paint.setBlendMode(DlBlendMode::kSrc);
filter_paint.setColorSource(nullptr);
layer->Paint(display_list_paint_context());
DisplayListBuilder expected_builder;
/* (ShaderMask)layer::Paint */ {
expected_builder.Save();
{
expected_builder.SaveLayer(&child_bounds);
{
/* mock_layer::Paint */ {
expected_builder.DrawPath(child_path, child_paint);
}
expected_builder.Translate(layer_bounds.fLeft, layer_bounds.fTop);
expected_builder.DrawRect(
SkRect::MakeWH(layer_bounds.width(), layer_bounds.height()),
filter_paint);
}
expected_builder.Restore();
}
expected_builder.Restore();
}
EXPECT_TRUE(DisplayListsEQ_Verbose(display_list(), expected_builder.Build()));
}
TEST_F(ShaderMaskLayerTest, SimpleFilter) {
const SkMatrix initial_transform = SkMatrix::Translate(0.5f, 1.0f);
const SkRect child_bounds = SkRect::MakeLTRB(5.0f, 6.0f, 20.5f, 21.5f);
const SkRect layer_bounds = SkRect::MakeLTRB(2.0f, 4.0f, 6.5f, 6.5f);
const SkPath child_path = SkPath().addRect(child_bounds);
const DlPaint child_paint = DlPaint(DlColor::kYellow());
auto dl_filter = MakeFilter(DlColor::kBlue());
auto mock_layer = std::make_shared<MockLayer>(child_path, child_paint);
auto layer = std::make_shared<ShaderMaskLayer>(dl_filter, layer_bounds,
DlBlendMode::kSrc);
layer->Add(mock_layer);
preroll_context()->state_stack.set_preroll_delegate(initial_transform);
layer->Preroll(preroll_context());
EXPECT_EQ(layer->paint_bounds(), child_bounds);
EXPECT_EQ(layer->child_paint_bounds(), child_bounds);
EXPECT_TRUE(layer->needs_painting(paint_context()));
EXPECT_EQ(mock_layer->parent_matrix(), initial_transform);
DlPaint filter_paint;
filter_paint.setBlendMode(DlBlendMode::kSrc);
filter_paint.setColorSource(dl_filter);
layer->Paint(display_list_paint_context());
DisplayListBuilder expected_builder;
/* (ShaderMask)layer::Paint */ {
expected_builder.Save();
{
expected_builder.SaveLayer(&child_bounds);
{
/* mock_layer::Paint */ {
expected_builder.DrawPath(child_path, child_paint);
}
expected_builder.Translate(layer_bounds.fLeft, layer_bounds.fTop);
expected_builder.DrawRect(
SkRect::MakeWH(layer_bounds.width(), layer_bounds.height()),
filter_paint);
}
expected_builder.Restore();
}
expected_builder.Restore();
}
EXPECT_TRUE(DisplayListsEQ_Verbose(display_list(), expected_builder.Build()));
}
TEST_F(ShaderMaskLayerTest, MultipleChildren) {
const SkMatrix initial_transform = SkMatrix::Translate(0.5f, 1.0f);
const SkRect child_bounds = SkRect::MakeLTRB(5.0f, 6.0f, 20.5f, 21.5f);
const SkRect layer_bounds = SkRect::MakeLTRB(2.0f, 4.0f, 6.5f, 6.5f);
const SkPath child_path1 = SkPath().addRect(child_bounds);
const SkPath child_path2 =
SkPath().addRect(child_bounds.makeOffset(3.0f, 0.0f));
const DlPaint child_paint1 = DlPaint(DlColor::kYellow());
const DlPaint child_paint2 = DlPaint(DlColor::kCyan());
auto dl_filter = MakeFilter(DlColor::kBlue());
auto mock_layer1 = std::make_shared<MockLayer>(child_path1, child_paint1);
auto mock_layer2 = std::make_shared<MockLayer>(child_path2, child_paint2);
auto layer = std::make_shared<ShaderMaskLayer>(dl_filter, layer_bounds,
DlBlendMode::kSrc);
layer->Add(mock_layer1);
layer->Add(mock_layer2);
SkRect children_bounds = child_path1.getBounds();
children_bounds.join(child_path2.getBounds());
preroll_context()->state_stack.set_preroll_delegate(initial_transform);
layer->Preroll(preroll_context());
EXPECT_EQ(mock_layer1->paint_bounds(), child_path1.getBounds());
EXPECT_EQ(mock_layer2->paint_bounds(), child_path2.getBounds());
EXPECT_EQ(layer->paint_bounds(), children_bounds);
EXPECT_EQ(layer->child_paint_bounds(), children_bounds);
EXPECT_TRUE(mock_layer1->needs_painting(paint_context()));
EXPECT_TRUE(mock_layer2->needs_painting(paint_context()));
EXPECT_TRUE(layer->needs_painting(paint_context()));
EXPECT_EQ(mock_layer1->parent_matrix(), initial_transform);
EXPECT_EQ(mock_layer2->parent_matrix(), initial_transform);
DlPaint filter_paint;
filter_paint.setBlendMode(DlBlendMode::kSrc);
filter_paint.setColorSource(dl_filter);
layer->Paint(display_list_paint_context());
DisplayListBuilder expected_builder;
/* (ShaderMask)layer::Paint */ {
expected_builder.Save();
{
expected_builder.SaveLayer(&children_bounds);
{
/* mock_layer1::Paint */ {
expected_builder.DrawPath(child_path1, child_paint1);
}
/* mock_layer2::Paint */ {
expected_builder.DrawPath(child_path2, child_paint2);
}
expected_builder.Translate(layer_bounds.fLeft, layer_bounds.fTop);
expected_builder.DrawRect(
SkRect::MakeWH(layer_bounds.width(), layer_bounds.height()),
filter_paint);
}
expected_builder.Restore();
}
expected_builder.Restore();
}
EXPECT_TRUE(DisplayListsEQ_Verbose(display_list(), expected_builder.Build()));
}
TEST_F(ShaderMaskLayerTest, Nested) {
const SkMatrix initial_transform = SkMatrix::Translate(0.5f, 1.0f);
const SkRect child_bounds = SkRect::MakeLTRB(5.0f, 6.0f, 7.5f, 8.5f);
const SkRect layer_bounds = SkRect::MakeLTRB(2.0f, 4.0f, 20.5f, 20.5f);
const SkPath child_path1 = SkPath().addRect(child_bounds);
const SkPath child_path2 =
SkPath().addRect(child_bounds.makeOffset(3.0f, 0.0f));
const DlPaint child_paint1 = DlPaint(DlColor::kYellow());
const DlPaint child_paint2 = DlPaint(DlColor::kCyan());
auto dl_filter1 = MakeFilter(DlColor::kGreen());
auto dl_filter2 = MakeFilter(DlColor::kMagenta());
auto mock_layer1 = std::make_shared<MockLayer>(child_path1, child_paint1);
auto mock_layer2 = std::make_shared<MockLayer>(child_path2, child_paint2);
auto layer1 = std::make_shared<ShaderMaskLayer>(dl_filter1, layer_bounds,
DlBlendMode::kSrc);
auto layer2 = std::make_shared<ShaderMaskLayer>(dl_filter2, layer_bounds,
DlBlendMode::kSrc);
layer2->Add(mock_layer2);
layer1->Add(mock_layer1);
layer1->Add(layer2);
SkRect children_bounds = child_path1.getBounds();
children_bounds.join(child_path2.getBounds());
preroll_context()->state_stack.set_preroll_delegate(initial_transform);
layer1->Preroll(preroll_context());
EXPECT_EQ(mock_layer1->paint_bounds(), child_path1.getBounds());
EXPECT_EQ(mock_layer2->paint_bounds(), child_path2.getBounds());
EXPECT_EQ(layer1->paint_bounds(), children_bounds);
EXPECT_EQ(layer1->child_paint_bounds(), children_bounds);
EXPECT_EQ(layer2->paint_bounds(), mock_layer2->paint_bounds());
EXPECT_EQ(layer2->child_paint_bounds(), mock_layer2->paint_bounds());
EXPECT_TRUE(mock_layer1->needs_painting(paint_context()));
EXPECT_TRUE(mock_layer2->needs_painting(paint_context()));
EXPECT_TRUE(layer1->needs_painting(paint_context()));
EXPECT_TRUE(layer2->needs_painting(paint_context()));
EXPECT_EQ(mock_layer1->parent_matrix(), initial_transform);
EXPECT_EQ(mock_layer2->parent_matrix(), initial_transform);
DlPaint filter_paint1, filter_paint2;
filter_paint1.setBlendMode(DlBlendMode::kSrc);
filter_paint2.setBlendMode(DlBlendMode::kSrc);
filter_paint1.setColorSource(dl_filter1);
filter_paint2.setColorSource(dl_filter2);
layer1->Paint(display_list_paint_context());
DisplayListBuilder expected_builder;
/* (ShaderMask)layer1::Paint */ {
expected_builder.Save();
{
expected_builder.SaveLayer(&children_bounds);
{
/* mock_layer1::Paint */ {
expected_builder.DrawPath(child_path1, child_paint1);
}
/* (ShaderMask)layer2::Paint */ {
expected_builder.Save();
{
expected_builder.SaveLayer(&child_path2.getBounds());
{
/* mock_layer2::Paint */ {
expected_builder.DrawPath(child_path2, child_paint2);
}
expected_builder.Translate(layer_bounds.fLeft, layer_bounds.fTop);
expected_builder.DrawRect(
SkRect::MakeWH(layer_bounds.width(), layer_bounds.height()),
filter_paint2);
}
expected_builder.Restore();
}
expected_builder.Restore();
}
expected_builder.Translate(layer_bounds.fLeft, layer_bounds.fTop);
expected_builder.DrawRect(
SkRect::MakeWH(layer_bounds.width(), layer_bounds.height()),
filter_paint1);
}
expected_builder.Restore();
}
expected_builder.Restore();
}
EXPECT_TRUE(DisplayListsEQ_Verbose(display_list(), expected_builder.Build()));
}
TEST_F(ShaderMaskLayerTest, Readback) {
const SkRect layer_bounds = SkRect::MakeLTRB(2.0f, 4.0f, 20.5f, 20.5f);
auto dl_filter = MakeFilter(DlColor::kBlue());
auto layer = std::make_shared<ShaderMaskLayer>(dl_filter, layer_bounds,
DlBlendMode::kSrc);
// ShaderMaskLayer does not read from surface
preroll_context()->surface_needs_readback = false;
layer->Preroll(preroll_context());
EXPECT_FALSE(preroll_context()->surface_needs_readback);
// ShaderMaskLayer blocks child with readback
auto mock_layer = std::make_shared<MockLayer>(SkPath(), DlPaint());
mock_layer->set_fake_reads_surface(true);
layer->Add(mock_layer);
preroll_context()->surface_needs_readback = false;
layer->Preroll(preroll_context());
EXPECT_FALSE(preroll_context()->surface_needs_readback);
}
TEST_F(ShaderMaskLayerTest, LayerCached) {
auto dl_filter = MakeFilter(DlColor::kBlue());
DlPaint paint;
const SkRect layer_bounds = SkRect::MakeLTRB(2.0f, 4.0f, 20.5f, 20.5f);
auto initial_transform = SkMatrix::Translate(50.0, 25.5);
const SkPath child_path = SkPath().addRect(SkRect::MakeWH(5.0f, 5.0f));
auto mock_layer = std::make_shared<MockLayer>(child_path);
auto layer = std::make_shared<ShaderMaskLayer>(dl_filter, layer_bounds,
DlBlendMode::kSrc);
layer->Add(mock_layer);
SkMatrix cache_ctm = initial_transform;
DisplayListBuilder cache_canvas;
cache_canvas.Transform(cache_ctm);
use_mock_raster_cache();
preroll_context()->state_stack.set_preroll_delegate(initial_transform);
const auto* cacheable_shader_masker_item = layer->raster_cache_item();
EXPECT_EQ(raster_cache()->GetLayerCachedEntriesCount(), (size_t)0);
EXPECT_EQ(cacheable_shader_masker_item->cache_state(),
RasterCacheItem::CacheState::kNone);
EXPECT_FALSE(cacheable_shader_masker_item->GetId().has_value());
// frame 1.
layer->Preroll(preroll_context());
LayerTree::TryToRasterCache(cacheable_items(), &paint_context());
EXPECT_EQ(raster_cache()->GetLayerCachedEntriesCount(), (size_t)0);
EXPECT_EQ(cacheable_shader_masker_item->cache_state(),
RasterCacheItem::CacheState::kNone);
EXPECT_FALSE(cacheable_shader_masker_item->GetId().has_value());
// frame 2.
layer->Preroll(preroll_context());
LayerTree::TryToRasterCache(cacheable_items(), &paint_context());
EXPECT_EQ(raster_cache()->GetLayerCachedEntriesCount(), (size_t)0);
EXPECT_EQ(cacheable_shader_masker_item->cache_state(),
RasterCacheItem::CacheState::kNone);
EXPECT_FALSE(cacheable_shader_masker_item->GetId().has_value());
// frame 3.
layer->Preroll(preroll_context());
LayerTree::TryToRasterCache(cacheable_items(), &paint_context());
EXPECT_EQ(raster_cache()->GetLayerCachedEntriesCount(), (size_t)1);
EXPECT_EQ(cacheable_shader_masker_item->cache_state(),
RasterCacheItem::CacheState::kCurrent);
EXPECT_TRUE(raster_cache()->Draw(
cacheable_shader_masker_item->GetId().value(), cache_canvas, &paint));
}
TEST_F(ShaderMaskLayerTest, OpacityInheritance) {
const SkRect child_bounds = SkRect::MakeLTRB(5.0f, 6.0f, 20.5f, 21.5f);
const SkPath child_path = SkPath().addRect(child_bounds);
auto mock_layer = MockLayer::Make(child_path);
const SkRect mask_rect = SkRect::MakeLTRB(10, 10, 20, 20);
auto shader_mask_layer =
std::make_shared<ShaderMaskLayer>(nullptr, mask_rect, DlBlendMode::kSrc);
shader_mask_layer->Add(mock_layer);
// ShaderMaskLayers can always support opacity despite incompatible children
PrerollContext* context = preroll_context();
shader_mask_layer->Preroll(context);
EXPECT_EQ(context->renderable_state_flags, Layer::kSaveLayerRenderFlags);
int opacity_alpha = 0x7F;
SkPoint offset = SkPoint::Make(10, 10);
auto opacity_layer = std::make_shared<OpacityLayer>(opacity_alpha, offset);
opacity_layer->Add(shader_mask_layer);
opacity_layer->Preroll(context);
EXPECT_TRUE(opacity_layer->children_can_accept_opacity());
DisplayListBuilder expected_builder;
/* OpacityLayer::Paint() */ {
expected_builder.Save();
{
expected_builder.Translate(offset.fX, offset.fY);
/* ShaderMaskLayer::Paint() */ {
DlPaint sl_paint = DlPaint(DlColor(opacity_alpha << 24));
expected_builder.SaveLayer(&child_path.getBounds(), &sl_paint);
{
/* child layer paint */ {
expected_builder.DrawPath(child_path, DlPaint());
}
expected_builder.Translate(mask_rect.fLeft, mask_rect.fTop);
expected_builder.DrawRect(
SkRect::MakeWH(mask_rect.width(), mask_rect.height()),
DlPaint().setBlendMode(DlBlendMode::kSrc));
}
expected_builder.Restore();
}
}
expected_builder.Restore();
}
opacity_layer->Paint(display_list_paint_context());
EXPECT_TRUE(DisplayListsEQ_Verbose(expected_builder.Build(), display_list()));
}
TEST_F(ShaderMaskLayerTest, SimpleFilterWithRasterCacheLayerNotCached) {
use_mock_raster_cache(); // Ensure non-fractional alignment.
const SkMatrix initial_transform = SkMatrix::Translate(0.5f, 1.0f);
const SkRect child_bounds = SkRect::MakeLTRB(5.0f, 6.0f, 20.5f, 21.5f);
const SkRect layer_bounds = SkRect::MakeLTRB(2.0f, 4.0f, 6.5f, 6.5f);
const SkPath child_path = SkPath().addRect(child_bounds);
const DlPaint child_paint = DlPaint(DlColor::kYellow());
auto dl_filter = MakeFilter(DlColor::kBlue());
auto mock_layer = std::make_shared<MockLayer>(child_path, child_paint);
auto layer = std::make_shared<ShaderMaskLayer>(dl_filter, layer_bounds,
DlBlendMode::kSrc);
layer->Add(mock_layer);
preroll_context()->state_stack.set_preroll_delegate(initial_transform);
layer->Preroll(preroll_context());
DlPaint filter_paint;
filter_paint.setBlendMode(DlBlendMode::kSrc);
filter_paint.setColorSource(dl_filter);
layer->Paint(display_list_paint_context());
DisplayListBuilder expected_builder;
/* (ShaderMask)layer::Paint */ {
expected_builder.Save();
{
// The layer will notice that the CTM is already an integer matrix
// and will not perform an Integral CTM operation.
// expected_builder.TransformReset();
// expected_builder.Transform(SkMatrix());
expected_builder.SaveLayer(&child_bounds);
{
/* mock_layer::Paint */ {
expected_builder.DrawPath(child_path, child_paint);
}
expected_builder.Translate(layer_bounds.fLeft, layer_bounds.fTop);
expected_builder.DrawRect(
SkRect::MakeWH(layer_bounds.width(), layer_bounds.height()),
filter_paint);
}
expected_builder.Restore();
}
expected_builder.Restore();
}
EXPECT_TRUE(DisplayListsEQ_Verbose(display_list(), expected_builder.Build()));
}
} // namespace testing
} // namespace flutter
// NOLINTEND(bugprone-unchecked-optional-access)
| engine/flow/layers/shader_mask_layer_unittests.cc/0 | {
"file_path": "engine/flow/layers/shader_mask_layer_unittests.cc",
"repo_id": "engine",
"token_count": 8039
} | 170 |
// 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.
#ifndef FLUTTER_FLOW_RASTER_CACHE_KEY_H_
#define FLUTTER_FLOW_RASTER_CACHE_KEY_H_
#include <optional>
#include <unordered_map>
#include <utility>
#include <vector>
#include "flutter/fml/hash_combine.h"
#include "flutter/fml/logging.h"
#include "third_party/skia/include/core/SkMatrix.h"
namespace flutter {
class Layer;
enum class RasterCacheKeyType { kLayer, kDisplayList, kLayerChildren };
class RasterCacheKeyID {
public:
static constexpr uint64_t kDefaultUniqueID = 0;
RasterCacheKeyID(uint64_t unique_id, RasterCacheKeyType type)
: unique_id_(unique_id), type_(type) {}
RasterCacheKeyID(std::vector<RasterCacheKeyID> child_ids,
RasterCacheKeyType type)
: unique_id_(kDefaultUniqueID),
type_(type),
child_ids_(std::move(child_ids)) {}
uint64_t unique_id() const { return unique_id_; }
RasterCacheKeyType type() const { return type_; }
const std::vector<RasterCacheKeyID>& child_ids() const { return child_ids_; }
static std::optional<std::vector<RasterCacheKeyID>> LayerChildrenIds(
const Layer* layer);
std::size_t GetHash() const {
if (cached_hash_) {
return cached_hash_.value();
}
std::size_t seed = fml::HashCombine();
fml::HashCombineSeed(seed, unique_id_);
fml::HashCombineSeed(seed, type_);
for (auto& child_id : child_ids_) {
fml::HashCombineSeed(seed, child_id.GetHash());
}
cached_hash_ = seed;
return seed;
}
bool operator==(const RasterCacheKeyID& other) const {
return unique_id_ == other.unique_id_ && type_ == other.type_ &&
GetHash() == other.GetHash() && child_ids_ == other.child_ids_;
}
bool operator!=(const RasterCacheKeyID& other) const {
return !operator==(other);
}
private:
const uint64_t unique_id_;
const RasterCacheKeyType type_;
const std::vector<RasterCacheKeyID> child_ids_;
mutable std::optional<std::size_t> cached_hash_;
};
enum class RasterCacheKeyKind { kLayerMetrics, kDisplayListMetrics };
class RasterCacheKey {
public:
RasterCacheKey(uint64_t unique_id,
RasterCacheKeyType type,
const SkMatrix& ctm)
: RasterCacheKey(RasterCacheKeyID(unique_id, type), ctm) {}
RasterCacheKey(RasterCacheKeyID id, const SkMatrix& ctm)
: id_(std::move(id)), matrix_(ctm) {
matrix_[SkMatrix::kMTransX] = 0;
matrix_[SkMatrix::kMTransY] = 0;
}
const RasterCacheKeyID& id() const { return id_; }
const SkMatrix& matrix() const { return matrix_; }
RasterCacheKeyKind kind() const {
switch (id_.type()) {
case RasterCacheKeyType::kDisplayList:
return RasterCacheKeyKind::kDisplayListMetrics;
case RasterCacheKeyType::kLayer:
case RasterCacheKeyType::kLayerChildren:
return RasterCacheKeyKind::kLayerMetrics;
}
}
struct Hash {
std::size_t operator()(RasterCacheKey const& key) const {
return key.id_.GetHash();
}
};
struct Equal {
constexpr bool operator()(const RasterCacheKey& lhs,
const RasterCacheKey& rhs) const {
return lhs.id_ == rhs.id_ && lhs.matrix_ == rhs.matrix_;
}
};
template <class Value>
using Map = std::unordered_map<RasterCacheKey, Value, Hash, Equal>;
private:
RasterCacheKeyID id_;
// ctm where only fractional (0-1) translations are preserved:
// matrix_ = ctm;
// matrix_[SkMatrix::kMTransX] = SkScalarFraction(ctm.getTranslateX());
// matrix_[SkMatrix::kMTransY] = SkScalarFraction(ctm.getTranslateY());
SkMatrix matrix_;
};
} // namespace flutter
#endif // FLUTTER_FLOW_RASTER_CACHE_KEY_H_
| engine/flow/raster_cache_key.h/0 | {
"file_path": "engine/flow/raster_cache_key.h",
"repo_id": "engine",
"token_count": 1497
} | 171 |
// 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.
#include "flutter/flow/surface_frame.h"
#include <limits>
#include <utility>
#include "flutter/fml/logging.h"
#include "flutter/fml/trace_event.h"
#include "third_party/skia/include/core/SkSurface.h"
#include "third_party/skia/include/utils/SkNWayCanvas.h"
namespace flutter {
SurfaceFrame::SurfaceFrame(sk_sp<SkSurface> surface,
FramebufferInfo framebuffer_info,
const SubmitCallback& submit_callback,
SkISize frame_size,
std::unique_ptr<GLContextResult> context_result,
bool display_list_fallback)
: surface_(std::move(surface)),
framebuffer_info_(framebuffer_info),
submit_callback_(submit_callback),
context_result_(std::move(context_result)) {
FML_DCHECK(submit_callback_);
if (surface_) {
adapter_.set_canvas(surface_->getCanvas());
canvas_ = &adapter_;
} else if (display_list_fallback) {
FML_DCHECK(!frame_size.isEmpty());
// The root frame of a surface will be filled by the layer_tree which
// performs branch culling so it will be unlikely to need an rtree for
// further culling during `DisplayList::Dispatch`. Further, this canvas
// will live underneath any platform views so we do not need to compute
// exact coverage to describe "pixel ownership" to the platform.
dl_builder_ = sk_make_sp<DisplayListBuilder>(SkRect::Make(frame_size),
/*prepare_rtree=*/false);
canvas_ = dl_builder_.get();
}
}
bool SurfaceFrame::Submit() {
TRACE_EVENT0("flutter", "SurfaceFrame::Submit");
if (submitted_) {
return false;
}
submitted_ = PerformSubmit();
return submitted_;
}
bool SurfaceFrame::IsSubmitted() const {
return submitted_;
}
DlCanvas* SurfaceFrame::Canvas() {
return canvas_;
}
sk_sp<SkSurface> SurfaceFrame::SkiaSurface() const {
return surface_;
}
bool SurfaceFrame::PerformSubmit() {
if (submit_callback_ == nullptr) {
return false;
}
if (submit_callback_(*this, Canvas())) {
return true;
}
return false;
}
sk_sp<DisplayList> SurfaceFrame::BuildDisplayList() {
TRACE_EVENT0("impeller", "SurfaceFrame::BuildDisplayList");
return dl_builder_ ? dl_builder_->Build() : nullptr;
}
} // namespace flutter
| engine/flow/surface_frame.cc/0 | {
"file_path": "engine/flow/surface_frame.cc",
"repo_id": "engine",
"token_count": 967
} | 172 |
// 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.
#ifndef FLUTTER_FLOW_TESTING_MOCK_TEXTURE_H_
#define FLUTTER_FLOW_TESTING_MOCK_TEXTURE_H_
#include <ostream>
#include <vector>
#include "flutter/common/graphics/texture.h"
#include "flutter/testing/assertions_skia.h"
namespace flutter {
namespace testing {
// Mock implementation of the |Texture| interface that does not interact with
// the GPU. It simply records the list of various calls made so the test can
// later verify them against expected data.
class MockTexture : public Texture {
public:
static sk_sp<DlImage> MakeTestTexture(int w, int h, int checker_size);
explicit MockTexture(int64_t textureId,
const sk_sp<DlImage>& texture = nullptr);
// Called from raster thread.
void Paint(PaintContext& context,
const SkRect& bounds,
bool freeze,
const DlImageSampling sampling) override;
void OnGrContextCreated() override { gr_context_created_ = true; }
void OnGrContextDestroyed() override { gr_context_destroyed_ = true; }
void MarkNewFrameAvailable() override {}
void OnTextureUnregistered() override { unregistered_ = true; }
bool gr_context_created() { return gr_context_created_; }
bool gr_context_destroyed() { return gr_context_destroyed_; }
bool unregistered() { return unregistered_; }
private:
sk_sp<DlImage> texture_;
bool gr_context_created_ = false;
bool gr_context_destroyed_ = false;
bool unregistered_ = false;
};
} // namespace testing
} // namespace flutter
#endif // FLUTTER_FLOW_TESTING_MOCK_TEXTURE_H_
| engine/flow/testing/mock_texture.h/0 | {
"file_path": "engine/flow/testing/mock_texture.h",
"repo_id": "engine",
"token_count": 569
} | 173 |
# 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("//flutter/common/config.gni")
import("//flutter/testing/testing.gni")
if (is_fuchsia) {
import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni")
}
source_set("fml") {
sources = [
"ascii_trie.cc",
"ascii_trie.h",
"backtrace.h",
"base32.cc",
"base32.h",
"build_config.h",
"closure.h",
"compiler_specific.h",
"concurrent_message_loop.cc",
"concurrent_message_loop.h",
"container.h",
"cpu_affinity.cc",
"cpu_affinity.h",
"delayed_task.cc",
"delayed_task.h",
"eintr_wrapper.h",
"endianness.cc",
"endianness.h",
"file.cc",
"file.h",
"hash_combine.h",
"hex_codec.cc",
"hex_codec.h",
"icu_util.cc",
"icu_util.h",
"log_level.h",
"log_settings.cc",
"log_settings.h",
"log_settings_state.cc",
"logging.cc",
"logging.h",
"make_copyable.h",
"mapping.cc",
"mapping.h",
"math.h",
"memory/ref_counted.h",
"memory/ref_counted_internal.h",
"memory/ref_ptr.h",
"memory/ref_ptr_internal.h",
"memory/task_runner_checker.cc",
"memory/task_runner_checker.h",
"memory/thread_checker.cc",
"memory/thread_checker.h",
"memory/weak_ptr.h",
"memory/weak_ptr_internal.cc",
"memory/weak_ptr_internal.h",
"message_loop.cc",
"message_loop.h",
"message_loop_impl.cc",
"message_loop_impl.h",
"message_loop_task_queues.cc",
"message_loop_task_queues.h",
"native_library.h",
"paths.cc",
"paths.h",
"posix_wrappers.h",
"process.h",
"raster_thread_merger.cc",
"raster_thread_merger.h",
"shared_thread_merger.cc",
"shared_thread_merger.h",
"size.h",
"status.h",
"status_or.h",
"synchronization/atomic_object.h",
"synchronization/count_down_latch.cc",
"synchronization/count_down_latch.h",
"synchronization/semaphore.cc",
"synchronization/semaphore.h",
"synchronization/shared_mutex.h",
"synchronization/sync_switch.cc",
"synchronization/sync_switch.h",
"synchronization/waitable_event.cc",
"synchronization/waitable_event.h",
"task_queue_id.h",
"task_runner.cc",
"task_runner.h",
"task_source.cc",
"task_source.h",
"thread.cc",
"thread.h",
"time/time_delta.h",
"time/time_point.cc",
"time/time_point.h",
"time/timestamp_provider.h",
"trace_event.cc",
"trace_event.h",
"unique_fd.cc",
"unique_fd.h",
"unique_object.h",
"wakeable.h",
]
if (enable_backtrace) {
sources += [ "backtrace.cc" ]
} else {
sources += [ "backtrace_stub.cc" ]
}
public_deps = [
":build_config",
":command_line",
":string_conversion",
]
deps = [
"$dart_src/runtime:dart_api",
# These need to be in sync with the Fuchsia buildroot.
"//flutter/third_party/icu",
]
if (enable_backtrace) {
# This abseil dependency is only used by backtrace.cc.
deps += [ "//flutter/third_party/abseil-cpp/absl/debugging:symbolize" ]
}
configs += [ "//flutter/third_party/icu:icu_config" ]
public_configs = [
"//flutter:config",
"//flutter/common:flutter_config",
]
libs = []
if (is_ios || is_mac) {
sources += [
"platform/darwin/concurrent_message_loop_factory.mm",
"platform/posix/shared_mutex_posix.cc",
]
} else {
sources += [
"concurrent_message_loop_factory.cc",
"synchronization/shared_mutex_std.cc",
]
}
if (is_ios || is_mac) {
cflags_objc = flutter_cflags_objc
cflags_objcc = flutter_cflags_objcc
sources += [
"platform/darwin/cf_utils.cc",
"platform/darwin/cf_utils.h",
"platform/darwin/message_loop_darwin.h",
"platform/darwin/message_loop_darwin.mm",
"platform/darwin/paths_darwin.mm",
"platform/darwin/platform_version.h",
"platform/darwin/platform_version.mm",
"platform/darwin/scoped_block.h",
"platform/darwin/scoped_block.mm",
"platform/darwin/scoped_nsautorelease_pool.cc",
"platform/darwin/scoped_nsautorelease_pool.h",
"platform/darwin/scoped_nsobject.h",
"platform/darwin/scoped_nsobject.mm",
"platform/darwin/scoped_policy.h",
"platform/darwin/scoped_typeref.h",
"platform/darwin/string_range_sanitization.h",
"platform/darwin/string_range_sanitization.mm",
"platform/darwin/weak_nsobject.h",
"platform/darwin/weak_nsobject.mm",
]
frameworks = [ "Foundation.framework" ]
}
if (is_android) {
sources += [
"platform/android/cpu_affinity.cc",
"platform/android/cpu_affinity.h",
"platform/android/jni_util.cc",
"platform/android/jni_util.h",
"platform/android/jni_weak_ref.cc",
"platform/android/jni_weak_ref.h",
"platform/android/message_loop_android.cc",
"platform/android/message_loop_android.h",
"platform/android/paths_android.cc",
"platform/android/paths_android.h",
"platform/android/scoped_java_ref.cc",
"platform/android/scoped_java_ref.h",
]
libs += [ "android" ]
}
if (is_android) {
sources += [
"platform/linux/timerfd.cc",
"platform/linux/timerfd.h",
]
}
if (is_linux) {
sources += [
"platform/linux/message_loop_linux.cc",
"platform/linux/message_loop_linux.h",
"platform/linux/paths_linux.cc",
"platform/linux/timerfd.cc",
"platform/linux/timerfd.h",
]
}
if (is_fuchsia) {
sources += [
"platform/fuchsia/log_interest_listener.cc",
"platform/fuchsia/log_interest_listener.h",
"platform/fuchsia/log_state.cc",
"platform/fuchsia/log_state.h",
"platform/fuchsia/message_loop_fuchsia.cc",
"platform/fuchsia/message_loop_fuchsia.h",
"platform/fuchsia/paths_fuchsia.cc",
"platform/fuchsia/task_observers.cc",
"platform/fuchsia/task_observers.h",
]
public_deps += [
"${fuchsia_sdk}/fidl/fuchsia.diagnostics:fuchsia.diagnostics_cpp",
"${fuchsia_sdk}/fidl/fuchsia.logger:fuchsia.logger_cpp",
"${fuchsia_sdk}/pkg/async-cpp",
"${fuchsia_sdk}/pkg/async-loop-cpp",
"${fuchsia_sdk}/pkg/async-loop-default",
"${fuchsia_sdk}/pkg/component_incoming_cpp",
"${fuchsia_sdk}/pkg/syslog_structured_backend",
"${fuchsia_sdk}/pkg/trace",
"${fuchsia_sdk}/pkg/trace-engine",
"${fuchsia_sdk}/pkg/zx",
]
}
if (is_win) {
sources += [
"platform/win/command_line_win.cc",
"platform/win/errors_win.cc",
"platform/win/errors_win.h",
"platform/win/file_win.cc",
"platform/win/mapping_win.cc",
"platform/win/message_loop_win.cc",
"platform/win/message_loop_win.h",
"platform/win/native_library_win.cc",
"platform/win/paths_win.cc",
"platform/win/posix_wrappers_win.cc",
"platform/win/process_win.cc",
]
} else {
sources += [
"platform/posix/command_line_posix.cc",
"platform/posix/file_posix.cc",
"platform/posix/mapping_posix.cc",
"platform/posix/native_library_posix.cc",
"platform/posix/paths_posix.cc",
"platform/posix/posix_wrappers_posix.cc",
"platform/posix/process_posix.cc",
]
}
}
source_set("build_config") {
sources = [ "build_config.h" ]
public_configs = [
"//flutter:config",
"//flutter/common:flutter_config",
]
}
source_set("command_line") {
sources = [
"command_line.cc",
"command_line.h",
]
public_configs = [
"//flutter:config",
"//flutter/common:flutter_config",
]
}
source_set("string_conversion") {
sources = [
"string_conversion.cc",
"string_conversion.h",
]
# Current versions of libcxx have deprecated some of the UTF-16 string
# conversion APIs.
defines = [ "_LIBCPP_DISABLE_DEPRECATION_WARNINGS" ]
if (is_win) {
sources += [
"platform/win/wstring_conversion.cc",
"platform/win/wstring_conversion.h",
]
# TODO(cbracken): https://github.com/flutter/flutter/issues/50053
defines += [ "_SILENCE_CXX17_CODECVT_HEADER_DEPRECATION_WARNING" ]
}
deps = [ ":build_config" ]
public_configs = [
"//flutter:config",
"//flutter/common:flutter_config",
]
}
if (enable_unittests) {
test_fixtures("fml_fixtures") {
fixtures = []
}
executable("fml_benchmarks") {
testonly = true
sources = [ "message_loop_task_queues_benchmark.cc" ]
deps = [
"//flutter/benchmarking",
"//flutter/fml",
]
}
executable("fml_unittests") {
testonly = true
sources = [
"ascii_trie_unittests.cc",
"backtrace_unittests.cc",
"base32_unittest.cc",
"closure_unittests.cc",
"command_line_unittest.cc",
"container_unittests.cc",
"cpu_affinity_unittests.cc",
"endianness_unittests.cc",
"file_unittest.cc",
"hash_combine_unittests.cc",
"hex_codec_unittest.cc",
"logging_unittests.cc",
"mapping_unittests.cc",
"math_unittests.cc",
"memory/ref_counted_unittest.cc",
"memory/task_runner_checker_unittest.cc",
"memory/weak_ptr_unittest.cc",
"message_loop_task_queues_merge_unmerge_unittests.cc",
"message_loop_task_queues_unittests.cc",
"message_loop_unittests.cc",
"paths_unittests.cc",
"raster_thread_merger_unittests.cc",
"string_conversion_unittests.cc",
"synchronization/count_down_latch_unittests.cc",
"synchronization/semaphore_unittest.cc",
"synchronization/sync_switch_unittest.cc",
"synchronization/waitable_event_unittest.cc",
"task_source_unittests.cc",
"thread_unittests.cc",
"time/chrono_timestamp_provider.cc",
"time/chrono_timestamp_provider.h",
"time/time_delta_unittest.cc",
"time/time_point_unittest.cc",
"time/time_unittest.cc",
]
if (is_mac) {
sources += [
"platform/darwin/cf_utils_unittests.mm",
"platform/darwin/string_range_sanitization_unittests.mm",
]
}
if (is_mac || is_ios) {
sources += [
"platform/darwin/scoped_nsobject_unittests.mm",
"platform/darwin/weak_nsobject_unittests.mm",
]
}
if (is_fuchsia) {
sources += [ "platform/fuchsia/log_interest_listener_unittests.cc" ]
}
if (is_win) {
sources += [
"platform/win/file_win_unittests.cc",
"platform/win/wstring_conversion_unittests.cc",
]
}
deps = [
":fml_fixtures",
"//flutter/fml",
"//flutter/runtime",
"//flutter/runtime:libdart",
"//flutter/testing",
]
if (is_fuchsia) {
deps += [
"${fuchsia_sdk}/pkg/async-loop-testing",
"${fuchsia_sdk}/pkg/sys_component_cpp_testing",
]
# This is needed for //flutter/third_party/googletest for linking zircon
# symbols.
libs = [ "${fuchsia_arch_root}/sysroot/lib/libzircon.so" ]
}
}
executable("fml_arc_unittests") {
testonly = true
if (is_mac || is_ios) {
cflags_objcc = flutter_cflags_objc_arc
sources = [
"platform/darwin/scoped_nsobject_arc_unittests.mm",
"platform/darwin/weak_nsobject_arc_unittests.mm",
]
}
deps = [
":fml_fixtures",
"//flutter/fml",
"//flutter/testing",
]
}
}
| engine/fml/BUILD.gn/0 | {
"file_path": "engine/fml/BUILD.gn",
"repo_id": "engine",
"token_count": 5386
} | 174 |
// 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.
#include "flutter/fml/command_line.h"
#include <string_view>
#include <utility>
#include "flutter/fml/macros.h"
#include "flutter/fml/size.h"
#include "gtest/gtest.h"
namespace fml {
namespace {
TEST(CommandLineTest, Basic) {
// Making this const verifies that the methods called are const.
const auto cl = CommandLineFromInitializerList(
{"my_program", "--flag1", "--flag2=value2", "arg1", "arg2", "arg3"});
EXPECT_TRUE(cl.has_argv0());
EXPECT_EQ("my_program", cl.argv0());
EXPECT_EQ(2u, cl.options().size());
EXPECT_EQ("flag1", cl.options()[0].name);
EXPECT_EQ(std::string(), cl.options()[0].value);
EXPECT_EQ("flag2", cl.options()[1].name);
EXPECT_EQ("value2", cl.options()[1].value);
EXPECT_EQ(3u, cl.positional_args().size());
EXPECT_EQ("arg1", cl.positional_args()[0]);
EXPECT_EQ("arg2", cl.positional_args()[1]);
EXPECT_EQ("arg3", cl.positional_args()[2]);
EXPECT_TRUE(cl.HasOption("flag1"));
EXPECT_TRUE(cl.HasOption("flag1", nullptr));
size_t index = static_cast<size_t>(-1);
EXPECT_TRUE(cl.HasOption("flag2", &index));
EXPECT_EQ(1u, index);
EXPECT_FALSE(cl.HasOption("flag3"));
EXPECT_FALSE(cl.HasOption("flag3", nullptr));
std::string value = "nonempty";
EXPECT_TRUE(cl.GetOptionValue("flag1", &value));
EXPECT_EQ(std::string(), value);
EXPECT_TRUE(cl.GetOptionValue("flag2", &value));
EXPECT_EQ("value2", value);
EXPECT_FALSE(cl.GetOptionValue("flag3", &value));
EXPECT_EQ(std::string(), cl.GetOptionValueWithDefault("flag1", "nope"));
EXPECT_EQ("value2", cl.GetOptionValueWithDefault("flag2", "nope"));
EXPECT_EQ("nope", cl.GetOptionValueWithDefault("flag3", "nope"));
}
TEST(CommandLineTest, DefaultConstructor) {
CommandLine cl;
EXPECT_FALSE(cl.has_argv0());
EXPECT_EQ(std::string(), cl.argv0());
EXPECT_EQ(std::vector<CommandLine::Option>(), cl.options());
EXPECT_EQ(std::vector<std::string>(), cl.positional_args());
}
TEST(CommandLineTest, ComponentConstructor) {
const std::string argv0 = "my_program";
const std::vector<CommandLine::Option> options = {
CommandLine::Option("flag", "value")};
const std::vector<std::string> positional_args = {"arg"};
CommandLine cl(argv0, options, positional_args);
EXPECT_TRUE(cl.has_argv0());
EXPECT_EQ(argv0, cl.argv0());
EXPECT_EQ(options, cl.options());
EXPECT_EQ(positional_args, cl.positional_args());
EXPECT_EQ("value", cl.GetOptionValueWithDefault("flag", "nope"));
}
TEST(CommandLineTest, CommandLineFromIteratorsFindFirstPositionalArg) {
// This shows how one might process subcommands.
{
static std::vector<std::string> argv = {"my_program", "--flag1",
"--flag2", "subcommand",
"--subflag", "subarg"};
auto first = argv.cbegin();
auto last = argv.cend();
std::vector<std::string>::const_iterator sub_first;
auto cl =
CommandLineFromIteratorsFindFirstPositionalArg(first, last, &sub_first);
EXPECT_TRUE(cl.has_argv0());
EXPECT_EQ(argv[0], cl.argv0());
std::vector<CommandLine::Option> expected_options = {
CommandLine::Option("flag1"), CommandLine::Option("flag2")};
EXPECT_EQ(expected_options, cl.options());
std::vector<std::string> expected_positional_args = {argv[3], argv[4],
argv[5]};
EXPECT_EQ(expected_positional_args, cl.positional_args());
EXPECT_TRUE(cl.HasOption("flag1", nullptr));
EXPECT_TRUE(cl.HasOption("flag2", nullptr));
EXPECT_FALSE(cl.HasOption("subflag", nullptr));
EXPECT_EQ(first + 3, sub_first);
auto sub_cl = CommandLineFromIterators(sub_first, last);
EXPECT_TRUE(sub_cl.has_argv0());
EXPECT_EQ(argv[3], sub_cl.argv0());
std::vector<CommandLine::Option> expected_sub_options = {
CommandLine::Option("subflag")};
EXPECT_EQ(expected_sub_options, sub_cl.options());
std::vector<std::string> expected_sub_positional_args = {argv[5]};
EXPECT_EQ(expected_sub_positional_args, sub_cl.positional_args());
EXPECT_FALSE(sub_cl.HasOption("flag1", nullptr));
EXPECT_FALSE(sub_cl.HasOption("flag2", nullptr));
EXPECT_TRUE(sub_cl.HasOption("subflag", nullptr));
}
// No positional argument.
{
static std::vector<std::string> argv = {"my_program", "--flag"};
std::vector<std::string>::const_iterator sub_first;
auto cl = CommandLineFromIteratorsFindFirstPositionalArg(
argv.cbegin(), argv.cend(), &sub_first);
EXPECT_EQ(argv.cend(), sub_first);
}
// Multiple positional arguments.
{
static std::vector<std::string> argv = {"my_program", "arg1", "arg2"};
std::vector<std::string>::const_iterator sub_first;
auto cl = CommandLineFromIteratorsFindFirstPositionalArg(
argv.cbegin(), argv.cend(), &sub_first);
EXPECT_EQ(argv.cbegin() + 1, sub_first);
}
// "--".
{
static std::vector<std::string> argv = {"my_program", "--", "--arg"};
std::vector<std::string>::const_iterator sub_first;
auto cl = CommandLineFromIteratorsFindFirstPositionalArg(
argv.cbegin(), argv.cend(), &sub_first);
EXPECT_EQ(argv.cbegin() + 2, sub_first);
}
}
TEST(CommandLineTest, CommmandLineFromIterators) {
{
// Note (here and below): The |const| ensures that the factory method can
// accept const iterators.
const std::vector<std::string> argv = {"my_program", "--flag=value", "arg"};
auto cl = CommandLineFromIterators(argv.begin(), argv.end());
EXPECT_TRUE(cl.has_argv0());
EXPECT_EQ(argv[0], cl.argv0());
std::vector<CommandLine::Option> expected_options = {
CommandLine::Option("flag", "value")};
EXPECT_EQ(expected_options, cl.options());
std::vector<std::string> expected_positional_args = {argv[2]};
EXPECT_EQ(expected_positional_args, cl.positional_args());
EXPECT_EQ("value", cl.GetOptionValueWithDefault("flag", "nope"));
}
// Can handle empty argv.
{
const std::vector<std::string> argv;
auto cl = CommandLineFromIterators(argv.begin(), argv.end());
EXPECT_FALSE(cl.has_argv0());
EXPECT_EQ(std::string(), cl.argv0());
EXPECT_EQ(std::vector<CommandLine::Option>(), cl.options());
EXPECT_EQ(std::vector<std::string>(), cl.positional_args());
}
// Can handle empty |argv[0]|.
{
const std::vector<std::string> argv = {""};
auto cl = CommandLineFromIterators(argv.begin(), argv.end());
EXPECT_TRUE(cl.has_argv0());
EXPECT_EQ(std::string(), cl.argv0());
EXPECT_EQ(std::vector<CommandLine::Option>(), cl.options());
EXPECT_EQ(std::vector<std::string>(), cl.positional_args());
}
// Can also take a vector of |const char*|s.
{
const std::vector<const char*> argv = {"my_program", "--flag=value", "arg"};
auto cl = CommandLineFromIterators(argv.begin(), argv.end());
EXPECT_TRUE(cl.has_argv0());
EXPECT_EQ(argv[0], cl.argv0());
std::vector<CommandLine::Option> expected_options = {
CommandLine::Option("flag", "value")};
EXPECT_EQ(expected_options, cl.options());
std::vector<std::string> expected_positional_args = {argv[2]};
EXPECT_EQ(expected_positional_args, cl.positional_args());
EXPECT_EQ("value", cl.GetOptionValueWithDefault("flag", "nope"));
}
// Or a plain old array.
{
static const char* const argv[] = {"my_program", "--flag=value", "arg"};
auto cl = CommandLineFromIterators(argv, argv + fml::size(argv));
EXPECT_TRUE(cl.has_argv0());
EXPECT_EQ(argv[0], cl.argv0());
std::vector<CommandLine::Option> expected_options = {
CommandLine::Option("flag", "value")};
EXPECT_EQ(expected_options, cl.options());
std::vector<std::string> expected_positional_args = {argv[2]};
EXPECT_EQ(expected_positional_args, cl.positional_args());
EXPECT_EQ("value", cl.GetOptionValueWithDefault("flag", "nope"));
}
}
TEST(CommandLineTest, CommandLineFromArgcArgv) {
static const char* const argv[] = {"my_program", "--flag=value", "arg"};
const int argc = static_cast<int>(fml::size(argv));
auto cl = CommandLineFromArgcArgv(argc, argv);
EXPECT_TRUE(cl.has_argv0());
EXPECT_EQ(argv[0], cl.argv0());
std::vector<CommandLine::Option> expected_options = {
CommandLine::Option("flag", "value")};
EXPECT_EQ(expected_options, cl.options());
std::vector<std::string> expected_positional_args = {argv[2]};
EXPECT_EQ(expected_positional_args, cl.positional_args());
EXPECT_EQ("value", cl.GetOptionValueWithDefault("flag", "nope"));
}
TEST(CommandLineTest, CommandLineFromInitializerList) {
{
std::initializer_list<const char*> il = {"my_program", "--flag=value",
"arg"};
auto cl = CommandLineFromInitializerList(il);
EXPECT_TRUE(cl.has_argv0());
EXPECT_EQ("my_program", cl.argv0());
std::vector<CommandLine::Option> expected_options = {
CommandLine::Option("flag", "value")};
EXPECT_EQ(expected_options, cl.options());
std::vector<std::string> expected_positional_args = {"arg"};
EXPECT_EQ(expected_positional_args, cl.positional_args());
EXPECT_EQ("value", cl.GetOptionValueWithDefault("flag", "nope"));
}
{
std::initializer_list<std::string> il = {"my_program", "--flag=value",
"arg"};
auto cl = CommandLineFromInitializerList(il);
EXPECT_TRUE(cl.has_argv0());
EXPECT_EQ("my_program", cl.argv0());
std::vector<CommandLine::Option> expected_options = {
CommandLine::Option("flag", "value")};
EXPECT_EQ(expected_options, cl.options());
std::vector<std::string> expected_positional_args = {"arg"};
EXPECT_EQ(expected_positional_args, cl.positional_args());
EXPECT_EQ("value", cl.GetOptionValueWithDefault("flag", "nope"));
}
}
TEST(CommandLineTest, OddArguments) {
{
// Except for "arg", these are all options.
auto cl = CommandLineFromInitializerList(
{"my_program", "--=", "--=foo", "--bar=", "--==", "--===", "--==x",
"arg"});
EXPECT_TRUE(cl.has_argv0());
EXPECT_EQ("my_program", cl.argv0());
std::vector<CommandLine::Option> expected_options = {
CommandLine::Option("="), CommandLine::Option("=foo"),
CommandLine::Option("bar"), CommandLine::Option("="),
CommandLine::Option("=", "="), CommandLine::Option("=", "x")};
EXPECT_EQ(expected_options, cl.options());
std::vector<std::string> expected_positional_args = {"arg"};
EXPECT_EQ(expected_positional_args, cl.positional_args());
}
// "-x" is an argument, not an options.
{
auto cl = CommandLineFromInitializerList({"", "-x"});
EXPECT_TRUE(cl.has_argv0());
EXPECT_EQ(std::string(), cl.argv0());
EXPECT_EQ(std::vector<CommandLine::Option>(), cl.options());
std::vector<std::string> expected_positional_args = {"-x"};
EXPECT_EQ(expected_positional_args, cl.positional_args());
}
// Ditto for "-".
{
auto cl = CommandLineFromInitializerList({"", "-"});
EXPECT_TRUE(cl.has_argv0());
EXPECT_EQ(std::string(), cl.argv0());
EXPECT_EQ(std::vector<CommandLine::Option>(), cl.options());
std::vector<std::string> expected_positional_args = {"-"};
EXPECT_EQ(expected_positional_args, cl.positional_args());
}
// "--" terminates option processing, but isn't an argument in the first
// occurrence.
{
auto cl = CommandLineFromInitializerList(
{"", "--flag=value", "--", "--not-a-flag", "arg", "--"});
EXPECT_TRUE(cl.has_argv0());
EXPECT_EQ(std::string(), cl.argv0());
std::vector<CommandLine::Option> expected_options = {
CommandLine::Option("flag", "value")};
std::vector<std::string> expected_positional_args = {"--not-a-flag", "arg",
"--"};
EXPECT_EQ(expected_positional_args, cl.positional_args());
}
}
TEST(CommandLineTest, MultipleOccurrencesOfOption) {
auto cl = CommandLineFromInitializerList(
{"my_program", "--flag1=value1", "--flag2=value2", "--flag1=value3"});
std::vector<CommandLine::Option> expected_options = {
CommandLine::Option("flag1", "value1"),
CommandLine::Option("flag2", "value2"),
CommandLine::Option("flag1", "value3")};
EXPECT_EQ("value3", cl.GetOptionValueWithDefault("flag1", "nope"));
EXPECT_EQ("value2", cl.GetOptionValueWithDefault("flag2", "nope"));
std::vector<std::string_view> values = cl.GetOptionValues("flag1");
ASSERT_EQ(2u, values.size());
EXPECT_EQ("value1", values[0]);
EXPECT_EQ("value3", values[1]);
}
// |cl1| and |cl2| should be not equal.
void ExpectNotEqual(const char* message,
std::initializer_list<std::string> c1,
std::initializer_list<std::string> c2) {
SCOPED_TRACE(message);
const auto cl1 = CommandLineFromInitializerList(c1);
const auto cl2 = CommandLineFromInitializerList(c2);
// These are tautological.
EXPECT_TRUE(cl1 == cl1);
EXPECT_FALSE(cl1 != cl1);
EXPECT_TRUE(cl2 == cl2);
EXPECT_FALSE(cl2 != cl2);
// These rely on |cl1| not being equal to |cl2|.
EXPECT_FALSE(cl1 == cl2);
EXPECT_TRUE(cl1 != cl2);
EXPECT_FALSE(cl2 == cl1);
EXPECT_TRUE(cl2 != cl1);
}
void ExpectEqual(const char* message,
std::initializer_list<std::string> c1,
std::initializer_list<std::string> c2) {
SCOPED_TRACE(message);
const auto cl1 = CommandLineFromInitializerList(c1);
const auto cl2 = CommandLineFromInitializerList(c2);
// These are tautological.
EXPECT_TRUE(cl1 == cl1);
EXPECT_FALSE(cl1 != cl1);
EXPECT_TRUE(cl2 == cl2);
EXPECT_FALSE(cl2 != cl2);
// These rely on |cl1| being equal to |cl2|.
EXPECT_TRUE(cl1 == cl2);
EXPECT_FALSE(cl1 != cl2);
EXPECT_TRUE(cl2 == cl1);
EXPECT_FALSE(cl2 != cl1);
}
TEST(CommandLineTest, ComparisonOperators) {
ExpectNotEqual("1", {}, {""});
ExpectNotEqual("2", {"abc"}, {"def"});
ExpectNotEqual("3", {"abc", "--flag"}, {"abc"});
ExpectNotEqual("4", {"abc", "--flag1"}, {"abc", "--flag2"});
ExpectNotEqual("5", {"abc", "--flag1", "--flag2"}, {"abc", "--flag1"});
ExpectNotEqual("6", {"abc", "arg"}, {"abc"});
ExpectNotEqual("7", {"abc", "arg1"}, {"abc", "arg2"});
ExpectNotEqual("8", {"abc", "arg1", "arg2"}, {"abc", "arg1"});
ExpectNotEqual("9", {"abc", "--flag", "arg1"}, {"abc", "--flag", "arg2"});
// However, the presence of an unnecessary "--" shouldn't affect what's
// constructed.
ExpectEqual("10", {"abc", "--flag", "arg"}, {"abc", "--flag", "--", "arg"});
}
TEST(CommandLineTest, MoveAndCopy) {
const auto cl = CommandLineFromInitializerList(
{"my_program", "--flag1=value1", "--flag2", "arg"});
// Copy constructor.
CommandLine cl2(cl);
EXPECT_EQ(cl, cl2);
// Check that |option_index_| gets copied too.
EXPECT_EQ("value1", cl2.GetOptionValueWithDefault("flag1", "nope"));
// Move constructor.
CommandLine cl3(std::move(cl2));
EXPECT_EQ(cl, cl3);
EXPECT_EQ("value1", cl3.GetOptionValueWithDefault("flag1", "nope"));
// Copy assignment.
CommandLine cl4;
EXPECT_NE(cl, cl4);
cl4 = cl;
EXPECT_EQ(cl, cl4);
EXPECT_EQ("value1", cl4.GetOptionValueWithDefault("flag1", "nope"));
// Move assignment.
CommandLine cl5;
EXPECT_NE(cl, cl5);
cl5 = std::move(cl4);
EXPECT_EQ(cl, cl5);
EXPECT_EQ("value1", cl5.GetOptionValueWithDefault("flag1", "nope"));
}
void ToArgvHelper(const char* message, std::initializer_list<std::string> c) {
SCOPED_TRACE(message);
std::vector<std::string> argv = c;
auto cl = CommandLineFromInitializerList(c);
EXPECT_EQ(argv, CommandLineToArgv(cl));
}
TEST(CommandLineTest, CommandLineToArgv) {
ToArgvHelper("1", {});
ToArgvHelper("2", {""});
ToArgvHelper("3", {"my_program"});
ToArgvHelper("4", {"my_program", "--flag"});
ToArgvHelper("5", {"my_program", "--flag1", "--flag2=value"});
ToArgvHelper("6", {"my_program", "arg"});
ToArgvHelper("7", {"my_program", "arg1", "arg2"});
ToArgvHelper("8", {"my_program", "--flag1", "--flag2=value", "arg1", "arg2"});
ToArgvHelper("9", {"my_program", "--flag", "--", "--not-a-flag"});
ToArgvHelper("10", {"my_program", "--flag", "arg", "--"});
// However, |CommandLineToArgv()| will "strip" an unneeded "--".
{
auto cl = CommandLineFromInitializerList({"my_program", "--"});
std::vector<std::string> argv = {"my_program"};
EXPECT_EQ(argv, CommandLineToArgv(cl));
}
{
auto cl =
CommandLineFromInitializerList({"my_program", "--flag", "--", "arg"});
std::vector<std::string> argv = {"my_program", "--flag", "arg"};
EXPECT_EQ(argv, CommandLineToArgv(cl));
}
}
} // namespace
} // namespace fml
| engine/fml/command_line_unittest.cc/0 | {
"file_path": "engine/fml/command_line_unittest.cc",
"repo_id": "engine",
"token_count": 6858
} | 175 |
// 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.
#include "flutter/fml/file.h"
#include "flutter/fml/logging.h"
#include "flutter/fml/unique_fd.h"
namespace fml {
static fml::UniqueFD CreateDirectory(const fml::UniqueFD& base_directory,
const std::vector<std::string>& components,
FilePermission permission,
size_t index) {
FML_DCHECK(index <= components.size());
const char* file_path = components[index].c_str();
auto directory = OpenDirectory(base_directory, file_path, true, permission);
if (!directory.is_valid()) {
return {};
}
if (index == components.size() - 1) {
return directory;
}
return CreateDirectory(directory, components, permission, index + 1);
}
fml::UniqueFD CreateDirectory(const fml::UniqueFD& base_directory,
const std::vector<std::string>& components,
FilePermission permission) {
if (!IsDirectory(base_directory)) {
return {};
}
if (components.empty()) {
return {};
}
return CreateDirectory(base_directory, components, permission, 0);
}
ScopedTemporaryDirectory::ScopedTemporaryDirectory()
: path_(CreateTemporaryDirectory()) {
if (path_ != "") {
dir_fd_ = OpenDirectory(path_.c_str(), false, FilePermission::kRead);
}
}
ScopedTemporaryDirectory::~ScopedTemporaryDirectory() {
// POSIX requires the directory to be empty before UnlinkDirectory.
if (path_ != "") {
if (!RemoveFilesInDirectory(dir_fd_)) {
FML_LOG(ERROR) << "Could not clean directory: " << path_;
}
}
// Windows has to close UniqueFD first before UnlinkDirectory
dir_fd_.reset();
if (path_ != "") {
if (!UnlinkDirectory(path_.c_str())) {
FML_LOG(ERROR) << "Could not remove directory: " << path_;
}
}
}
bool VisitFilesRecursively(const fml::UniqueFD& directory,
const FileVisitor& visitor) {
FileVisitor recursive_visitor = [&recursive_visitor, &visitor](
const UniqueFD& directory,
const std::string& filename) {
if (!visitor(directory, filename)) {
return false;
}
if (IsDirectory(directory, filename.c_str())) {
UniqueFD sub_dir = OpenDirectoryReadOnly(directory, filename.c_str());
if (!sub_dir.is_valid()) {
FML_LOG(ERROR) << "Can't open sub-directory: " << filename;
return true;
}
return VisitFiles(sub_dir, recursive_visitor);
}
return true;
};
return VisitFiles(directory, recursive_visitor);
}
fml::UniqueFD OpenFileReadOnly(const fml::UniqueFD& base_directory,
const char* path) {
return OpenFile(base_directory, path, false, FilePermission::kRead);
}
fml::UniqueFD OpenDirectoryReadOnly(const fml::UniqueFD& base_directory,
const char* path) {
return OpenDirectory(base_directory, path, false, FilePermission::kRead);
}
bool RemoveFilesInDirectory(const fml::UniqueFD& directory) {
fml::FileVisitor recursive_cleanup = [&recursive_cleanup](
const fml::UniqueFD& directory,
const std::string& filename) {
bool removed;
if (fml::IsDirectory(directory, filename.c_str())) {
fml::UniqueFD sub_dir =
OpenDirectoryReadOnly(directory, filename.c_str());
removed = VisitFiles(sub_dir, recursive_cleanup) &&
fml::UnlinkDirectory(directory, filename.c_str());
} else {
removed = fml::UnlinkFile(directory, filename.c_str());
}
return removed;
};
return VisitFiles(directory, recursive_cleanup);
}
bool RemoveDirectoryRecursively(const fml::UniqueFD& parent,
const char* directory_name) {
auto dir = fml::OpenDirectory(parent, directory_name, false,
fml::FilePermission::kReadWrite);
return RemoveFilesInDirectory(dir) && UnlinkDirectory(parent, directory_name);
}
} // namespace fml
| engine/fml/file.cc/0 | {
"file_path": "engine/fml/file.cc",
"repo_id": "engine",
"token_count": 1749
} | 176 |
// 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.
#include <signal.h>
#include "flutter/fml/build_config.h"
#include "flutter/fml/log_settings.h"
#include "flutter/fml/logging.h"
#include "fml/log_level.h"
#include "gtest/gtest.h"
namespace fml {
namespace testing {
static_assert(fml::kLogFatal == fml::kLogNumSeverities - 1);
static_assert(fml::kLogImportant < fml::kLogFatal);
static_assert(fml::kLogImportant > fml::kLogError);
#ifndef OS_FUCHSIA
class MakeSureFmlLogDoesNotSegfaultWhenStaticallyCalled {
public:
MakeSureFmlLogDoesNotSegfaultWhenStaticallyCalled() {
SegfaultCatcher catcher;
// If this line causes a segfault, FML is using a method of logging that is
// not safe from static initialization on your platform.
FML_LOG(INFO)
<< "This log exists to verify that static logging from FML works.";
}
private:
struct SegfaultCatcher {
typedef void (*sighandler_t)(int);
SegfaultCatcher() {
handler = ::signal(SIGSEGV, SegfaultHandler);
FML_CHECK(handler != SIG_ERR);
}
~SegfaultCatcher() { FML_CHECK(::signal(SIGSEGV, handler) != SIG_ERR); }
static void SegfaultHandler(int signal) {
fprintf(stderr,
"FML failed to handle logging from static initialization.\n");
exit(signal);
}
sighandler_t handler;
};
};
static MakeSureFmlLogDoesNotSegfaultWhenStaticallyCalled fml_log_static_check_;
#endif // !defined(OS_FUCHSIA)
int UnreachableScopeWithoutReturnDoesNotMakeCompilerMad() {
KillProcess();
// return 0; <--- Missing but compiler is fine.
}
int UnreachableScopeWithMacroWithoutReturnDoesNotMakeCompilerMad() {
FML_UNREACHABLE();
// return 0; <--- Missing but compiler is fine.
}
TEST(LoggingTest, UnreachableKillProcess) {
::testing::FLAGS_gtest_death_test_style = "threadsafe";
ASSERT_DEATH(KillProcess(), "");
}
TEST(LoggingTest, UnreachableKillProcessWithMacro) {
::testing::FLAGS_gtest_death_test_style = "threadsafe";
ASSERT_DEATH({ FML_UNREACHABLE(); }, "");
}
#ifndef OS_FUCHSIA
TEST(LoggingTest, SanityTests) {
::testing::FLAGS_gtest_death_test_style = "threadsafe";
std::vector<std::string> severities = {"INFO", "WARNING", "ERROR",
"IMPORTANT"};
for (size_t i = 0; i < severities.size(); i++) {
LogCapture capture;
{
LogMessage log(i, "path/to/file.cc", 4, nullptr);
log.stream() << "Hello!";
}
EXPECT_EQ(capture.str(), std::string("[" + severities[i] +
":path/to/file.cc(4)] Hello!\n"));
}
ASSERT_DEATH(
{
LogMessage log(kLogFatal, "path/to/file.cc", 5, nullptr);
log.stream() << "Goodbye";
},
R"(\[FATAL:path/to/file.cc\(5\)\] Goodbye)");
}
#endif // !OS_FUCHSIA
} // namespace testing
} // namespace fml
| engine/fml/logging_unittests.cc/0 | {
"file_path": "engine/fml/logging_unittests.cc",
"repo_id": "engine",
"token_count": 1187
} | 177 |
// 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.
#ifndef FLUTTER_FML_NATIVE_LIBRARY_H_
#define FLUTTER_FML_NATIVE_LIBRARY_H_
#include <optional>
#include "flutter/fml/build_config.h"
#include "flutter/fml/macros.h"
#include "flutter/fml/memory/ref_counted.h"
#include "flutter/fml/memory/ref_ptr.h"
#if defined(FML_OS_WIN)
#include <windows.h>
#endif // defined(FML_OS_WIN)
namespace fml {
class NativeLibrary : public fml::RefCountedThreadSafe<NativeLibrary> {
public:
#if FML_OS_WIN
using Handle = HMODULE;
using SymbolHandle = FARPROC;
#else // FML_OS_WIN
using Handle = void*;
using SymbolHandle = void*;
#endif // FML_OS_WIN
static fml::RefPtr<NativeLibrary> Create(const char* path);
static fml::RefPtr<NativeLibrary> CreateWithHandle(
Handle handle,
bool close_handle_when_done);
static fml::RefPtr<NativeLibrary> CreateForCurrentProcess();
template <typename T>
const std::optional<T> ResolveFunction(const char* symbol) {
auto* resolved_symbol = Resolve(symbol);
if (!resolved_symbol) {
return std::nullopt;
}
return std::optional<T>(reinterpret_cast<T>(resolved_symbol));
}
const uint8_t* ResolveSymbol(const char* symbol) {
auto* resolved_symbol = reinterpret_cast<const uint8_t*>(Resolve(symbol));
if (resolved_symbol == nullptr) {
FML_DLOG(INFO) << "Could not resolve symbol in library: " << symbol;
}
return resolved_symbol;
}
private:
Handle handle_ = nullptr;
bool close_handle_ = true;
explicit NativeLibrary(const char* path);
NativeLibrary(Handle handle, bool close_handle);
~NativeLibrary();
Handle GetHandle() const;
SymbolHandle Resolve(const char* symbol) const;
FML_DISALLOW_COPY_AND_ASSIGN(NativeLibrary);
FML_FRIEND_REF_COUNTED_THREAD_SAFE(NativeLibrary);
FML_FRIEND_MAKE_REF_COUNTED(NativeLibrary);
};
} // namespace fml
#endif // FLUTTER_FML_NATIVE_LIBRARY_H_
| engine/fml/native_library.h/0 | {
"file_path": "engine/fml/native_library.h",
"repo_id": "engine",
"token_count": 733
} | 178 |
// 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.
#include <vector>
#include "flutter/fml/platform/darwin/scoped_nsautorelease_pool.h"
#include "flutter/fml/platform/darwin/scoped_nsobject.h"
#include "gtest/gtest.h"
namespace {
// This is to suppress the bugprone-use-after-move warning.
// This strategy is recommanded here:
// https://clang.llvm.org/extra/clang-tidy/checks/bugprone/use-after-move.html#silencing-erroneous-warnings
template <class T>
void IS_INITIALIZED(T&) {}
TEST(ScopedNSObjectTest, ScopedNSObject) {
fml::scoped_nsobject<NSObject> p1([[NSObject alloc] init]);
ASSERT_TRUE(p1.get());
ASSERT_EQ(1u, [p1 retainCount]);
fml::scoped_nsobject<NSObject> p2(p1);
ASSERT_EQ(p1.get(), p2.get());
ASSERT_EQ(2u, [p1 retainCount]);
p2.reset();
ASSERT_EQ(nil, p2.get());
ASSERT_EQ(1u, [p1 retainCount]);
{
fml::scoped_nsobject<NSObject> p3 = p1;
ASSERT_EQ(p1.get(), p3.get());
ASSERT_EQ(2u, [p1 retainCount]);
p3 = p1;
ASSERT_EQ(p1.get(), p3.get());
ASSERT_EQ(2u, [p1 retainCount]);
}
ASSERT_EQ(1u, [p1 retainCount]);
fml::scoped_nsobject<NSObject> p4([p1.get() retain]);
ASSERT_EQ(2u, [p1 retainCount]);
ASSERT_TRUE(p1 == p1.get());
ASSERT_TRUE(p1 == p1);
ASSERT_FALSE(p1 != p1);
ASSERT_FALSE(p1 != p1.get());
fml::scoped_nsobject<NSObject> p5([[NSObject alloc] init]);
ASSERT_TRUE(p1 != p5);
ASSERT_TRUE(p1 != p5.get());
ASSERT_FALSE(p1 == p5);
ASSERT_FALSE(p1 == p5.get());
fml::scoped_nsobject<NSObject> p6 = p1;
ASSERT_EQ(3u, [p6 retainCount]);
{
fml::ScopedNSAutoreleasePool pool;
p6.autorelease();
ASSERT_EQ(nil, p6.get());
ASSERT_EQ(3u, [p1 retainCount]);
}
ASSERT_EQ(2u, [p1 retainCount]);
fml::scoped_nsobject<NSObject> p7([[NSObject alloc] init]);
fml::scoped_nsobject<NSObject> p8(std::move(p7));
ASSERT_TRUE(p8);
ASSERT_EQ(1u, [p8 retainCount]);
IS_INITIALIZED(p7);
ASSERT_FALSE(p7.get());
}
// Instantiating scoped_nsobject<> with T=NSAutoreleasePool should trip a
// static_assert.
#if 0
TEST(ScopedNSObjectTest, FailToCreateScopedNSObjectAutoreleasePool) {
fml::scoped_nsobject<NSAutoreleasePool> pool;
}
#endif
TEST(ScopedNSObjectTest, ScopedNSObjectInContainer) {
fml::scoped_nsobject<id> p([[NSObject alloc] init]);
ASSERT_TRUE(p.get());
ASSERT_EQ(1u, [p retainCount]);
{
std::vector<fml::scoped_nsobject<id>> objects;
objects.push_back(p);
ASSERT_EQ(2u, [p retainCount]);
ASSERT_EQ(p.get(), objects[0].get());
objects.push_back(fml::scoped_nsobject<id>([[NSObject alloc] init]));
ASSERT_TRUE(objects[1].get());
ASSERT_EQ(1u, [objects[1] retainCount]);
}
ASSERT_EQ(1u, [p retainCount]);
}
TEST(ScopedNSObjectTest, ScopedNSObjectFreeFunctions) {
fml::scoped_nsobject<id> p1([[NSObject alloc] init]);
id o1 = p1.get();
ASSERT_TRUE(o1 == p1);
ASSERT_FALSE(o1 != p1);
fml::scoped_nsobject<id> p2([[NSObject alloc] init]);
ASSERT_TRUE(o1 != p2);
ASSERT_FALSE(o1 == p2);
id o2 = p2.get();
swap(p1, p2);
ASSERT_EQ(o2, p1.get());
ASSERT_EQ(o1, p2.get());
}
} // namespace
| engine/fml/platform/darwin/scoped_nsobject_unittests.mm/0 | {
"file_path": "engine/fml/platform/darwin/scoped_nsobject_unittests.mm",
"repo_id": "engine",
"token_count": 1449
} | 179 |
// 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.
#ifndef FLUTTER_FML_PLATFORM_FUCHSIA_MESSAGE_LOOP_FUCHSIA_H_
#define FLUTTER_FML_PLATFORM_FUCHSIA_MESSAGE_LOOP_FUCHSIA_H_
#include <lib/async-loop/cpp/loop.h>
#include <lib/async/cpp/wait.h>
#include <lib/zx/timer.h>
#include "flutter/fml/macros.h"
#include "flutter/fml/message_loop_impl.h"
namespace fml {
class MessageLoopFuchsia : public MessageLoopImpl {
private:
MessageLoopFuchsia();
~MessageLoopFuchsia() override;
void Run() override;
void Terminate() override;
void WakeUp(fml::TimePoint time_point) override;
async::Loop loop_;
std::unique_ptr<async::Wait> timer_wait_;
zx::timer timer_;
FML_FRIEND_MAKE_REF_COUNTED(MessageLoopFuchsia);
FML_FRIEND_REF_COUNTED_THREAD_SAFE(MessageLoopFuchsia);
FML_DISALLOW_COPY_AND_ASSIGN(MessageLoopFuchsia);
};
} // namespace fml
#endif // FLUTTER_FML_PLATFORM_FUCHSIA_MESSAGE_LOOP_FUCHSIA_H_
| engine/fml/platform/fuchsia/message_loop_fuchsia.h/0 | {
"file_path": "engine/fml/platform/fuchsia/message_loop_fuchsia.h",
"repo_id": "engine",
"token_count": 414
} | 180 |
// 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.
#include "flutter/fml/platform/posix/shared_mutex_posix.h"
#include "flutter/fml/logging.h"
namespace fml {
SharedMutex* SharedMutex::Create() {
return new SharedMutexPosix();
}
SharedMutexPosix::SharedMutexPosix() {
FML_CHECK(pthread_rwlock_init(&rwlock_, nullptr) == 0);
}
void SharedMutexPosix::Lock() {
pthread_rwlock_wrlock(&rwlock_);
}
void SharedMutexPosix::LockShared() {
pthread_rwlock_rdlock(&rwlock_);
}
void SharedMutexPosix::Unlock() {
pthread_rwlock_unlock(&rwlock_);
}
void SharedMutexPosix::UnlockShared() {
pthread_rwlock_unlock(&rwlock_);
}
} // namespace fml
| engine/fml/platform/posix/shared_mutex_posix.cc/0 | {
"file_path": "engine/fml/platform/posix/shared_mutex_posix.cc",
"repo_id": "engine",
"token_count": 287
} | 181 |
// 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.
#include "flutter/fml/platform/win/wstring_conversion.h"
#include "gtest/gtest.h"
namespace fml {
namespace testing {
TEST(StringConversion, Utf8ToWideStringEmpty) {
EXPECT_EQ(Utf8ToWideString(""), L"");
}
TEST(StringConversion, Utf8ToWideStringAscii) {
EXPECT_EQ(Utf8ToWideString("abc123"), L"abc123");
}
TEST(StringConversion, Utf8ToWideStringUnicode) {
EXPECT_EQ(Utf8ToWideString("\xe2\x98\x83"), L"\x2603");
}
TEST(StringConversion, WideStringToUtf8Empty) {
EXPECT_EQ(WideStringToUtf8(L""), "");
}
TEST(StringConversion, WideStringToUtf8Ascii) {
EXPECT_EQ(WideStringToUtf8(L"abc123"), "abc123");
}
TEST(StringConversion, WideStringToUtf8Unicode) {
EXPECT_EQ(WideStringToUtf8(L"\x2603"), "\xe2\x98\x83");
}
TEST(StringConversion, WideStringToUtf16Empty) {
EXPECT_EQ(WideStringToUtf16(L""), u"");
}
TEST(StringConversion, WideStringToUtf16Ascii) {
EXPECT_EQ(WideStringToUtf16(L"abc123"), u"abc123");
}
TEST(StringConversion, WideStringToUtf16Unicode) {
EXPECT_EQ(WideStringToUtf16(L"\xe2\x98\x83"), u"\xe2\x98\x83");
}
TEST(StringConversion, Utf16ToWideStringEmpty) {
EXPECT_EQ(Utf16ToWideString(u""), L"");
}
TEST(StringConversion, Utf16ToWideStringAscii) {
EXPECT_EQ(Utf16ToWideString(u"abc123"), L"abc123");
}
TEST(StringConversion, Utf16ToWideStringUtf8Unicode) {
EXPECT_EQ(Utf16ToWideString(u"\xe2\x98\x83"), L"\xe2\x98\x83");
}
} // namespace testing
} // namespace fml
| engine/fml/platform/win/wstring_conversion_unittests.cc/0 | {
"file_path": "engine/fml/platform/win/wstring_conversion_unittests.cc",
"repo_id": "engine",
"token_count": 681
} | 182 |
// 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.
#ifndef FLUTTER_FML_SYNCHRONIZATION_COUNT_DOWN_LATCH_H_
#define FLUTTER_FML_SYNCHRONIZATION_COUNT_DOWN_LATCH_H_
#include <atomic>
#include "flutter/fml/macros.h"
#include "flutter/fml/synchronization/waitable_event.h"
namespace fml {
class CountDownLatch {
public:
explicit CountDownLatch(size_t count);
~CountDownLatch();
void Wait();
void CountDown();
private:
std::atomic_size_t count_;
ManualResetWaitableEvent waitable_event_;
FML_DISALLOW_COPY_AND_ASSIGN(CountDownLatch);
};
} // namespace fml
#endif // FLUTTER_FML_SYNCHRONIZATION_COUNT_DOWN_LATCH_H_
| engine/fml/synchronization/count_down_latch.h/0 | {
"file_path": "engine/fml/synchronization/count_down_latch.h",
"repo_id": "engine",
"token_count": 278
} | 183 |
// 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.
#ifndef FLUTTER_FML_TASK_RUNNER_H_
#define FLUTTER_FML_TASK_RUNNER_H_
#include "flutter/fml/closure.h"
#include "flutter/fml/macros.h"
#include "flutter/fml/memory/ref_counted.h"
#include "flutter/fml/memory/ref_ptr.h"
#include "flutter/fml/message_loop_task_queues.h"
#include "flutter/fml/time/time_point.h"
namespace fml {
class MessageLoopImpl;
/// An interface over the ability to schedule tasks on a \p TaskRunner.
class BasicTaskRunner {
public:
/// Schedules \p task to be executed on the TaskRunner's associated event
/// loop.
virtual void PostTask(const fml::closure& task) = 0;
};
/// The object for scheduling tasks on a \p fml::MessageLoop.
///
/// Typically there is one \p TaskRunner associated with each thread. When one
/// wants to execute an operation on that thread they post a task to the
/// TaskRunner.
///
/// \see fml::MessageLoop
class TaskRunner : public fml::RefCountedThreadSafe<TaskRunner>,
public BasicTaskRunner {
public:
virtual ~TaskRunner();
virtual void PostTask(const fml::closure& task) override;
virtual void PostTaskForTime(const fml::closure& task,
fml::TimePoint target_time);
/// Schedules a task to be run on the MessageLoop after the time \p delay has
/// passed.
/// \note There is latency between when the task is schedule and actually
/// executed so that the actual execution time is: now + delay +
/// message_loop_latency, where message_loop_latency is undefined and could be
/// tens of milliseconds.
virtual void PostDelayedTask(const fml::closure& task, fml::TimeDelta delay);
/// Returns \p true when the current executing thread's TaskRunner matches
/// this instance.
virtual bool RunsTasksOnCurrentThread();
/// Returns the unique identifier associated with the TaskRunner.
/// \see fml::MessageLoopTaskQueues
virtual TaskQueueId GetTaskQueueId();
/// Executes the \p task directly if the TaskRunner \p runner is the
/// TaskRunner associated with the current executing thread.
static void RunNowOrPostTask(const fml::RefPtr<fml::TaskRunner>& runner,
const fml::closure& task);
protected:
explicit TaskRunner(fml::RefPtr<MessageLoopImpl> loop);
private:
fml::RefPtr<MessageLoopImpl> loop_;
FML_FRIEND_MAKE_REF_COUNTED(TaskRunner);
FML_FRIEND_REF_COUNTED_THREAD_SAFE(TaskRunner);
FML_DISALLOW_COPY_AND_ASSIGN(TaskRunner);
};
} // namespace fml
#endif // FLUTTER_FML_TASK_RUNNER_H_
| engine/fml/task_runner.h/0 | {
"file_path": "engine/fml/task_runner.h",
"repo_id": "engine",
"token_count": 871
} | 184 |
// 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.
#ifndef FLUTTER_FML_TIME_TIMESTAMP_PROVIDER_H_
#define FLUTTER_FML_TIME_TIMESTAMP_PROVIDER_H_
#include <cstdint>
#include "flutter/fml/time/time_point.h"
namespace fml {
/// Pluggable provider of monotonic timestamps. Invocations of `Now` must return
/// unique values. Any two consecutive invocations must be ordered.
class TimestampProvider {
public:
virtual ~TimestampProvider(){};
// Returns the number of ticks elapsed by a monotonic clock since epoch.
virtual fml::TimePoint Now() = 0;
};
} // namespace fml
#endif // FLUTTER_FML_TIME_TIMESTAMP_PROVIDER_H_
| engine/fml/time/timestamp_provider.h/0 | {
"file_path": "engine/fml/time/timestamp_provider.h",
"repo_id": "engine",
"token_count": 240
} | 185 |
// 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.
#include "flutter/impeller/aiks/aiks_unittests.h"
#include "impeller/aiks/canvas.h"
#include "impeller/geometry/path_builder.h"
#include "impeller/playground/widgets.h"
#include "third_party/imgui/imgui.h"
////////////////////////////////////////////////////////////////////////////////
// This is for tests of Canvas that are interested the results of rendering
// paths.
////////////////////////////////////////////////////////////////////////////////
namespace impeller {
namespace testing {
TEST_P(AiksTest, RotateColorFilteredPath) {
Canvas canvas;
canvas.Concat(Matrix::MakeTranslation({300, 300}));
canvas.Concat(Matrix::MakeRotationZ(Radians(kPiOver2)));
auto arrow_stem =
PathBuilder{}.MoveTo({120, 190}).LineTo({120, 50}).TakePath();
auto arrow_head = PathBuilder{}
.MoveTo({50, 120})
.LineTo({120, 190})
.LineTo({190, 120})
.TakePath();
auto paint = Paint{
.stroke_width = 15.0,
.stroke_cap = Cap::kRound,
.stroke_join = Join::kRound,
.style = Paint::Style::kStroke,
.color_filter =
ColorFilter::MakeBlend(BlendMode::kSourceIn, Color::AliceBlue()),
};
canvas.DrawPath(arrow_stem, paint);
canvas.DrawPath(arrow_head, paint);
ASSERT_TRUE(OpenPlaygroundHere(canvas.EndRecordingAsPicture()));
}
TEST_P(AiksTest, CanRenderStrokes) {
Canvas canvas;
Paint paint;
paint.color = Color::Red();
paint.stroke_width = 20.0;
paint.style = Paint::Style::kStroke;
canvas.DrawPath(PathBuilder{}.AddLine({200, 100}, {800, 100}).TakePath(),
paint);
ASSERT_TRUE(OpenPlaygroundHere(canvas.EndRecordingAsPicture()));
}
TEST_P(AiksTest, CanRenderCurvedStrokes) {
Canvas canvas;
Paint paint;
paint.color = Color::Red();
paint.stroke_width = 25.0;
paint.style = Paint::Style::kStroke;
canvas.DrawPath(PathBuilder{}.AddCircle({500, 500}, 250).TakePath(), paint);
ASSERT_TRUE(OpenPlaygroundHere(canvas.EndRecordingAsPicture()));
}
TEST_P(AiksTest, CanRenderThickCurvedStrokes) {
Canvas canvas;
Paint paint;
paint.color = Color::Red();
paint.stroke_width = 100.0;
paint.style = Paint::Style::kStroke;
canvas.DrawPath(PathBuilder{}.AddCircle({100, 100}, 50).TakePath(), paint);
ASSERT_TRUE(OpenPlaygroundHere(canvas.EndRecordingAsPicture()));
}
TEST_P(AiksTest, CanRenderStrokePathThatEndsAtSharpTurn) {
Canvas canvas;
Paint paint;
paint.color = Color::Red();
paint.style = Paint::Style::kStroke;
paint.stroke_width = 200;
Rect rect = Rect::MakeXYWH(100, 100, 200, 200);
PathBuilder builder;
builder.AddArc(rect, Degrees(0), Degrees(90), false);
canvas.DrawPath(builder.TakePath(), paint);
ASSERT_TRUE(OpenPlaygroundHere(canvas.EndRecordingAsPicture()));
}
TEST_P(AiksTest, CanRenderStrokePathWithCubicLine) {
Canvas canvas;
Paint paint;
paint.color = Color::Red();
paint.style = Paint::Style::kStroke;
paint.stroke_width = 20;
PathBuilder builder;
builder.AddCubicCurve({0, 200}, {50, 400}, {350, 0}, {400, 200});
canvas.DrawPath(builder.TakePath(), paint);
ASSERT_TRUE(OpenPlaygroundHere(canvas.EndRecordingAsPicture()));
}
TEST_P(AiksTest, CanRenderDifferencePaths) {
Canvas canvas;
Paint paint;
paint.color = Color::Red();
PathBuilder builder;
PathBuilder::RoundingRadii radii;
radii.top_left = {50, 25};
radii.top_right = {25, 50};
radii.bottom_right = {50, 25};
radii.bottom_left = {25, 50};
builder.AddRoundedRect(Rect::MakeXYWH(100, 100, 200, 200), radii);
builder.AddCircle({200, 200}, 50);
auto path = builder.TakePath(FillType::kOdd);
canvas.DrawImage(
std::make_shared<Image>(CreateTextureForFixture("boston.jpg")), {10, 10},
Paint{});
canvas.DrawPath(path, paint);
ASSERT_TRUE(OpenPlaygroundHere(canvas.EndRecordingAsPicture()));
}
// Regression test for https://github.com/flutter/flutter/issues/134816.
//
// It should be possible to draw 3 lines, and not have an implicit close path.
TEST_P(AiksTest, CanDrawAnOpenPath) {
Canvas canvas;
// Starting at (50, 50), draw lines from:
// 1. (50, height)
// 2. (width, height)
// 3. (width, 50)
PathBuilder builder;
builder.MoveTo({50, 50});
builder.LineTo({50, 100});
builder.LineTo({100, 100});
builder.LineTo({100, 50});
Paint paint;
paint.color = Color::Red();
paint.style = Paint::Style::kStroke;
paint.stroke_width = 10;
canvas.DrawPath(builder.TakePath(), paint);
ASSERT_TRUE(OpenPlaygroundHere(canvas.EndRecordingAsPicture()));
}
TEST_P(AiksTest, CanDrawAnOpenPathThatIsntARect) {
Canvas canvas;
// Draw a stroked path that is explicitly closed to verify
// It doesn't become a rectangle.
PathBuilder builder;
builder.MoveTo({50, 50});
builder.LineTo({520, 120});
builder.LineTo({300, 310});
builder.LineTo({100, 50});
builder.Close();
Paint paint;
paint.color = Color::Red();
paint.style = Paint::Style::kStroke;
paint.stroke_width = 10;
canvas.DrawPath(builder.TakePath(), paint);
ASSERT_TRUE(OpenPlaygroundHere(canvas.EndRecordingAsPicture()));
}
TEST_P(AiksTest, SolidStrokesRenderCorrectly) {
// Compare with https://fiddle.skia.org/c/027392122bec8ac2b5d5de00a4b9bbe2
auto callback = [&](AiksContext& renderer) -> std::optional<Picture> {
static Color color = Color::Black().WithAlpha(0.5);
static float scale = 3;
static bool add_circle_clip = true;
if (AiksTest::ImGuiBegin("Controls", nullptr,
ImGuiWindowFlags_AlwaysAutoResize)) {
ImGui::ColorEdit4("Color", reinterpret_cast<float*>(&color));
ImGui::SliderFloat("Scale", &scale, 0, 6);
ImGui::Checkbox("Circle clip", &add_circle_clip);
ImGui::End();
}
Canvas canvas;
canvas.Scale(GetContentScale());
Paint paint;
paint.color = Color::White();
canvas.DrawPaint(paint);
paint.color = color;
paint.style = Paint::Style::kStroke;
paint.stroke_width = 10;
Path path = PathBuilder{}
.MoveTo({20, 20})
.QuadraticCurveTo({60, 20}, {60, 60})
.Close()
.MoveTo({60, 20})
.QuadraticCurveTo({60, 60}, {20, 60})
.TakePath();
canvas.Scale(Vector2(scale, scale));
if (add_circle_clip) {
static PlaygroundPoint circle_clip_point_a(Point(60, 300), 20,
Color::Red());
static PlaygroundPoint circle_clip_point_b(Point(600, 300), 20,
Color::Red());
auto [handle_a, handle_b] =
DrawPlaygroundLine(circle_clip_point_a, circle_clip_point_b);
auto screen_to_canvas = canvas.GetCurrentTransform().Invert();
Point point_a = screen_to_canvas * handle_a * GetContentScale();
Point point_b = screen_to_canvas * handle_b * GetContentScale();
Point middle = (point_a + point_b) / 2;
auto radius = point_a.GetDistance(middle);
canvas.ClipPath(PathBuilder{}.AddCircle(middle, radius).TakePath());
}
for (auto join : {Join::kBevel, Join::kRound, Join::kMiter}) {
paint.stroke_join = join;
for (auto cap : {Cap::kButt, Cap::kSquare, Cap::kRound}) {
paint.stroke_cap = cap;
canvas.DrawPath(path, paint);
canvas.Translate({80, 0});
}
canvas.Translate({-240, 60});
}
return canvas.EndRecordingAsPicture();
};
ASSERT_TRUE(OpenPlaygroundHere(callback));
}
TEST_P(AiksTest, DrawLinesRenderCorrectly) {
Canvas canvas;
canvas.Scale(GetContentScale());
Paint paint;
paint.color = Color::Blue();
paint.stroke_width = 10;
auto draw = [&canvas](Paint& paint) {
for (auto cap : {Cap::kButt, Cap::kSquare, Cap::kRound}) {
paint.stroke_cap = cap;
Point origin = {100, 100};
Point p0 = {50, 0};
Point p1 = {150, 0};
canvas.DrawLine({150, 100}, {250, 100}, paint);
for (int d = 15; d < 90; d += 15) {
Matrix m = Matrix::MakeRotationZ(Degrees(d));
canvas.DrawLine(origin + m * p0, origin + m * p1, paint);
}
canvas.DrawLine({100, 150}, {100, 250}, paint);
canvas.DrawCircle({origin}, 35, paint);
canvas.DrawLine({250, 250}, {250, 250}, paint);
canvas.Translate({250, 0});
}
canvas.Translate({-750, 250});
};
std::vector<Color> colors = {
Color{0x1f / 255.0, 0.0, 0x5c / 255.0, 1.0},
Color{0x5b / 255.0, 0.0, 0x60 / 255.0, 1.0},
Color{0x87 / 255.0, 0x01 / 255.0, 0x60 / 255.0, 1.0},
Color{0xac / 255.0, 0x25 / 255.0, 0x53 / 255.0, 1.0},
Color{0xe1 / 255.0, 0x6b / 255.0, 0x5c / 255.0, 1.0},
Color{0xf3 / 255.0, 0x90 / 255.0, 0x60 / 255.0, 1.0},
Color{0xff / 255.0, 0xb5 / 255.0, 0x6b / 250.0, 1.0}};
std::vector<Scalar> stops = {
0.0,
(1.0 / 6.0) * 1,
(1.0 / 6.0) * 2,
(1.0 / 6.0) * 3,
(1.0 / 6.0) * 4,
(1.0 / 6.0) * 5,
1.0,
};
auto texture = CreateTextureForFixture("airplane.jpg",
/*enable_mipmapping=*/true);
draw(paint);
paint.color_source = ColorSource::MakeRadialGradient(
{100, 100}, 200, std::move(colors), std::move(stops),
Entity::TileMode::kMirror, {});
draw(paint);
paint.color_source = ColorSource::MakeImage(
texture, Entity::TileMode::kRepeat, Entity::TileMode::kRepeat, {},
Matrix::MakeTranslation({-150, 75}));
draw(paint);
ASSERT_TRUE(OpenPlaygroundHere(canvas.EndRecordingAsPicture()));
}
TEST_P(AiksTest, DrawRectStrokesRenderCorrectly) {
Canvas canvas;
Paint paint;
paint.color = Color::Red();
paint.style = Paint::Style::kStroke;
paint.stroke_width = 10;
canvas.Translate({100, 100});
canvas.DrawPath(
PathBuilder{}.AddRect(Rect::MakeSize(Size{100, 100})).TakePath(),
{paint});
ASSERT_TRUE(OpenPlaygroundHere(canvas.EndRecordingAsPicture()));
}
TEST_P(AiksTest, DrawRectStrokesWithBevelJoinRenderCorrectly) {
Canvas canvas;
Paint paint;
paint.color = Color::Red();
paint.style = Paint::Style::kStroke;
paint.stroke_width = 10;
paint.stroke_join = Join::kBevel;
canvas.Translate({100, 100});
canvas.DrawPath(
PathBuilder{}.AddRect(Rect::MakeSize(Size{100, 100})).TakePath(),
{paint});
ASSERT_TRUE(OpenPlaygroundHere(canvas.EndRecordingAsPicture()));
}
TEST_P(AiksTest, CanDrawMultiContourConvexPath) {
PathBuilder builder = {};
for (auto i = 0; i < 10; i++) {
if (i % 2 == 0) {
builder.AddCircle(Point(100 + 50 * i, 100 + 50 * i), 100);
} else {
builder.MoveTo({100.f + 50.f * i - 100, 100.f + 50.f * i});
builder.LineTo({100.f + 50.f * i, 100.f + 50.f * i - 100});
builder.LineTo({100.f + 50.f * i - 100, 100.f + 50.f * i - 100});
builder.Close();
}
}
builder.SetConvexity(Convexity::kConvex);
Canvas canvas;
canvas.DrawPath(builder.TakePath(), {.color = Color::Red().WithAlpha(0.4)});
ASSERT_TRUE(OpenPlaygroundHere(canvas.EndRecordingAsPicture()));
}
TEST_P(AiksTest, ArcWithZeroSweepAndBlur) {
Canvas canvas;
canvas.Scale(GetContentScale());
Paint paint;
paint.color = Color::Red();
std::vector<Color> colors = {Color{1.0, 0.0, 0.0, 1.0},
Color{0.0, 0.0, 0.0, 1.0}};
std::vector<Scalar> stops = {0.0, 1.0};
paint.color_source = ColorSource::MakeSweepGradient(
{100, 100}, Degrees(45), Degrees(135), std::move(colors),
std::move(stops), Entity::TileMode::kMirror, {});
paint.mask_blur_descriptor = Paint::MaskBlurDescriptor{
.style = FilterContents::BlurStyle::kNormal,
.sigma = Sigma(20),
};
PathBuilder builder;
builder.AddArc(Rect::MakeXYWH(10, 10, 100, 100), Degrees(0), Degrees(0),
false);
canvas.DrawPath(builder.TakePath(), paint);
// Check that this empty picture can be created without crashing.
canvas.EndRecordingAsPicture();
}
TEST_P(AiksTest, CanRenderClips) {
Canvas canvas;
Paint paint;
paint.color = Color::Fuchsia();
canvas.ClipPath(
PathBuilder{}.AddRect(Rect::MakeXYWH(0, 0, 500, 500)).TakePath());
canvas.DrawPath(PathBuilder{}.AddCircle({500, 500}, 250).TakePath(), paint);
ASSERT_TRUE(OpenPlaygroundHere(canvas.EndRecordingAsPicture()));
}
TEST_P(AiksTest, CanRenderOverlappingMultiContourPath) {
Canvas canvas;
Paint paint;
paint.color = Color::Red();
PathBuilder::RoundingRadii radii;
radii.top_left = {50, 50};
radii.top_right = {50, 50};
radii.bottom_right = {50, 50};
radii.bottom_left = {50, 50};
const Scalar kTriangleHeight = 100;
canvas.Translate(Vector2(200, 200));
// Form a path similar to the Material drop slider value indicator. Both
// shapes should render identically side-by-side.
{
auto path =
PathBuilder{}
.MoveTo({0, kTriangleHeight})
.LineTo({-kTriangleHeight / 2.0f, 0})
.LineTo({kTriangleHeight / 2.0f, 0})
.Close()
.AddRoundedRect(
Rect::MakeXYWH(-kTriangleHeight / 2.0f, -kTriangleHeight / 2.0f,
kTriangleHeight, kTriangleHeight),
radii)
.TakePath();
canvas.DrawPath(path, paint);
}
canvas.Translate(Vector2(100, 0));
{
auto path =
PathBuilder{}
.MoveTo({0, kTriangleHeight})
.LineTo({-kTriangleHeight / 2.0f, 0})
.LineTo({0, -10})
.LineTo({kTriangleHeight / 2.0f, 0})
.Close()
.AddRoundedRect(
Rect::MakeXYWH(-kTriangleHeight / 2.0f, -kTriangleHeight / 2.0f,
kTriangleHeight, kTriangleHeight),
radii)
.TakePath();
canvas.DrawPath(path, paint);
}
ASSERT_TRUE(OpenPlaygroundHere(canvas.EndRecordingAsPicture()));
}
} // namespace testing
} // namespace impeller
| engine/impeller/aiks/aiks_path_unittests.cc/0 | {
"file_path": "engine/impeller/aiks/aiks_path_unittests.cc",
"repo_id": "engine",
"token_count": 5945
} | 186 |
// 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.
#include "impeller/aiks/color_source.h"
#include <memory>
#include <vector>
#include "impeller/aiks/paint.h"
#include "impeller/core/sampler_descriptor.h"
#include "impeller/entity/contents/conical_gradient_contents.h"
#include "impeller/entity/contents/filters/color_filter_contents.h"
#include "impeller/entity/contents/linear_gradient_contents.h"
#include "impeller/entity/contents/radial_gradient_contents.h"
#include "impeller/entity/contents/runtime_effect_contents.h"
#include "impeller/entity/contents/solid_color_contents.h"
#include "impeller/entity/contents/sweep_gradient_contents.h"
#include "impeller/entity/contents/tiled_texture_contents.h"
#include "impeller/geometry/color.h"
#include "impeller/geometry/matrix.h"
#include "impeller/geometry/scalar.h"
#include "impeller/runtime_stage/runtime_stage.h"
#if IMPELLER_ENABLE_3D
#include "impeller/entity/contents/scene_contents.h" // nogncheck
#include "impeller/scene/node.h" // nogncheck
#endif // IMPELLER_ENABLE_3D
namespace impeller {
ColorSource::ColorSource() noexcept
: proc_([](const Paint& paint) -> std::shared_ptr<ColorSourceContents> {
auto contents = std::make_shared<SolidColorContents>();
contents->SetColor(paint.color);
return contents;
}){};
ColorSource::~ColorSource() = default;
ColorSource ColorSource::MakeColor() {
return {};
}
ColorSource ColorSource::MakeLinearGradient(Point start_point,
Point end_point,
std::vector<Color> colors,
std::vector<Scalar> stops,
Entity::TileMode tile_mode,
Matrix effect_transform) {
ColorSource result;
result.type_ = Type::kLinearGradient;
result.proc_ = [start_point, end_point, colors = std::move(colors),
stops = std::move(stops), tile_mode,
effect_transform](const Paint& paint) {
auto contents = std::make_shared<LinearGradientContents>();
contents->SetOpacityFactor(paint.color.alpha);
contents->SetColors(colors);
contents->SetStops(stops);
contents->SetEndPoints(start_point, end_point);
contents->SetTileMode(tile_mode);
contents->SetEffectTransform(effect_transform);
std::vector<Point> bounds{start_point, end_point};
auto intrinsic_size = Rect::MakePointBounds(bounds.begin(), bounds.end());
if (intrinsic_size.has_value()) {
contents->SetColorSourceSize(intrinsic_size->GetSize());
}
return contents;
};
return result;
}
ColorSource ColorSource::MakeConicalGradient(Point center,
Scalar radius,
std::vector<Color> colors,
std::vector<Scalar> stops,
Point focus_center,
Scalar focus_radius,
Entity::TileMode tile_mode,
Matrix effect_transform) {
ColorSource result;
result.type_ = Type::kConicalGradient;
result.proc_ = [center, radius, colors = std::move(colors),
stops = std::move(stops), focus_center, focus_radius,
tile_mode, effect_transform](const Paint& paint) {
std::shared_ptr<ConicalGradientContents> contents =
std::make_shared<ConicalGradientContents>();
contents->SetOpacityFactor(paint.color.alpha);
contents->SetColors(colors);
contents->SetStops(stops);
contents->SetCenterAndRadius(center, radius);
contents->SetTileMode(tile_mode);
contents->SetEffectTransform(effect_transform);
contents->SetFocus(focus_center, focus_radius);
auto radius_pt = Point(radius, radius);
std::vector<Point> bounds{center + radius_pt, center - radius_pt};
auto intrinsic_size = Rect::MakePointBounds(bounds.begin(), bounds.end());
if (intrinsic_size.has_value()) {
contents->SetColorSourceSize(intrinsic_size->GetSize());
}
return contents;
};
return result;
}
ColorSource ColorSource::MakeRadialGradient(Point center,
Scalar radius,
std::vector<Color> colors,
std::vector<Scalar> stops,
Entity::TileMode tile_mode,
Matrix effect_transform) {
ColorSource result;
result.type_ = Type::kRadialGradient;
result.proc_ = [center, radius, colors = std::move(colors),
stops = std::move(stops), tile_mode,
effect_transform](const Paint& paint) {
auto contents = std::make_shared<RadialGradientContents>();
contents->SetOpacityFactor(paint.color.alpha);
contents->SetColors(colors);
contents->SetStops(stops);
contents->SetCenterAndRadius(center, radius);
contents->SetTileMode(tile_mode);
contents->SetEffectTransform(effect_transform);
auto radius_pt = Point(radius, radius);
std::vector<Point> bounds{center + radius_pt, center - radius_pt};
auto intrinsic_size = Rect::MakePointBounds(bounds.begin(), bounds.end());
if (intrinsic_size.has_value()) {
contents->SetColorSourceSize(intrinsic_size->GetSize());
}
return contents;
};
return result;
}
ColorSource ColorSource::MakeSweepGradient(Point center,
Degrees start_angle,
Degrees end_angle,
std::vector<Color> colors,
std::vector<Scalar> stops,
Entity::TileMode tile_mode,
Matrix effect_transform) {
ColorSource result;
result.type_ = Type::kSweepGradient;
result.proc_ = [center, start_angle, end_angle, colors = std::move(colors),
stops = std::move(stops), tile_mode,
effect_transform](const Paint& paint) {
auto contents = std::make_shared<SweepGradientContents>();
contents->SetOpacityFactor(paint.color.alpha);
contents->SetCenterAndAngles(center, start_angle, end_angle);
contents->SetColors(colors);
contents->SetStops(stops);
contents->SetTileMode(tile_mode);
contents->SetEffectTransform(effect_transform);
return contents;
};
return result;
}
ColorSource ColorSource::MakeImage(std::shared_ptr<Texture> texture,
Entity::TileMode x_tile_mode,
Entity::TileMode y_tile_mode,
SamplerDescriptor sampler_descriptor,
Matrix effect_transform) {
ColorSource result;
result.type_ = Type::kImage;
result.proc_ = [texture = std::move(texture), x_tile_mode, y_tile_mode,
sampler_descriptor = std::move(sampler_descriptor),
effect_transform](const Paint& paint) {
auto contents = std::make_shared<TiledTextureContents>();
contents->SetOpacityFactor(paint.color.alpha);
contents->SetTexture(texture);
contents->SetTileModes(x_tile_mode, y_tile_mode);
contents->SetSamplerDescriptor(sampler_descriptor);
contents->SetEffectTransform(effect_transform);
if (paint.color_filter) {
TiledTextureContents::ColorFilterProc filter_proc =
[color_filter = paint.color_filter](FilterInput::Ref input) {
return color_filter->WrapWithGPUColorFilter(
std::move(input), ColorFilterContents::AbsorbOpacity::kNo);
};
contents->SetColorFilter(filter_proc);
}
contents->SetColorSourceSize(Size::Ceil(texture->GetSize()));
return contents;
};
return result;
}
ColorSource ColorSource::MakeRuntimeEffect(
std::shared_ptr<RuntimeStage> runtime_stage,
std::shared_ptr<std::vector<uint8_t>> uniform_data,
std::vector<RuntimeEffectContents::TextureInput> texture_inputs) {
ColorSource result;
result.type_ = Type::kRuntimeEffect;
result.proc_ = [runtime_stage = std::move(runtime_stage),
uniform_data = std::move(uniform_data),
texture_inputs =
std::move(texture_inputs)](const Paint& paint) {
auto contents = std::make_shared<RuntimeEffectContents>();
contents->SetOpacityFactor(paint.color.alpha);
contents->SetRuntimeStage(runtime_stage);
contents->SetUniformData(uniform_data);
contents->SetTextureInputs(texture_inputs);
return contents;
};
return result;
}
#if IMPELLER_ENABLE_3D
ColorSource ColorSource::MakeScene(std::shared_ptr<scene::Node> scene_node,
Matrix camera_transform) {
ColorSource result;
result.type_ = Type::kScene;
result.proc_ = [scene_node = std::move(scene_node),
camera_transform](const Paint& paint) {
auto contents = std::make_shared<SceneContents>();
contents->SetOpacityFactor(paint.color.alpha);
contents->SetNode(scene_node);
contents->SetCameraTransform(camera_transform);
return contents;
};
return result;
}
#endif // IMPELLER_ENABLE_3D
ColorSource::Type ColorSource::GetType() const {
return type_;
}
std::shared_ptr<ColorSourceContents> ColorSource::GetContents(
const Paint& paint) const {
return proc_(paint);
}
} // namespace impeller
| engine/impeller/aiks/color_source.cc/0 | {
"file_path": "engine/impeller/aiks/color_source.cc",
"repo_id": "engine",
"token_count": 4358
} | 187 |
// 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.
#ifndef FLUTTER_IMPELLER_AIKS_TESTING_CONTEXT_SPY_H_
#define FLUTTER_IMPELLER_AIKS_TESTING_CONTEXT_SPY_H_
#include <memory>
#include "impeller/aiks/testing/context_mock.h"
#include "impeller/entity/contents/test/recording_render_pass.h"
#include "impeller/renderer/command_queue.h"
namespace impeller {
namespace testing {
class NoopCommandQueue : public CommandQueue {
public:
fml::Status Submit(
const std::vector<std::shared_ptr<CommandBuffer>>& buffers,
const CompletionCallback& completion_callback = {}) override;
};
/// Forwards calls to a real Context but can store information about how
/// the Context was used.
class ContextSpy : public std::enable_shared_from_this<ContextSpy> {
public:
static std::shared_ptr<ContextSpy> Make();
std::shared_ptr<ContextMock> MakeContext(
const std::shared_ptr<Context>& real_context);
std::vector<std::shared_ptr<RecordingRenderPass>> render_passes_;
std::shared_ptr<CommandQueue> command_queue_ =
std::make_shared<NoopCommandQueue>();
private:
ContextSpy() = default;
};
} // namespace testing
} // namespace impeller
#endif // FLUTTER_IMPELLER_AIKS_TESTING_CONTEXT_SPY_H_
| engine/impeller/aiks/testing/context_spy.h/0 | {
"file_path": "engine/impeller/aiks/testing/context_spy.h",
"repo_id": "engine",
"token_count": 463
} | 188 |
// 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.
#include "impeller/base/strings.h"
#include <cstdarg>
namespace impeller {
IMPELLER_PRINTF_FORMAT(1, 2)
std::string SPrintF(const char* format, ...) {
std::string ret_val;
va_list list;
va_list list2;
va_start(list, format);
va_copy(list2, list);
if (auto string_length = ::vsnprintf(nullptr, 0, format, list);
string_length >= 0) {
auto buffer = reinterpret_cast<char*>(::malloc(string_length + 1));
::vsnprintf(buffer, string_length + 1, format, list2);
ret_val = std::string{buffer, static_cast<size_t>(string_length)};
::free(buffer);
}
va_end(list2);
va_end(list);
return ret_val;
}
bool HasPrefix(const std::string& string, const std::string& prefix) {
return string.find(prefix) == 0u;
}
bool HasSuffix(const std::string& string, const std::string& suffix) {
auto position = string.rfind(suffix);
if (position == std::string::npos) {
return false;
}
return position == string.size() - suffix.size();
}
std::string StripPrefix(const std::string& string,
const std::string& to_strip) {
if (!HasPrefix(string, to_strip)) {
return string;
}
return string.substr(to_strip.length());
}
} // namespace impeller
| engine/impeller/base/strings.cc/0 | {
"file_path": "engine/impeller/base/strings.cc",
"repo_id": "engine",
"token_count": 511
} | 189 |
// 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.
#include "impeller/compiler/compiler_backend.h"
#include "impeller/base/comparable.h"
namespace impeller {
namespace compiler {
CompilerBackend::CompilerBackend(MSLCompiler compiler)
: CompilerBackend(Type::kMSL, compiler) {}
CompilerBackend::CompilerBackend(GLSLCompiler compiler)
: CompilerBackend(compiler->get_common_options().vulkan_semantics
? Type::kGLSLVulkan
: Type::kGLSL,
compiler) {}
CompilerBackend::CompilerBackend(SkSLCompiler compiler)
: CompilerBackend(Type::kSkSL, compiler) {}
CompilerBackend::CompilerBackend() = default;
CompilerBackend::CompilerBackend(Type type, Compiler compiler)
: type_(type), compiler_(std::move(compiler)){};
CompilerBackend::~CompilerBackend() = default;
const spirv_cross::Compiler* CompilerBackend::operator->() const {
return GetCompiler();
}
uint32_t CompilerBackend::GetExtendedMSLResourceBinding(
ExtendedResourceIndex index,
spirv_cross::ID id) const {
if (auto compiler = GetMSLCompiler()) {
switch (index) {
case ExtendedResourceIndex::kPrimary:
return compiler->get_automatic_msl_resource_binding(id);
case ExtendedResourceIndex::kSecondary:
return compiler->get_automatic_msl_resource_binding_secondary(id);
break;
}
}
if (auto compiler = GetGLSLCompiler()) {
return compiler->get_decoration(id, spv::Decoration::DecorationBinding);
}
const auto kOOBIndex = static_cast<uint32_t>(-1);
return kOOBIndex;
}
const spirv_cross::Compiler* CompilerBackend::GetCompiler() const {
if (auto compiler = GetGLSLCompiler()) {
return compiler;
}
if (auto compiler = GetMSLCompiler()) {
return compiler;
}
if (auto compiler = GetSkSLCompiler()) {
return compiler;
}
return nullptr;
}
spirv_cross::Compiler* CompilerBackend::GetCompiler() {
if (auto* msl = std::get_if<MSLCompiler>(&compiler_)) {
return msl->get();
}
if (auto* glsl = std::get_if<GLSLCompiler>(&compiler_)) {
return glsl->get();
}
if (auto* sksl = std::get_if<SkSLCompiler>(&compiler_)) {
return sksl->get();
}
return nullptr;
}
const spirv_cross::CompilerMSL* CompilerBackend::GetMSLCompiler() const {
if (auto* msl = std::get_if<MSLCompiler>(&compiler_)) {
return msl->get();
}
return nullptr;
}
const spirv_cross::CompilerGLSL* CompilerBackend::GetGLSLCompiler() const {
if (auto* glsl = std::get_if<GLSLCompiler>(&compiler_)) {
return glsl->get();
}
return nullptr;
}
const CompilerSkSL* CompilerBackend::GetSkSLCompiler() const {
if (auto* sksl = std::get_if<SkSLCompiler>(&compiler_)) {
return sksl->get();
}
return nullptr;
}
CompilerBackend::operator bool() const {
return !!GetCompiler();
}
CompilerBackend::Type CompilerBackend::GetType() const {
return type_;
}
} // namespace compiler
} // namespace impeller
| engine/impeller/compiler/compiler_backend.cc/0 | {
"file_path": "engine/impeller/compiler/compiler_backend.cc",
"repo_id": "engine",
"token_count": 1175
} | 190 |
// 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.
#include "impeller/compiler/shader_bundle.h"
#include "impeller/compiler/compiler.h"
#include "impeller/compiler/reflector.h"
#include "impeller/compiler/source_options.h"
#include "impeller/compiler/types.h"
#include "impeller/compiler/utilities.h"
#include "impeller/runtime_stage/runtime_stage.h"
#include "impeller/shader_bundle/shader_bundle_flatbuffers.h"
#include "third_party/json/include/nlohmann/json.hpp"
namespace impeller {
namespace compiler {
std::optional<ShaderBundleConfig> ParseShaderBundleConfig(
const std::string& bundle_config_json,
std::ostream& error_stream) {
auto json = nlohmann::json::parse(bundle_config_json, nullptr, false);
if (json.is_discarded() || !json.is_object()) {
error_stream << "The shader bundle is not a valid JSON object."
<< std::endl;
return std::nullopt;
}
ShaderBundleConfig bundle;
for (auto& [shader_name, shader_value] : json.items()) {
if (bundle.find(shader_name) != bundle.end()) {
error_stream << "Duplicate shader \"" << shader_name << "\"."
<< std::endl;
return std::nullopt;
}
if (!shader_value.is_object()) {
error_stream << "Invalid shader entry \"" << shader_name
<< "\": Entry is not a JSON object." << std::endl;
return std::nullopt;
}
ShaderConfig shader;
if (!shader_value.contains("file")) {
error_stream << "Invalid shader entry \"" << shader_name
<< "\": Missing required \"file\" field." << std::endl;
return std::nullopt;
}
shader.source_file_name = shader_value["file"];
if (!shader_value.contains("type")) {
error_stream << "Invalid shader entry \"" << shader_name
<< "\": Missing required \"type\" field." << std::endl;
return std::nullopt;
}
shader.type = SourceTypeFromString(shader_value["type"]);
if (shader.type == SourceType::kUnknown) {
error_stream << "Invalid shader entry \"" << shader_name
<< "\": Shader type " << shader_value["type"]
<< " is unknown." << std::endl;
return std::nullopt;
}
shader.language = shader_value.contains("language")
? ToSourceLanguage(shader_value["language"])
: SourceLanguage::kGLSL;
if (shader.language == SourceLanguage::kUnknown) {
error_stream << "Invalid shader entry \"" << shader_name
<< "\": Unknown language type " << shader_value["language"]
<< "." << std::endl;
return std::nullopt;
}
shader.entry_point = shader_value.contains("entry_point")
? shader_value["entry_point"]
: "main";
bundle[shader_name] = shader;
}
return bundle;
}
static std::unique_ptr<fb::shaderbundle::BackendShaderT>
GenerateShaderBackendFB(TargetPlatform target_platform,
SourceOptions& options,
const std::string& shader_name,
const ShaderConfig& shader_config) {
auto result = std::make_unique<fb::shaderbundle::BackendShaderT>();
std::shared_ptr<fml::FileMapping> source_file_mapping =
fml::FileMapping::CreateReadOnly(shader_config.source_file_name);
if (!source_file_mapping) {
std::cerr << "Could not open file for bundled shader \"" << shader_name
<< "\"." << std::endl;
return nullptr;
}
/// Override options.
options.target_platform = target_platform;
options.file_name = shader_name; // This is just used for error messages.
options.type = shader_config.type;
options.source_language = shader_config.language;
options.entry_point_name = EntryPointFunctionNameFromSourceName(
shader_config.source_file_name, options.type, options.source_language,
shader_config.entry_point);
Reflector::Options reflector_options;
reflector_options.target_platform = options.target_platform;
reflector_options.entry_point_name = options.entry_point_name;
reflector_options.shader_name = shader_name;
Compiler compiler(source_file_mapping, options, reflector_options);
if (!compiler.IsValid()) {
std::cerr << "Compilation failed for bundled shader \"" << shader_name
<< "\"." << std::endl;
std::cerr << compiler.GetErrorMessages() << std::endl;
return nullptr;
}
auto reflector = compiler.GetReflector();
if (reflector == nullptr) {
std::cerr << "Could not create reflector for bundled shader \""
<< shader_name << "\"." << std::endl;
return nullptr;
}
auto bundle_data = reflector->GetShaderBundleData();
if (!bundle_data) {
std::cerr << "Bundled shader information was nil for \"" << shader_name
<< "\"." << std::endl;
return nullptr;
}
result = bundle_data->CreateFlatbuffer();
if (!result) {
std::cerr << "Failed to create flatbuffer for bundled shader \""
<< shader_name << "\"." << std::endl;
return nullptr;
}
return result;
}
static std::unique_ptr<fb::shaderbundle::ShaderT> GenerateShaderFB(
SourceOptions options,
const std::string& shader_name,
const ShaderConfig& shader_config) {
auto result = std::make_unique<fb::shaderbundle::ShaderT>();
result->name = shader_name;
result->metal_ios = GenerateShaderBackendFB(
TargetPlatform::kMetalIOS, options, shader_name, shader_config);
if (!result->metal_ios) {
return nullptr;
}
result->metal_desktop = GenerateShaderBackendFB(
TargetPlatform::kMetalDesktop, options, shader_name, shader_config);
if (!result->metal_desktop) {
return nullptr;
}
result->opengl_es = GenerateShaderBackendFB(
TargetPlatform::kOpenGLES, options, shader_name, shader_config);
if (!result->opengl_es) {
return nullptr;
}
result->opengl_desktop = GenerateShaderBackendFB(
TargetPlatform::kOpenGLDesktop, options, shader_name, shader_config);
if (!result->opengl_desktop) {
return nullptr;
}
result->vulkan = GenerateShaderBackendFB(TargetPlatform::kVulkan, options,
shader_name, shader_config);
if (!result->vulkan) {
return nullptr;
}
return result;
}
std::optional<fb::shaderbundle::ShaderBundleT> GenerateShaderBundleFlatbuffer(
const std::string& bundle_config_json,
const SourceOptions& options) {
// --------------------------------------------------------------------------
/// 1. Parse the bundle configuration.
///
std::optional<ShaderBundleConfig> bundle_config =
ParseShaderBundleConfig(bundle_config_json, std::cerr);
if (!bundle_config) {
return std::nullopt;
}
// --------------------------------------------------------------------------
/// 2. Build the deserialized shader bundle.
///
fb::shaderbundle::ShaderBundleT shader_bundle;
for (const auto& [shader_name, shader_config] : bundle_config.value()) {
std::unique_ptr<fb::shaderbundle::ShaderT> shader =
GenerateShaderFB(options, shader_name, shader_config);
if (!shader) {
return std::nullopt;
}
shader_bundle.shaders.push_back(std::move(shader));
}
return shader_bundle;
}
bool GenerateShaderBundle(Switches& switches) {
// --------------------------------------------------------------------------
/// 1. Parse the shader bundle and generate the flatbuffer result.
///
auto shader_bundle = GenerateShaderBundleFlatbuffer(
switches.shader_bundle, switches.CreateSourceOptions());
if (!shader_bundle.has_value()) {
// Specific error messages are already handled by
// GenerateShaderBundleFlatbuffer.
return false;
}
// --------------------------------------------------------------------------
/// 2. Serialize the shader bundle and write to disk.
///
auto builder = std::make_shared<flatbuffers::FlatBufferBuilder>();
builder->Finish(fb::shaderbundle::ShaderBundle::Pack(*builder.get(),
&shader_bundle.value()),
fb::shaderbundle::ShaderBundleIdentifier());
auto mapping = std::make_shared<fml::NonOwnedMapping>(
builder->GetBufferPointer(), builder->GetSize(),
[builder](auto, auto) {});
auto sl_file_name = std::filesystem::absolute(
std::filesystem::current_path() / switches.sl_file_name);
if (!fml::WriteAtomically(*switches.working_directory, //
Utf8FromPath(sl_file_name).c_str(), //
*mapping //
)) {
std::cerr << "Could not write file to " << switches.sl_file_name
<< std::endl;
return false;
}
// Tools that consume the runtime stage data expect the access mode to
// be 0644.
if (!SetPermissiveAccess(sl_file_name)) {
return false;
}
return true;
}
} // namespace compiler
} // namespace impeller
| engine/impeller/compiler/shader_bundle.cc/0 | {
"file_path": "engine/impeller/compiler/shader_bundle.cc",
"repo_id": "engine",
"token_count": 3520
} | 191 |
// 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.
#ifndef GAUSSIAN_GLSL_
#define GAUSSIAN_GLSL_
#include <impeller/constants.glsl>
#include <impeller/types.glsl>
/// Gaussian distribution function.
float IPGaussian(float x, float sigma) {
float variance = sigma * sigma;
return exp(-0.5f * x * x / variance) / (kSqrtTwoPi * sigma);
}
/// Gaussian distribution function.
float16_t IPHalfGaussian(float16_t x, float16_t sigma) {
float16_t variance = sigma * sigma;
return exp(-0.5hf * x * x / variance) / (float16_t(kSqrtTwoPi) * sigma);
}
/// Abramowitz and Stegun erf approximation.
float16_t IPErf(float16_t x) {
float16_t a = abs(x);
// 0.278393*x + 0.230389*x^2 + 0.078108*x^4 + 1
float16_t b =
(0.278393hf + (0.230389hf + 0.078108hf * a * a) * a) * a + 1.0hf;
return sign(x) * (1.0hf - 1.0hf / (b * b * b * b));
}
/// Vec2 variation for the Abramowitz and Stegun erf approximation.
f16vec2 IPVec2Erf(f16vec2 x) {
f16vec2 a = abs(x);
// 0.278393*x + 0.230389*x^2 + 0.078108*x^4 + 1
f16vec2 b = (0.278393hf + (0.230389hf + 0.078108hf * a * a) * a) * a + 1.0hf;
return sign(x) * (1.0hf - 1.0hf / (b * b * b * b));
}
/// The indefinite integral of the Gaussian function.
/// Uses a very close approximation of Erf.
float16_t IPGaussianIntegral(float16_t x, float16_t sigma) {
// ( 1 + erf( x * (sqrt(2) / (2 * sigma) ) ) / 2
return (1.0hf + IPErf(x * (float16_t(kHalfSqrtTwo) / sigma))) * 0.5hf;
}
/// Vec2 variation for the indefinite integral of the Gaussian function.
/// Uses a very close approximation of Erf.
f16vec2 IPVec2GaussianIntegral(f16vec2 x, float16_t sigma) {
// ( 1 + erf( x * (sqrt(2) / (2 * sigma) ) ) / 2
return (1.0hf + IPVec2Erf(x * (float16_t(kHalfSqrtTwo) / sigma))) * 0.5hf;
}
/// Simpler (but less accurate) approximation of the Gaussian integral.
vec2 IPVec2FastGaussianIntegral(vec2 x, float sigma) {
return 1.0 / (1.0 + exp(-kSqrtThree / sigma * x));
}
/// Simpler (but less accurate) approximation of the Gaussian integral.
f16vec2 IPHalfVec2FastGaussianIntegral(f16vec2 x, float16_t sigma) {
return 1.0hf / (1.0hf + exp(float16_t(-kSqrtThree) / sigma * x));
}
/// Simple logistic sigmoid with a domain of [-1, 1] and range of [0, 1].
float16_t IPSigmoid(float16_t x) {
return 1.03731472073hf / (1.0hf + exp(-4.0hf * x)) - 0.0186573603638hf;
}
#endif
| engine/impeller/compiler/shader_lib/impeller/gaussian.glsl/0 | {
"file_path": "engine/impeller/compiler/shader_lib/impeller/gaussian.glsl",
"repo_id": "engine",
"token_count": 1044
} | 192 |
// 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.
#include <initializer_list>
#include <vector>
#include "flutter/fml/command_line.h"
#include "flutter/fml/file.h"
#include "flutter/testing/testing.h"
#include "impeller/compiler/switches.h"
#include "impeller/compiler/utilities.h"
namespace impeller {
namespace compiler {
namespace testing {
Switches MakeSwitchesDesktopGL(
std::initializer_list<const char*> additional_options = {}) {
std::vector<const char*> options = {"--opengl-desktop", "--input=input.vert",
"--sl=output.vert",
"--spirv=output.spirv"};
options.insert(options.end(), additional_options.begin(),
additional_options.end());
auto cl = fml::CommandLineFromIteratorsWithArgv0("impellerc", options.begin(),
options.end());
return Switches(cl);
}
TEST(SwitchesTest, DoesntMangleUnicodeIncludes) {
const char* directory_name = "test_shader_include_�";
fml::CreateDirectory(flutter::testing::OpenFixturesDirectory(),
{directory_name}, fml::FilePermission::kRead);
auto include_path =
std::string(flutter::testing::GetFixturesPath()) + "/" + directory_name;
auto include_option = "--include=" + include_path;
Switches switches = MakeSwitchesDesktopGL({include_option.c_str()});
ASSERT_TRUE(switches.AreValid(std::cout));
ASSERT_EQ(switches.include_directories.size(), 1u);
ASSERT_NE(switches.include_directories[0].dir, nullptr);
ASSERT_EQ(switches.include_directories[0].name, include_path);
}
TEST(SwitchesTest, SourceLanguageDefaultsToGLSL) {
Switches switches = MakeSwitchesDesktopGL();
ASSERT_TRUE(switches.AreValid(std::cout));
ASSERT_EQ(switches.source_language, SourceLanguage::kGLSL);
}
TEST(SwitchesTest, SourceLanguageCanBeSetToHLSL) {
Switches switches = MakeSwitchesDesktopGL({"--source-language=hLsL"});
ASSERT_TRUE(switches.AreValid(std::cout));
ASSERT_EQ(switches.source_language, SourceLanguage::kHLSL);
}
TEST(SwitchesTest, DefaultEntryPointIsMain) {
Switches switches = MakeSwitchesDesktopGL({});
ASSERT_TRUE(switches.AreValid(std::cout));
ASSERT_EQ(switches.entry_point, "main");
}
TEST(SwitchesTest, EntryPointCanBeSetForHLSL) {
Switches switches = MakeSwitchesDesktopGL({"--entry-point=CustomEntryPoint"});
ASSERT_TRUE(switches.AreValid(std::cout));
ASSERT_EQ(switches.entry_point, "CustomEntryPoint");
}
TEST(SwitchesTEst, ConvertToEntrypointName) {
ASSERT_EQ(ConvertToEntrypointName("mandelbrot_unrolled"),
"mandelbrot_unrolled");
ASSERT_EQ(ConvertToEntrypointName("mandelbrot-unrolled"),
"mandelbrotunrolled");
ASSERT_EQ(ConvertToEntrypointName("7_"), "i_7_");
ASSERT_EQ(ConvertToEntrypointName("415"), "i_415");
ASSERT_EQ(ConvertToEntrypointName("#$%"), "i_");
ASSERT_EQ(ConvertToEntrypointName(""), "");
}
TEST(SwitchesTest, ShaderBundleModeValid) {
// Shader bundles process multiple shaders, and so the single-file input/spirv
// flags are not required.
std::vector<const char*> options = {
"--shader-bundle={}", "--sl=test.shaderbundle", "--runtime-stage-metal"};
auto cl = fml::CommandLineFromIteratorsWithArgv0("impellerc", options.begin(),
options.end());
Switches switches(cl);
ASSERT_TRUE(switches.AreValid(std::cout));
ASSERT_EQ(switches.shader_bundle, "{}");
}
} // namespace testing
} // namespace compiler
} // namespace impeller
| engine/impeller/compiler/switches_unittests.cc/0 | {
"file_path": "engine/impeller/compiler/switches_unittests.cc",
"repo_id": "engine",
"token_count": 1439
} | 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.
#ifndef FLUTTER_IMPELLER_CORE_DEVICE_BUFFER_H_
#define FLUTTER_IMPELLER_CORE_DEVICE_BUFFER_H_
#include <memory>
#include <string>
#include "impeller/core/allocator.h"
#include "impeller/core/buffer_view.h"
#include "impeller/core/device_buffer_descriptor.h"
#include "impeller/core/range.h"
#include "impeller/core/texture.h"
namespace impeller {
class DeviceBuffer {
public:
virtual ~DeviceBuffer();
[[nodiscard]] bool CopyHostBuffer(const uint8_t* source,
Range source_range,
size_t offset = 0u);
virtual bool SetLabel(const std::string& label) = 0;
virtual bool SetLabel(const std::string& label, Range range) = 0;
/// @brief Create a buffer view of this entire buffer.
static BufferView AsBufferView(std::shared_ptr<DeviceBuffer> buffer);
virtual std::shared_ptr<Texture> AsTexture(
Allocator& allocator,
const TextureDescriptor& descriptor,
uint16_t row_bytes) const;
const DeviceBufferDescriptor& GetDeviceBufferDescriptor() const;
virtual uint8_t* OnGetContents() const = 0;
/// Make any pending writes visible to the GPU.
///
/// This method must be called if the device pointer provided by
/// [OnGetContents] is written to without using [CopyHostBuffer]. On Devices
/// with coherent host memory, this method will not perform extra work.
///
/// If the range is not provided, the entire buffer is flushed.
virtual void Flush(std::optional<Range> range = std::nullopt) const;
virtual void Invalidate(std::optional<Range> range = std::nullopt) const;
protected:
const DeviceBufferDescriptor desc_;
explicit DeviceBuffer(DeviceBufferDescriptor desc);
virtual bool OnCopyHostBuffer(const uint8_t* source,
Range source_range,
size_t offset) = 0;
private:
DeviceBuffer(const DeviceBuffer&) = delete;
DeviceBuffer& operator=(const DeviceBuffer&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_CORE_DEVICE_BUFFER_H_
| engine/impeller/core/device_buffer.h/0 | {
"file_path": "engine/impeller/core/device_buffer.h",
"repo_id": "engine",
"token_count": 791
} | 194 |
// 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.
#ifndef FLUTTER_IMPELLER_CORE_SAMPLER_H_
#define FLUTTER_IMPELLER_CORE_SAMPLER_H_
#include <unordered_map>
#include "impeller/base/comparable.h"
#include "impeller/core/sampler_descriptor.h"
namespace impeller {
class Sampler {
public:
virtual ~Sampler();
const SamplerDescriptor& GetDescriptor() const;
protected:
SamplerDescriptor desc_;
explicit Sampler(SamplerDescriptor desc);
private:
Sampler(const Sampler&) = delete;
Sampler& operator=(const Sampler&) = delete;
};
using SamplerMap = std::unordered_map<SamplerDescriptor,
std::unique_ptr<const Sampler>,
ComparableHash<SamplerDescriptor>,
ComparableEqual<SamplerDescriptor>>;
} // namespace impeller
#endif // FLUTTER_IMPELLER_CORE_SAMPLER_H_
| engine/impeller/core/sampler.h/0 | {
"file_path": "engine/impeller/core/sampler.h",
"repo_id": "engine",
"token_count": 427
} | 195 |
// 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.
#include "impeller/display_list/dl_playground.h"
#include "flutter/testing/testing.h"
#include "impeller/aiks/aiks_context.h"
#include "impeller/display_list/dl_dispatcher.h"
#include "impeller/typographer/backends/skia/typographer_context_skia.h"
#include "third_party/imgui/imgui.h"
#include "third_party/skia/include/core/SkData.h"
#include "third_party/skia/include/core/SkFontMgr.h"
#include "third_party/skia/include/core/SkTypeface.h"
#include "txt/platform.h"
namespace impeller {
DlPlayground::DlPlayground() = default;
DlPlayground::~DlPlayground() = default;
bool DlPlayground::OpenPlaygroundHere(flutter::DisplayListBuilder& builder) {
return OpenPlaygroundHere(builder.Build());
}
bool DlPlayground::OpenPlaygroundHere(sk_sp<flutter::DisplayList> list) {
return OpenPlaygroundHere([&list]() { return list; });
}
bool DlPlayground::OpenPlaygroundHere(DisplayListPlaygroundCallback callback) {
if (!switches_.enable_playground) {
return true;
}
AiksContext context(GetContext(), TypographerContextSkia::Make());
if (!context.IsValid()) {
return false;
}
return Playground::OpenPlaygroundHere(
[&context, &callback](RenderTarget& render_target) -> bool {
static bool wireframe = false;
if (ImGui::IsKeyPressed(ImGuiKey_Z)) {
wireframe = !wireframe;
context.GetContentContext().SetWireframe(wireframe);
}
auto list = callback();
DlDispatcher dispatcher;
list->Dispatch(dispatcher);
auto picture = dispatcher.EndRecordingAsPicture();
return context.Render(picture, render_target, true);
});
}
SkFont DlPlayground::CreateTestFontOfSize(SkScalar scalar) {
static constexpr const char* kTestFontFixture = "Roboto-Regular.ttf";
auto mapping = flutter::testing::OpenFixtureAsSkData(kTestFontFixture);
FML_CHECK(mapping);
sk_sp<SkFontMgr> font_mgr = txt::GetDefaultFontManager();
return SkFont{font_mgr->makeFromData(mapping), scalar};
}
SkFont DlPlayground::CreateTestFont() {
return CreateTestFontOfSize(50);
}
} // namespace impeller
| engine/impeller/display_list/dl_playground.cc/0 | {
"file_path": "engine/impeller/display_list/dl_playground.cc",
"repo_id": "engine",
"token_count": 808
} | 196 |
# Frame Capture with RenderDoc
[RenderDoc](https://renderdoc.org/) is a graphics debugger that can be used to capture frames. With Impeller starting to support OpenGL ES and Vulkan backends, RenderDoc can provide insights into the application's frames.
1. First step is to set up RenderDoc. Follow the [quickstart instructions](https://renderdoc.org/docs/getting_started/quick_start.html).
For the purposes of this guide it is assumed that you are able to get RenderDoc running.
If the RenderDoc installed from your package manager crashes on startup, consider [building from source](https://github.com/baldurk/renderdoc/blob/v1.x/docs/CONTRIBUTING/Compiling.md).
2. The next step would be to run the application you wish the capture the frames of.
Typically these would be one of the [playground tests](https://github.com/flutter/engine/tree/main/impeller/playground),
for example [those in entity_unittests.cc](https://github.com/flutter/engine/blob/main/impeller/entity/entity_unittests.cc).
To build these, do:
```bash
# In your $ENGINE_SRC folder, do:
./flutter/tools/gn --unopt
ninja -C out/host_debug_unopt/
```
Building a "debug_unopt" build ensures that you have tracing enabled. Without this, RenderDoc will not have much to show.
3. Start RenderDoc and (if necessary) select "Launch Application" button from the menu:

On Linux, the executable is `qrenderdoc`.
You may also need to click the message that says "Click here to set up Vulkan capture".
This will probably be needed if you built from source.
4. Fill out the configuration fields.
Here, we will configure RenderDoc to specifically capture the "CanDrawRect" test:
- executable path: `$ENGINE_SRC/out/host_debug/impeller_unittests` (expand `ENGINE_SRC`).
- working directory: `$ENGINE_SRC` (expand `ENGINE_SRC`)
- command-line arguments: `--gtest_filter="*CanDrawRect/Vulkan*" --enable_playground`
5. Click "Launch". If everything is working, you'll get a window with the selected unit test rendering,
with a prompt in the top-left corner telling you to press `F12` or `Print Screen` to capture a frame.
(If you do not, try capturing a different program, like factorio. On at least one occasion that has
shaken things loose, though we have no explanation for why.)
Press `ESC` to move on to the next test.
5. For the frame you wish to capture, press `F12`, you will now be able to see the frame capture and inspect the state:

_See also:_
* [Learning to Read GPU Frame Captures](https://github.com/flutter/engine/blob/main/impeller/docs/read_frame_captures.md)
| engine/impeller/docs/renderdoc_frame_capture.md/0 | {
"file_path": "engine/impeller/docs/renderdoc_frame_capture.md",
"repo_id": "engine",
"token_count": 822
} | 197 |
// 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.
#include "impeller/entity/contents/color_source_contents.h"
#include "impeller/entity/entity.h"
#include "impeller/geometry/matrix.h"
namespace impeller {
ColorSourceContents::ColorSourceContents() = default;
ColorSourceContents::~ColorSourceContents() = default;
void ColorSourceContents::SetGeometry(std::shared_ptr<Geometry> geometry) {
geometry_ = std::move(geometry);
}
const std::shared_ptr<Geometry>& ColorSourceContents::GetGeometry() const {
return geometry_;
}
void ColorSourceContents::SetOpacityFactor(Scalar alpha) {
opacity_ = alpha;
}
Scalar ColorSourceContents::GetOpacityFactor() const {
return opacity_ * inherited_opacity_;
}
void ColorSourceContents::SetEffectTransform(Matrix matrix) {
inverse_matrix_ = matrix.Invert();
}
const Matrix& ColorSourceContents::GetInverseEffectTransform() const {
return inverse_matrix_;
}
bool ColorSourceContents::IsSolidColor() const {
return false;
}
std::optional<Rect> ColorSourceContents::GetCoverage(
const Entity& entity) const {
return geometry_->GetCoverage(entity.GetTransform());
};
bool ColorSourceContents::CanInheritOpacity(const Entity& entity) const {
return true;
}
void ColorSourceContents::SetInheritedOpacity(Scalar opacity) {
inherited_opacity_ = opacity;
}
} // namespace impeller
| engine/impeller/entity/contents/color_source_contents.cc/0 | {
"file_path": "engine/impeller/entity/contents/color_source_contents.cc",
"repo_id": "engine",
"token_count": 444
} | 198 |
// 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.
#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_COLOR_MATRIX_FILTER_CONTENTS_H_
#define FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_COLOR_MATRIX_FILTER_CONTENTS_H_
#include <memory>
#include <optional>
#include "impeller/entity/contents/filters/color_filter_contents.h"
#include "impeller/entity/contents/filters/inputs/filter_input.h"
namespace impeller {
// Look at example at: https://github.com/flutter/impeller/pull/132
class ColorMatrixFilterContents final : public ColorFilterContents {
public:
ColorMatrixFilterContents();
~ColorMatrixFilterContents() override;
void SetMatrix(const ColorMatrix& matrix);
private:
// |FilterContents|
std::optional<Entity> RenderFilter(
const FilterInput::Vector& input_textures,
const ContentContext& renderer,
const Entity& entity,
const Matrix& effect_transform,
const Rect& coverage,
const std::optional<Rect>& coverage_hint) const override;
ColorMatrix matrix_;
ColorMatrixFilterContents(const ColorMatrixFilterContents&) = delete;
ColorMatrixFilterContents& operator=(const ColorMatrixFilterContents&) =
delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_COLOR_MATRIX_FILTER_CONTENTS_H_
| engine/impeller/entity/contents/filters/color_matrix_filter_contents.h/0 | {
"file_path": "engine/impeller/entity/contents/filters/color_matrix_filter_contents.h",
"repo_id": "engine",
"token_count": 463
} | 199 |
// 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.
#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_INPUTS_TEXTURE_FILTER_INPUT_H_
#define FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_INPUTS_TEXTURE_FILTER_INPUT_H_
#include "impeller/entity/contents/filters/inputs/filter_input.h"
#include "impeller/geometry/matrix.h"
namespace impeller {
class TextureFilterInput final : public FilterInput {
public:
~TextureFilterInput() override;
// |FilterInput|
Variant GetInput() const override;
// |FilterInput|
std::optional<Snapshot> GetSnapshot(const std::string& label,
const ContentContext& renderer,
const Entity& entity,
std::optional<Rect> coverage_limit,
int32_t mip_count) const override;
// |FilterInput|
std::optional<Rect> GetCoverage(const Entity& entity) const override;
// |FilterInput|
Matrix GetLocalTransform(const Entity& entity) const override;
private:
explicit TextureFilterInput(std::shared_ptr<Texture> texture,
Matrix local_transform = Matrix());
std::shared_ptr<Texture> texture_;
Matrix local_transform_;
friend FilterInput;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_INPUTS_TEXTURE_FILTER_INPUT_H_
| engine/impeller/entity/contents/filters/inputs/texture_filter_input.h/0 | {
"file_path": "engine/impeller/entity/contents/filters/inputs/texture_filter_input.h",
"repo_id": "engine",
"token_count": 601
} | 200 |
// 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.
#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_GRADIENT_GENERATOR_H_
#define FLUTTER_IMPELLER_ENTITY_CONTENTS_GRADIENT_GENERATOR_H_
#include <functional>
#include <memory>
#include <vector>
#include "flutter/fml/macros.h"
#include "flutter/impeller/core/texture.h"
#include "impeller/core/shader_types.h"
#include "impeller/geometry/color.h"
#include "impeller/geometry/gradient.h"
#include "impeller/geometry/path.h"
#include "impeller/geometry/point.h"
namespace impeller {
class Context;
/**
* @brief Create a host visible texture that contains the gradient defined
* by the provided gradient data.
*/
std::shared_ptr<Texture> CreateGradientTexture(
const GradientData& gradient_data,
const std::shared_ptr<impeller::Context>& context);
struct StopData {
Color color;
Scalar stop;
Padding<12> _padding_;
};
/**
* @brief Populate a vector with the color and stop data for a gradient
*
* @param colors
* @param stops
* @return StopData
*/
std::vector<StopData> CreateGradientColors(const std::vector<Color>& colors,
const std::vector<Scalar>& stops);
} // namespace impeller
#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_GRADIENT_GENERATOR_H_
| engine/impeller/entity/contents/gradient_generator.h/0 | {
"file_path": "engine/impeller/entity/contents/gradient_generator.h",
"repo_id": "engine",
"token_count": 504
} | 201 |
// 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.
#include "impeller/entity/entity_pass.h"
#include <limits>
#include <memory>
#include <utility>
#include <variant>
#include "flutter/fml/closure.h"
#include "flutter/fml/logging.h"
#include "flutter/fml/trace_event.h"
#include "impeller/base/strings.h"
#include "impeller/base/validation.h"
#include "impeller/core/formats.h"
#include "impeller/entity/contents/clip_contents.h"
#include "impeller/entity/contents/content_context.h"
#include "impeller/entity/contents/filters/color_filter_contents.h"
#include "impeller/entity/contents/filters/inputs/filter_input.h"
#include "impeller/entity/contents/framebuffer_blend_contents.h"
#include "impeller/entity/contents/texture_contents.h"
#include "impeller/entity/entity.h"
#include "impeller/entity/inline_pass_context.h"
#include "impeller/geometry/color.h"
#include "impeller/geometry/rect.h"
#include "impeller/renderer/command_buffer.h"
#ifdef IMPELLER_DEBUG
#include "impeller/entity/contents/checkerboard_contents.h"
#endif // IMPELLER_DEBUG
namespace impeller {
namespace {
std::tuple<std::optional<Color>, BlendMode> ElementAsBackgroundColor(
const EntityPass::Element& element,
ISize target_size) {
if (const Entity* entity = std::get_if<Entity>(&element)) {
std::optional<Color> entity_color = entity->AsBackgroundColor(target_size);
if (entity_color.has_value()) {
return {entity_color.value(), entity->GetBlendMode()};
}
}
return {};
}
} // namespace
const std::string EntityPass::kCaptureDocumentName = "EntityPass";
EntityPass::EntityPass() = default;
EntityPass::~EntityPass() = default;
void EntityPass::SetDelegate(std::shared_ptr<EntityPassDelegate> delegate) {
if (!delegate) {
return;
}
delegate_ = std::move(delegate);
}
void EntityPass::SetBoundsLimit(std::optional<Rect> bounds_limit,
ContentBoundsPromise bounds_promise) {
bounds_limit_ = bounds_limit;
bounds_promise_ = bounds_limit.has_value() ? bounds_promise
: ContentBoundsPromise::kUnknown;
}
std::optional<Rect> EntityPass::GetBoundsLimit() const {
return bounds_limit_;
}
bool EntityPass::GetBoundsLimitMightClipContent() const {
switch (bounds_promise_) {
case ContentBoundsPromise::kUnknown:
// If the promise is unknown due to not having a bounds limit,
// then no clipping will occur. But if we have a bounds limit
// and it is unkown, then we can make no promises about whether
// it causes clipping of the entity pass contents and we
// conservatively return true.
return bounds_limit_.has_value();
case ContentBoundsPromise::kContainsContents:
FML_DCHECK(bounds_limit_.has_value());
return false;
case ContentBoundsPromise::kMayClipContents:
FML_DCHECK(bounds_limit_.has_value());
return true;
}
FML_UNREACHABLE();
}
bool EntityPass::GetBoundsLimitIsSnug() const {
switch (bounds_promise_) {
case ContentBoundsPromise::kUnknown:
return false;
case ContentBoundsPromise::kContainsContents:
case ContentBoundsPromise::kMayClipContents:
FML_DCHECK(bounds_limit_.has_value());
return true;
}
FML_UNREACHABLE();
}
void EntityPass::AddEntity(Entity entity) {
if (entity.GetBlendMode() == BlendMode::kSourceOver &&
entity.GetContents()->IsOpaque()) {
entity.SetBlendMode(BlendMode::kSource);
}
if (entity.GetBlendMode() > Entity::kLastPipelineBlendMode) {
advanced_blend_reads_from_pass_texture_ += 1;
}
elements_.emplace_back(std::move(entity));
}
void EntityPass::PushClip(Entity entity) {
elements_.emplace_back(std::move(entity));
active_clips_.emplace_back(elements_.size() - 1);
}
void EntityPass::PopClips(size_t num_clips, uint64_t depth) {
if (num_clips > active_clips_.size()) {
VALIDATION_LOG
<< "Attempted to pop more clips than are currently active. Active: "
<< active_clips_.size() << ", Popped: " << num_clips
<< ", Depth: " << depth;
}
size_t max = std::min(num_clips, active_clips_.size());
for (size_t i = 0; i < max; i++) {
FML_DCHECK(active_clips_.back() < elements_.size());
Entity* element = std::get_if<Entity>(&elements_[active_clips_.back()]);
FML_DCHECK(element);
element->SetNewClipDepth(depth);
active_clips_.pop_back();
}
}
void EntityPass::PopAllClips(uint64_t depth) {
PopClips(active_clips_.size(), depth);
}
void EntityPass::SetElements(std::vector<Element> elements) {
elements_ = std::move(elements);
}
size_t EntityPass::GetSubpassesDepth() const {
size_t max_subpass_depth = 0u;
for (const auto& element : elements_) {
if (auto subpass = std::get_if<std::unique_ptr<EntityPass>>(&element)) {
max_subpass_depth =
std::max(max_subpass_depth, subpass->get()->GetSubpassesDepth());
}
}
return max_subpass_depth + 1u;
}
std::optional<Rect> EntityPass::GetElementsCoverage(
std::optional<Rect> coverage_limit) const {
std::optional<Rect> accumulated_coverage;
for (const auto& element : elements_) {
std::optional<Rect> element_coverage;
if (auto entity = std::get_if<Entity>(&element)) {
element_coverage = entity->GetCoverage();
// When the coverage limit is std::nullopt, that means there is no limit,
// as opposed to empty coverage.
if (element_coverage.has_value() && coverage_limit.has_value()) {
const auto* filter = entity->GetContents()->AsFilter();
if (!filter || filter->IsTranslationOnly()) {
element_coverage =
element_coverage->Intersection(coverage_limit.value());
}
}
} else if (auto subpass_ptr =
std::get_if<std::unique_ptr<EntityPass>>(&element)) {
auto& subpass = *subpass_ptr->get();
std::optional<Rect> unfiltered_coverage =
GetSubpassCoverage(subpass, std::nullopt);
// If the current pass elements have any coverage so far and there's a
// backdrop filter, then incorporate the backdrop filter in the
// pre-filtered coverage of the subpass.
if (accumulated_coverage.has_value() && subpass.backdrop_filter_proc_) {
std::shared_ptr<FilterContents> backdrop_filter =
subpass.backdrop_filter_proc_(
FilterInput::Make(accumulated_coverage.value()),
subpass.transform_, Entity::RenderingMode::kSubpass);
if (backdrop_filter) {
auto backdrop_coverage = backdrop_filter->GetCoverage({});
unfiltered_coverage =
Rect::Union(unfiltered_coverage, backdrop_coverage);
} else {
VALIDATION_LOG << "The EntityPass backdrop filter proc didn't return "
"a valid filter.";
}
}
if (!unfiltered_coverage.has_value()) {
continue;
}
// Additionally, subpass textures may be passed through filters, which may
// modify the coverage.
//
// Note that we currently only assume that ImageFilters (such as blurs and
// matrix transforms) may modify coverage, although it's technically
// possible ColorFilters to affect coverage as well. For example: A
// ColorMatrixFilter could output a completely transparent result, and
// we could potentially detect this case as zero coverage in the future.
std::shared_ptr<FilterContents> image_filter =
subpass.delegate_->WithImageFilter(*unfiltered_coverage,
subpass.transform_);
if (image_filter) {
Entity subpass_entity;
subpass_entity.SetTransform(subpass.transform_);
element_coverage = image_filter->GetCoverage(subpass_entity);
} else {
element_coverage = unfiltered_coverage;
}
element_coverage = Rect::Intersection(element_coverage, coverage_limit);
} else {
FML_UNREACHABLE();
}
accumulated_coverage = Rect::Union(accumulated_coverage, element_coverage);
}
return accumulated_coverage;
}
std::optional<Rect> EntityPass::GetSubpassCoverage(
const EntityPass& subpass,
std::optional<Rect> coverage_limit) const {
if (subpass.bounds_limit_.has_value() && subpass.GetBoundsLimitIsSnug()) {
return subpass.bounds_limit_->TransformBounds(subpass.transform_);
}
std::shared_ptr<FilterContents> image_filter =
subpass.delegate_->WithImageFilter(Rect(), subpass.transform_);
// If the subpass has an image filter, then its coverage space may deviate
// from the parent pass and make intersecting with the pass coverage limit
// unsafe.
if (image_filter && coverage_limit.has_value()) {
coverage_limit = image_filter->GetSourceCoverage(subpass.transform_,
coverage_limit.value());
}
auto entities_coverage = subpass.GetElementsCoverage(coverage_limit);
// The entities don't cover anything. There is nothing to do.
if (!entities_coverage.has_value()) {
return std::nullopt;
}
if (!subpass.bounds_limit_.has_value()) {
return entities_coverage;
}
auto user_bounds_coverage =
subpass.bounds_limit_->TransformBounds(subpass.transform_);
return entities_coverage->Intersection(user_bounds_coverage);
}
EntityPass* EntityPass::GetSuperpass() const {
return superpass_;
}
EntityPass* EntityPass::AddSubpass(std::unique_ptr<EntityPass> pass) {
if (!pass) {
return nullptr;
}
FML_DCHECK(pass->superpass_ == nullptr);
pass->superpass_ = this;
if (pass->backdrop_filter_proc_) {
backdrop_filter_reads_from_pass_texture_ += 1;
}
if (pass->blend_mode_ > Entity::kLastPipelineBlendMode) {
advanced_blend_reads_from_pass_texture_ += 1;
}
auto subpass_pointer = pass.get();
elements_.emplace_back(std::move(pass));
return subpass_pointer;
}
void EntityPass::AddSubpassInline(std::unique_ptr<EntityPass> pass) {
if (!pass) {
return;
}
FML_DCHECK(pass->superpass_ == nullptr);
std::vector<Element>& elements = pass->elements_;
for (auto i = 0u; i < elements.size(); i++) {
elements_.emplace_back(std::move(elements[i]));
}
backdrop_filter_reads_from_pass_texture_ +=
pass->backdrop_filter_reads_from_pass_texture_;
advanced_blend_reads_from_pass_texture_ +=
pass->advanced_blend_reads_from_pass_texture_;
}
static const constexpr RenderTarget::AttachmentConfig kDefaultStencilConfig =
RenderTarget::AttachmentConfig{
.storage_mode = StorageMode::kDeviceTransient,
.load_action = LoadAction::kDontCare,
.store_action = StoreAction::kDontCare,
};
static EntityPassTarget CreateRenderTarget(ContentContext& renderer,
ISize size,
int mip_count,
const Color& clear_color) {
const std::shared_ptr<Context>& context = renderer.GetContext();
/// All of the load/store actions are managed by `InlinePassContext` when
/// `RenderPasses` are created, so we just set them to `kDontCare` here.
/// What's important is the `StorageMode` of the textures, which cannot be
/// changed for the lifetime of the textures.
if (context->GetBackendType() == Context::BackendType::kOpenGLES) {
// TODO(https://github.com/flutter/flutter/issues/141732): Implement mip map
// generation on opengles.
mip_count = 1;
}
RenderTarget target;
if (context->GetCapabilities()->SupportsOffscreenMSAA()) {
target = renderer.GetRenderTargetCache()->CreateOffscreenMSAA(
/*context=*/*context,
/*size=*/size,
/*mip_count=*/mip_count,
/*label=*/"EntityPass",
/*color_attachment_config=*/
RenderTarget::AttachmentConfigMSAA{
.storage_mode = StorageMode::kDeviceTransient,
.resolve_storage_mode = StorageMode::kDevicePrivate,
.load_action = LoadAction::kDontCare,
.store_action = StoreAction::kMultisampleResolve,
.clear_color = clear_color},
/*stencil_attachment_config=*/
kDefaultStencilConfig);
} else {
target = renderer.GetRenderTargetCache()->CreateOffscreen(
*context, // context
size, // size
/*mip_count=*/mip_count,
"EntityPass", // label
RenderTarget::AttachmentConfig{
.storage_mode = StorageMode::kDevicePrivate,
.load_action = LoadAction::kDontCare,
.store_action = StoreAction::kDontCare,
.clear_color = clear_color,
}, // color_attachment_config
kDefaultStencilConfig // stencil_attachment_config
);
}
return EntityPassTarget(
target, renderer.GetDeviceCapabilities().SupportsReadFromResolve(),
renderer.GetDeviceCapabilities().SupportsImplicitResolvingMSAA());
}
uint32_t EntityPass::GetTotalPassReads(ContentContext& renderer) const {
return renderer.GetDeviceCapabilities().SupportsFramebufferFetch()
? backdrop_filter_reads_from_pass_texture_
: backdrop_filter_reads_from_pass_texture_ +
advanced_blend_reads_from_pass_texture_;
}
bool EntityPass::Render(ContentContext& renderer,
const RenderTarget& render_target) const {
auto capture =
renderer.GetContext()->capture.GetDocument(kCaptureDocumentName);
renderer.GetRenderTargetCache()->Start();
fml::ScopedCleanupClosure reset_state([&renderer]() {
renderer.GetLazyGlyphAtlas()->ResetTextFrames();
renderer.GetRenderTargetCache()->End();
});
auto root_render_target = render_target;
if (root_render_target.GetColorAttachments().find(0u) ==
root_render_target.GetColorAttachments().end()) {
VALIDATION_LOG << "The root RenderTarget must have a color attachment.";
return false;
}
if (root_render_target.GetDepthAttachment().has_value() !=
root_render_target.GetStencilAttachment().has_value()) {
VALIDATION_LOG << "The root RenderTarget should have a stencil attachment "
"iff it has a depth attachment.";
return false;
}
capture.AddRect("Coverage",
Rect::MakeSize(root_render_target.GetRenderTargetSize()),
{.readonly = true});
const auto& lazy_glyph_atlas = renderer.GetLazyGlyphAtlas();
IterateAllEntities([&lazy_glyph_atlas](const Entity& entity) {
if (const auto& contents = entity.GetContents()) {
contents->PopulateGlyphAtlas(lazy_glyph_atlas, entity.DeriveTextScale());
}
return true;
});
ClipCoverageStack clip_coverage_stack = {ClipCoverageLayer{
.coverage = Rect::MakeSize(root_render_target.GetRenderTargetSize()),
.clip_depth = 0}};
bool reads_from_onscreen_backdrop = GetTotalPassReads(renderer) > 0;
// In this branch path, we need to render everything to an offscreen texture
// and then blit the results onto the onscreen texture. If using this branch,
// there's no need to set up a stencil attachment on the root render target.
if (reads_from_onscreen_backdrop) {
EntityPassTarget offscreen_target = CreateRenderTarget(
renderer, root_render_target.GetRenderTargetSize(),
GetRequiredMipCount(),
GetClearColorOrDefault(render_target.GetRenderTargetSize()));
if (!OnRender(renderer, // renderer
capture, // capture
offscreen_target.GetRenderTarget()
.GetRenderTargetSize(), // root_pass_size
offscreen_target, // pass_target
Point(), // global_pass_position
Point(), // local_pass_position
0, // pass_depth
clip_coverage_stack // clip_coverage_stack
)) {
// Validation error messages are triggered for all `OnRender()` failure
// cases.
return false;
}
auto command_buffer = renderer.GetContext()->CreateCommandBuffer();
command_buffer->SetLabel("EntityPass Root Command Buffer");
// If the context supports blitting, blit the offscreen texture to the
// onscreen texture. Otherwise, draw it to the parent texture using a
// pipeline (slower).
if (renderer.GetContext()
->GetCapabilities()
->SupportsTextureToTextureBlits()) {
auto blit_pass = command_buffer->CreateBlitPass();
blit_pass->AddCopy(
offscreen_target.GetRenderTarget().GetRenderTargetTexture(),
root_render_target.GetRenderTargetTexture());
if (!blit_pass->EncodeCommands(
renderer.GetContext()->GetResourceAllocator())) {
VALIDATION_LOG << "Failed to encode root pass blit command.";
return false;
}
if (!renderer.GetContext()
->GetCommandQueue()
->Submit({command_buffer})
.ok()) {
return false;
}
} else {
auto render_pass = command_buffer->CreateRenderPass(root_render_target);
render_pass->SetLabel("EntityPass Root Render Pass");
{
auto size_rect = Rect::MakeSize(
offscreen_target.GetRenderTarget().GetRenderTargetSize());
auto contents = TextureContents::MakeRect(size_rect);
contents->SetTexture(
offscreen_target.GetRenderTarget().GetRenderTargetTexture());
contents->SetSourceRect(size_rect);
contents->SetLabel("Root pass blit");
Entity entity;
entity.SetContents(contents);
entity.SetBlendMode(BlendMode::kSource);
if (!entity.Render(renderer, *render_pass)) {
VALIDATION_LOG << "Failed to render EntityPass root blit.";
return false;
}
}
if (!render_pass->EncodeCommands()) {
VALIDATION_LOG << "Failed to encode root pass command buffer.";
return false;
}
if (!renderer.GetContext()
->GetCommandQueue()
->Submit({command_buffer})
.ok()) {
return false;
}
}
return true;
}
// If we make it this far, that means the context is capable of rendering
// everything directly to the onscreen texture.
// The safety check for fetching this color attachment is at the beginning of
// this method.
auto color0 = root_render_target.GetColorAttachments().find(0u)->second;
auto stencil_attachment = root_render_target.GetStencilAttachment();
auto depth_attachment = root_render_target.GetDepthAttachment();
if (!stencil_attachment.has_value() || !depth_attachment.has_value()) {
// Setup a new root stencil with an optimal configuration if one wasn't
// provided by the caller.
root_render_target.SetupDepthStencilAttachments(
*renderer.GetContext(), *renderer.GetContext()->GetResourceAllocator(),
color0.texture->GetSize(),
renderer.GetContext()->GetCapabilities()->SupportsOffscreenMSAA(),
"ImpellerOnscreen", kDefaultStencilConfig);
}
// Set up the clear color of the root pass.
color0.clear_color =
GetClearColorOrDefault(render_target.GetRenderTargetSize());
root_render_target.SetColorAttachment(color0, 0);
EntityPassTarget pass_target(
root_render_target,
renderer.GetDeviceCapabilities().SupportsReadFromResolve(),
renderer.GetDeviceCapabilities().SupportsImplicitResolvingMSAA());
return OnRender( //
renderer, // renderer
capture, // capture
root_render_target.GetRenderTargetSize(), // root_pass_size
pass_target, // pass_target
Point(), // global_pass_position
Point(), // local_pass_position
0, // pass_depth
clip_coverage_stack); // clip_coverage_stack
}
EntityPass::EntityResult EntityPass::GetEntityForElement(
const EntityPass::Element& element,
ContentContext& renderer,
Capture& capture,
InlinePassContext& pass_context,
ISize root_pass_size,
Point global_pass_position,
uint32_t pass_depth,
ClipCoverageStack& clip_coverage_stack,
size_t clip_depth_floor) const {
//--------------------------------------------------------------------------
/// Setup entity element.
///
if (const auto& entity = std::get_if<Entity>(&element)) {
Entity element_entity = entity->Clone();
element_entity.SetCapture(capture.CreateChild("Entity"));
if (!global_pass_position.IsZero()) {
// If the pass image is going to be rendered with a non-zero position,
// apply the negative translation to entity copies before rendering them
// so that they'll end up rendering to the correct on-screen position.
element_entity.SetTransform(
Matrix::MakeTranslation(Vector3(-global_pass_position)) *
element_entity.GetTransform());
}
return EntityPass::EntityResult::Success(std::move(element_entity));
}
//--------------------------------------------------------------------------
/// Setup subpass element.
///
if (const auto& subpass_ptr =
std::get_if<std::unique_ptr<EntityPass>>(&element)) {
auto subpass = subpass_ptr->get();
if (subpass->delegate_->CanElide()) {
return EntityPass::EntityResult::Skip();
}
if (!subpass->backdrop_filter_proc_ &&
subpass->delegate_->CanCollapseIntoParentPass(subpass)) {
auto subpass_capture = capture.CreateChild("EntityPass (Collapsed)");
// Directly render into the parent target and move on.
if (!subpass->OnRender(
renderer, // renderer
subpass_capture, // capture
root_pass_size, // root_pass_size
pass_context.GetPassTarget(), // pass_target
global_pass_position, // global_pass_position
Point(), // local_pass_position
pass_depth, // pass_depth
clip_coverage_stack, // clip_coverage_stack
clip_depth_, // clip_depth_floor
nullptr, // backdrop_filter_contents
pass_context.GetRenderPass(pass_depth) // collapsed_parent_pass
)) {
// Validation error messages are triggered for all `OnRender()` failure
// cases.
return EntityPass::EntityResult::Failure();
}
return EntityPass::EntityResult::Skip();
}
std::shared_ptr<Contents> subpass_backdrop_filter_contents = nullptr;
if (subpass->backdrop_filter_proc_) {
auto texture = pass_context.GetTexture();
// Render the backdrop texture before any of the pass elements.
const auto& proc = subpass->backdrop_filter_proc_;
subpass_backdrop_filter_contents =
proc(FilterInput::Make(std::move(texture)),
subpass->transform_.Basis(), Entity::RenderingMode::kSubpass);
// If the very first thing we render in this EntityPass is a subpass that
// happens to have a backdrop filter, than that backdrop filter will end
// may wind up sampling from the raw, uncleared texture that came straight
// out of the texture cache. By calling `pass_context.GetRenderPass` here,
// we force the texture to pass through at least one RenderPass with the
// correct clear configuration before any sampling occurs.
pass_context.GetRenderPass(pass_depth);
// The subpass will need to read from the current pass texture when
// rendering the backdrop, so if there's an active pass, end it prior to
// rendering the subpass.
pass_context.EndPass();
}
if (clip_coverage_stack.empty()) {
// The current clip is empty. This means the pass texture won't be
// visible, so skip it.
capture.CreateChild("Subpass Entity (Skipped: Empty clip A)");
return EntityPass::EntityResult::Skip();
}
auto clip_coverage_back = clip_coverage_stack.back().coverage;
if (!clip_coverage_back.has_value()) {
capture.CreateChild("Subpass Entity (Skipped: Empty clip B)");
return EntityPass::EntityResult::Skip();
}
// The maximum coverage of the subpass. Subpasses textures should never
// extend outside the parent pass texture or the current clip coverage.
auto coverage_limit = Rect::MakeOriginSize(global_pass_position,
Size(pass_context.GetPassTarget()
.GetRenderTarget()
.GetRenderTargetSize()))
.Intersection(clip_coverage_back.value());
if (!coverage_limit.has_value()) {
capture.CreateChild("Subpass Entity (Skipped: Empty coverage limit A)");
return EntityPass::EntityResult::Skip();
}
coverage_limit =
coverage_limit->Intersection(Rect::MakeSize(root_pass_size));
if (!coverage_limit.has_value()) {
capture.CreateChild("Subpass Entity (Skipped: Empty coverage limit B)");
return EntityPass::EntityResult::Skip();
}
auto subpass_coverage =
(subpass->flood_clip_ || subpass_backdrop_filter_contents)
? coverage_limit
: GetSubpassCoverage(*subpass, coverage_limit);
if (!subpass_coverage.has_value()) {
capture.CreateChild("Subpass Entity (Skipped: Empty subpass coverage A)");
return EntityPass::EntityResult::Skip();
}
auto subpass_size = ISize(subpass_coverage->GetSize());
if (subpass_size.IsEmpty()) {
capture.CreateChild("Subpass Entity (Skipped: Empty subpass coverage B)");
return EntityPass::EntityResult::Skip();
}
auto subpass_target = CreateRenderTarget(
renderer, // renderer
subpass_size, // size
subpass->GetRequiredMipCount(),
subpass->GetClearColorOrDefault(subpass_size)); // clear_color
if (!subpass_target.IsValid()) {
VALIDATION_LOG << "Subpass render target is invalid.";
return EntityPass::EntityResult::Failure();
}
auto subpass_capture = capture.CreateChild("EntityPass");
subpass_capture.AddRect("Coverage", *subpass_coverage, {.readonly = true});
// Start non-collapsed subpasses with a fresh clip coverage stack limited by
// the subpass coverage. This is important because image filters applied to
// save layers may transform the subpass texture after it's rendered,
// causing parent clip coverage to get misaligned with the actual area that
// the subpass will affect in the parent pass.
ClipCoverageStack subpass_clip_coverage_stack = {ClipCoverageLayer{
.coverage = subpass_coverage, .clip_depth = subpass->clip_depth_}};
// Stencil textures aren't shared between EntityPasses (as much of the
// time they are transient).
if (!subpass->OnRender(
renderer, // renderer
subpass_capture, // capture
root_pass_size, // root_pass_size
subpass_target, // pass_target
subpass_coverage->GetOrigin(), // global_pass_position
subpass_coverage->GetOrigin() -
global_pass_position, // local_pass_position
++pass_depth, // pass_depth
subpass_clip_coverage_stack, // clip_coverage_stack
subpass->clip_depth_, // clip_depth_floor
subpass_backdrop_filter_contents // backdrop_filter_contents
)) {
// Validation error messages are triggered for all `OnRender()` failure
// cases.
return EntityPass::EntityResult::Failure();
}
// The subpass target's texture may have changed during OnRender.
auto subpass_texture =
subpass_target.GetRenderTarget().GetRenderTargetTexture();
auto offscreen_texture_contents =
subpass->delegate_->CreateContentsForSubpassTarget(
subpass_texture,
Matrix::MakeTranslation(Vector3{-global_pass_position}) *
subpass->transform_);
if (!offscreen_texture_contents) {
// This is an error because the subpass delegate said the pass couldn't
// be collapsed into its parent. Yet, when asked how it want's to
// postprocess the offscreen texture, it couldn't give us an answer.
//
// Theoretically, we could collapse the pass now. But that would be
// wasteful as we already have the offscreen texture and we don't want
// to discard it without ever using it. Just make the delegate do the
// right thing.
return EntityPass::EntityResult::Failure();
}
Entity element_entity;
Capture subpass_texture_capture =
capture.CreateChild("Entity (Subpass texture)");
element_entity.SetNewClipDepth(subpass->new_clip_depth_);
element_entity.SetCapture(subpass_texture_capture);
element_entity.SetContents(std::move(offscreen_texture_contents));
element_entity.SetClipDepth(subpass->clip_depth_);
element_entity.SetBlendMode(subpass->blend_mode_);
element_entity.SetTransform(subpass_texture_capture.AddMatrix(
"Transform",
Matrix::MakeTranslation(
Vector3(subpass_coverage->GetOrigin() - global_pass_position))));
return EntityPass::EntityResult::Success(std::move(element_entity));
}
FML_UNREACHABLE();
}
bool EntityPass::RenderElement(Entity& element_entity,
size_t clip_depth_floor,
InlinePassContext& pass_context,
int32_t pass_depth,
ContentContext& renderer,
ClipCoverageStack& clip_coverage_stack,
Point global_pass_position) const {
auto result = pass_context.GetRenderPass(pass_depth);
if (!result.pass) {
// Failure to produce a render pass should be explained by specific errors
// in `InlinePassContext::GetRenderPass()`, so avoid log spam and don't
// append a validation log here.
return false;
}
if (result.just_created) {
// Restore any clips that were recorded before the backdrop filter was
// applied.
auto& replay_entities = clip_replay_->GetReplayEntities();
for (const auto& entity : replay_entities) {
if (!entity.Render(renderer, *result.pass)) {
VALIDATION_LOG << "Failed to render entity for clip restore.";
}
}
}
// If the pass context returns a backdrop texture, we need to draw it to the
// current pass. We do this because it's faster and takes significantly less
// memory than storing/loading large MSAA textures. Also, it's not possible to
// blit the non-MSAA resolve texture of the previous pass to MSAA textures
// (let alone a transient one).
if (result.backdrop_texture) {
auto size_rect = Rect::MakeSize(result.pass->GetRenderTargetSize());
auto msaa_backdrop_contents = TextureContents::MakeRect(size_rect);
msaa_backdrop_contents->SetStencilEnabled(false);
msaa_backdrop_contents->SetLabel("MSAA backdrop");
msaa_backdrop_contents->SetSourceRect(size_rect);
msaa_backdrop_contents->SetTexture(result.backdrop_texture);
Entity msaa_backdrop_entity;
msaa_backdrop_entity.SetContents(std::move(msaa_backdrop_contents));
msaa_backdrop_entity.SetBlendMode(BlendMode::kSource);
msaa_backdrop_entity.SetNewClipDepth(std::numeric_limits<uint32_t>::max());
if (!msaa_backdrop_entity.Render(renderer, *result.pass)) {
VALIDATION_LOG << "Failed to render MSAA backdrop filter entity.";
return false;
}
}
auto current_clip_coverage = clip_coverage_stack.back().coverage;
if (current_clip_coverage.has_value()) {
// Entity transforms are relative to the current pass position, so we need
// to check clip coverage in the same space.
current_clip_coverage = current_clip_coverage->Shift(-global_pass_position);
}
if (!element_entity.ShouldRender(current_clip_coverage)) {
return true; // Nothing to render.
}
auto clip_coverage = element_entity.GetClipCoverage(current_clip_coverage);
if (clip_coverage.coverage.has_value()) {
clip_coverage.coverage =
clip_coverage.coverage->Shift(global_pass_position);
}
// The coverage hint tells the rendered Contents which portion of the
// rendered output will actually be used, and so we set this to the current
// clip coverage (which is the max clip bounds). The contents may
// optionally use this hint to avoid unnecessary rendering work.
auto element_coverage_hint = element_entity.GetContents()->GetCoverageHint();
element_entity.GetContents()->SetCoverageHint(
Rect::Intersection(element_coverage_hint, current_clip_coverage));
switch (clip_coverage.type) {
case Contents::ClipCoverage::Type::kNoChange:
break;
case Contents::ClipCoverage::Type::kAppend: {
auto op = clip_coverage_stack.back().coverage;
clip_coverage_stack.push_back(
ClipCoverageLayer{.coverage = clip_coverage.coverage,
.clip_depth = element_entity.GetClipDepth() + 1});
FML_DCHECK(clip_coverage_stack.back().clip_depth ==
clip_coverage_stack.front().clip_depth +
clip_coverage_stack.size() - 1);
if (!op.has_value()) {
// Running this append op won't impact the clip buffer because the
// whole screen is already being clipped, so skip it.
return true;
}
} break;
case Contents::ClipCoverage::Type::kRestore: {
if (clip_coverage_stack.back().clip_depth <=
element_entity.GetClipDepth()) {
// Drop clip restores that will do nothing.
return true;
}
auto restoration_index = element_entity.GetClipDepth() -
clip_coverage_stack.front().clip_depth;
FML_DCHECK(restoration_index < clip_coverage_stack.size());
// We only need to restore the area that covers the coverage of the
// clip rect at target depth + 1.
std::optional<Rect> restore_coverage =
(restoration_index + 1 < clip_coverage_stack.size())
? clip_coverage_stack[restoration_index + 1].coverage
: std::nullopt;
if (restore_coverage.has_value()) {
// Make the coverage rectangle relative to the current pass.
restore_coverage = restore_coverage->Shift(-global_pass_position);
}
clip_coverage_stack.resize(restoration_index + 1);
if constexpr (ContentContext::kEnableStencilThenCover) {
// Skip all clip restores when stencil-then-cover is enabled.
clip_replay_->RecordEntity(element_entity, clip_coverage.type);
return true;
}
if (!clip_coverage_stack.back().coverage.has_value()) {
// Running this restore op won't make anything renderable, so skip it.
return true;
}
auto restore_contents =
static_cast<ClipRestoreContents*>(element_entity.GetContents().get());
restore_contents->SetRestoreCoverage(restore_coverage);
} break;
}
#ifdef IMPELLER_ENABLE_CAPTURE
{
auto element_entity_coverage = element_entity.GetCoverage();
if (element_entity_coverage.has_value()) {
element_entity_coverage =
element_entity_coverage->Shift(global_pass_position);
element_entity.GetCapture().AddRect("Coverage", *element_entity_coverage,
{.readonly = true});
}
}
#endif
element_entity.SetClipDepth(element_entity.GetClipDepth() - clip_depth_floor);
clip_replay_->RecordEntity(element_entity, clip_coverage.type);
if (!element_entity.Render(renderer, *result.pass)) {
VALIDATION_LOG << "Failed to render entity.";
return false;
}
return true;
}
bool EntityPass::OnRender(
ContentContext& renderer,
Capture& capture,
ISize root_pass_size,
EntityPassTarget& pass_target,
Point global_pass_position,
Point local_pass_position,
uint32_t pass_depth,
ClipCoverageStack& clip_coverage_stack,
size_t clip_depth_floor,
std::shared_ptr<Contents> backdrop_filter_contents,
const std::optional<InlinePassContext::RenderPassResult>&
collapsed_parent_pass) const {
TRACE_EVENT0("impeller", "EntityPass::OnRender");
if (!active_clips_.empty()) {
VALIDATION_LOG << SPrintF(
"EntityPass (Depth=%d) contains one or more clips with an unresolved "
"depth value.",
pass_depth);
}
InlinePassContext pass_context(renderer, pass_target,
GetTotalPassReads(renderer), GetElementCount(),
collapsed_parent_pass);
if (!pass_context.IsValid()) {
VALIDATION_LOG << SPrintF("Pass context invalid (Depth=%d)", pass_depth);
return false;
}
auto clear_color_size = pass_target.GetRenderTarget().GetRenderTargetSize();
if (!collapsed_parent_pass) {
// Always force the pass to construct the render pass object, even if there
// is not a clear color. This ensures that the attachment textures are
// cleared/transitioned to the right state.
pass_context.GetRenderPass(pass_depth);
}
if (backdrop_filter_proc_) {
if (!backdrop_filter_contents) {
VALIDATION_LOG
<< "EntityPass contains a backdrop filter, but no backdrop filter "
"contents was supplied by the parent pass at render time. This is "
"a bug in EntityPass. Parent passes are responsible for setting "
"up backdrop filters for their children.";
return false;
}
Entity backdrop_entity;
backdrop_entity.SetContents(std::move(backdrop_filter_contents));
backdrop_entity.SetTransform(
Matrix::MakeTranslation(Vector3(-local_pass_position)));
backdrop_entity.SetClipDepth(clip_depth_floor);
backdrop_entity.SetNewClipDepth(std::numeric_limits<uint32_t>::max());
RenderElement(backdrop_entity, clip_depth_floor, pass_context, pass_depth,
renderer, clip_coverage_stack, global_pass_position);
}
bool is_collapsing_clear_colors = !collapsed_parent_pass &&
// Backdrop filters act as a entity before
// everything and disrupt the optimization.
!backdrop_filter_proc_;
for (const auto& element : elements_) {
// Skip elements that are incorporated into the clear color.
if (is_collapsing_clear_colors) {
auto [entity_color, _] =
ElementAsBackgroundColor(element, clear_color_size);
if (entity_color.has_value()) {
continue;
}
is_collapsing_clear_colors = false;
}
EntityResult result =
GetEntityForElement(element, // element
renderer, // renderer
capture, // capture
pass_context, // pass_context
root_pass_size, // root_pass_size
global_pass_position, // global_pass_position
pass_depth, // pass_depth
clip_coverage_stack, // clip_coverage_stack
clip_depth_floor); // clip_depth_floor
switch (result.status) {
case EntityResult::kSuccess:
break;
case EntityResult::kFailure:
// All failure cases should be covered by specific validation messages
// in `GetEntityForElement()`.
return false;
case EntityResult::kSkip:
continue;
};
//--------------------------------------------------------------------------
/// Setup advanced blends.
///
if (result.entity.GetBlendMode() > Entity::kLastPipelineBlendMode) {
if (renderer.GetDeviceCapabilities().SupportsFramebufferFetch()) {
auto src_contents = result.entity.GetContents();
auto contents = std::make_shared<FramebufferBlendContents>();
contents->SetChildContents(src_contents);
contents->SetBlendMode(result.entity.GetBlendMode());
result.entity.SetContents(std::move(contents));
result.entity.SetBlendMode(BlendMode::kSource);
} else {
// End the active pass and flush the buffer before rendering "advanced"
// blends. Advanced blends work by binding the current render target
// texture as an input ("destination"), blending with a second texture
// input ("source"), writing the result to an intermediate texture, and
// finally copying the data from the intermediate texture back to the
// render target texture. And so all of the commands that have written
// to the render target texture so far need to execute before it's bound
// for blending (otherwise the blend pass will end up executing before
// all the previous commands in the active pass).
if (!pass_context.EndPass()) {
VALIDATION_LOG
<< "Failed to end the current render pass in order to read from "
"the backdrop texture and apply an advanced blend.";
return false;
}
// Amend an advanced blend filter to the contents, attaching the pass
// texture.
auto texture = pass_context.GetTexture();
if (!texture) {
VALIDATION_LOG << "Failed to fetch the color texture in order to "
"apply an advanced blend.";
return false;
}
FilterInput::Vector inputs = {
FilterInput::Make(texture, result.entity.GetTransform().Invert()),
FilterInput::Make(result.entity.GetContents())};
auto contents = ColorFilterContents::MakeBlend(
result.entity.GetBlendMode(), inputs);
contents->SetCoverageHint(result.entity.GetCoverage());
result.entity.SetContents(std::move(contents));
result.entity.SetBlendMode(BlendMode::kSource);
}
}
//--------------------------------------------------------------------------
/// Render the Element.
///
if (!RenderElement(result.entity, clip_depth_floor, pass_context,
pass_depth, renderer, clip_coverage_stack,
global_pass_position)) {
// Specific validation logs are handled in `render_element()`.
return false;
}
}
#ifdef IMPELLER_DEBUG
//--------------------------------------------------------------------------
/// Draw debug checkerboard over offscreen textures.
///
// When the pass depth is > 0, this EntityPass is being rendered to an
// offscreen texture.
if (enable_offscreen_debug_checkerboard_ &&
!collapsed_parent_pass.has_value() && pass_depth > 0) {
auto result = pass_context.GetRenderPass(pass_depth);
if (!result.pass) {
// Failure to produce a render pass should be explained by specific errors
// in `InlinePassContext::GetRenderPass()`.
return false;
}
auto checkerboard = CheckerboardContents();
auto color = ColorHSB(0, // hue
1, // saturation
std::max(0.0, 0.6 - pass_depth / 5), // brightness
0.25); // alpha
checkerboard.SetColor(Color(color));
checkerboard.Render(renderer, {}, *result.pass);
}
#endif
return true;
}
void EntityPass::IterateAllElements(
const std::function<bool(Element&)>& iterator) {
if (!iterator) {
return;
}
for (auto& element : elements_) {
if (!iterator(element)) {
return;
}
if (auto subpass = std::get_if<std::unique_ptr<EntityPass>>(&element)) {
subpass->get()->IterateAllElements(iterator);
}
}
}
void EntityPass::IterateAllElements(
const std::function<bool(const Element&)>& iterator) const {
/// TODO(gaaclarke): Remove duplication here between const and non-const
/// versions.
if (!iterator) {
return;
}
for (auto& element : elements_) {
if (!iterator(element)) {
return;
}
if (auto subpass = std::get_if<std::unique_ptr<EntityPass>>(&element)) {
const EntityPass* entity_pass = subpass->get();
entity_pass->IterateAllElements(iterator);
}
}
}
void EntityPass::IterateAllEntities(
const std::function<bool(Entity&)>& iterator) {
if (!iterator) {
return;
}
for (auto& element : elements_) {
if (auto entity = std::get_if<Entity>(&element)) {
if (!iterator(*entity)) {
return;
}
continue;
}
if (auto subpass = std::get_if<std::unique_ptr<EntityPass>>(&element)) {
subpass->get()->IterateAllEntities(iterator);
continue;
}
FML_UNREACHABLE();
}
}
void EntityPass::IterateAllEntities(
const std::function<bool(const Entity&)>& iterator) const {
if (!iterator) {
return;
}
for (const auto& element : elements_) {
if (auto entity = std::get_if<Entity>(&element)) {
if (!iterator(*entity)) {
return;
}
continue;
}
if (auto subpass = std::get_if<std::unique_ptr<EntityPass>>(&element)) {
const EntityPass* entity_pass = subpass->get();
entity_pass->IterateAllEntities(iterator);
continue;
}
FML_UNREACHABLE();
}
}
bool EntityPass::IterateUntilSubpass(
const std::function<bool(Entity&)>& iterator) {
if (!iterator) {
return true;
}
for (auto& element : elements_) {
if (auto entity = std::get_if<Entity>(&element)) {
if (!iterator(*entity)) {
return false;
}
continue;
}
return true;
}
return false;
}
size_t EntityPass::GetElementCount() const {
return elements_.size();
}
void EntityPass::SetTransform(Matrix transform) {
transform_ = transform;
}
void EntityPass::SetClipDepth(size_t clip_depth) {
clip_depth_ = clip_depth;
}
size_t EntityPass::GetClipDepth() const {
return clip_depth_;
}
void EntityPass::SetNewClipDepth(size_t clip_depth) {
new_clip_depth_ = clip_depth;
}
uint32_t EntityPass::GetNewClipDepth() const {
return new_clip_depth_;
}
void EntityPass::SetBlendMode(BlendMode blend_mode) {
blend_mode_ = blend_mode;
flood_clip_ = Entity::IsBlendModeDestructive(blend_mode);
}
Color EntityPass::GetClearColorOrDefault(ISize size) const {
return GetClearColor(size).value_or(Color::BlackTransparent());
}
std::optional<Color> EntityPass::GetClearColor(ISize target_size) const {
if (backdrop_filter_proc_) {
return std::nullopt;
}
std::optional<Color> result = std::nullopt;
for (const Element& element : elements_) {
auto [entity_color, blend_mode] =
ElementAsBackgroundColor(element, target_size);
if (!entity_color.has_value()) {
break;
}
result = result.value_or(Color::BlackTransparent())
.Blend(entity_color.value(), blend_mode);
}
if (result.has_value()) {
return result->Premultiply();
}
return result;
}
void EntityPass::SetBackdropFilter(BackdropFilterProc proc) {
if (superpass_) {
VALIDATION_LOG << "Backdrop filters cannot be set on EntityPasses that "
"have already been appended to another pass.";
}
backdrop_filter_proc_ = std::move(proc);
}
void EntityPass::SetEnableOffscreenCheckerboard(bool enabled) {
enable_offscreen_debug_checkerboard_ = enabled;
}
const EntityPassClipRecorder& EntityPass::GetEntityPassClipRecorder() const {
return *clip_replay_;
}
EntityPassClipRecorder::EntityPassClipRecorder() {}
void EntityPassClipRecorder::RecordEntity(const Entity& entity,
Contents::ClipCoverage::Type type) {
switch (type) {
case Contents::ClipCoverage::Type::kNoChange:
return;
case Contents::ClipCoverage::Type::kAppend:
rendered_clip_entities_.push_back(entity.Clone());
break;
case Contents::ClipCoverage::Type::kRestore:
rendered_clip_entities_.pop_back();
break;
}
}
const std::vector<Entity>& EntityPassClipRecorder::GetReplayEntities() const {
return rendered_clip_entities_;
}
} // namespace impeller
| engine/impeller/entity/entity_pass.cc/0 | {
"file_path": "engine/impeller/entity/entity_pass.cc",
"repo_id": "engine",
"token_count": 19172
} | 202 |
// 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.
#include "impeller/entity/geometry/fill_path_geometry.h"
#include "fml/logging.h"
#include "impeller/core/formats.h"
#include "impeller/entity/contents/content_context.h"
#include "impeller/entity/geometry/geometry.h"
namespace impeller {
FillPathGeometry::FillPathGeometry(const Path& path,
std::optional<Rect> inner_rect)
: path_(path), inner_rect_(inner_rect) {}
GeometryResult FillPathGeometry::GetPositionBuffer(
const ContentContext& renderer,
const Entity& entity,
RenderPass& pass) const {
auto& host_buffer = renderer.GetTransientsBuffer();
VertexBuffer vertex_buffer;
if constexpr (!ContentContext::kEnableStencilThenCover) {
if (!path_.IsConvex()) {
auto tesselation_result = renderer.GetTessellator()->Tessellate(
path_, entity.GetTransform().GetMaxBasisLength(),
[&vertex_buffer, &host_buffer](
const float* vertices, size_t vertices_count,
const uint16_t* indices, size_t indices_count) {
vertex_buffer.vertex_buffer = host_buffer.Emplace(
vertices, vertices_count * sizeof(float) * 2, alignof(float));
if (indices != nullptr) {
vertex_buffer.index_buffer = host_buffer.Emplace(
indices, indices_count * sizeof(uint16_t), alignof(uint16_t));
vertex_buffer.vertex_count = indices_count;
vertex_buffer.index_type = IndexType::k16bit;
} else {
vertex_buffer.index_buffer = {};
vertex_buffer.vertex_count = vertices_count;
vertex_buffer.index_type = IndexType::kNone;
}
return true;
});
if (tesselation_result != Tessellator::Result::kSuccess) {
return {};
}
return GeometryResult{
.type = PrimitiveType::kTriangle,
.vertex_buffer = vertex_buffer,
.transform = pass.GetOrthographicTransform() * entity.GetTransform(),
};
}
}
auto points = renderer.GetTessellator()->TessellateConvex(
path_, entity.GetTransform().GetMaxBasisLength());
vertex_buffer.vertex_buffer = host_buffer.Emplace(
points.data(), points.size() * sizeof(Point), alignof(Point));
vertex_buffer.index_buffer = {}, vertex_buffer.vertex_count = points.size();
vertex_buffer.index_type = IndexType::kNone;
return GeometryResult{
.type = PrimitiveType::kTriangleStrip,
.vertex_buffer = vertex_buffer,
.transform = pass.GetOrthographicTransform() * entity.GetTransform(),
.mode = GetResultMode(),
};
}
// |Geometry|
GeometryResult FillPathGeometry::GetPositionUVBuffer(
Rect texture_coverage,
Matrix effect_transform,
const ContentContext& renderer,
const Entity& entity,
RenderPass& pass) const {
using VS = TextureFillVertexShader;
auto uv_transform =
texture_coverage.GetNormalizingTransform() * effect_transform;
if constexpr (!ContentContext::kEnableStencilThenCover) {
if (!path_.IsConvex()) {
VertexBufferBuilder<VS::PerVertexData> vertex_builder;
auto tesselation_result = renderer.GetTessellator()->Tessellate(
path_, entity.GetTransform().GetMaxBasisLength(),
[&vertex_builder, &uv_transform](
const float* vertices, size_t vertices_count,
const uint16_t* indices, size_t indices_count) {
for (auto i = 0u; i < vertices_count * 2; i += 2) {
VS::PerVertexData data;
Point vtx = {vertices[i], vertices[i + 1]};
data.position = vtx;
data.texture_coords = uv_transform * vtx;
vertex_builder.AppendVertex(data);
}
FML_DCHECK(vertex_builder.GetVertexCount() == vertices_count);
if (indices != nullptr) {
for (auto i = 0u; i < indices_count; i++) {
vertex_builder.AppendIndex(indices[i]);
}
}
return true;
});
if (tesselation_result != Tessellator::Result::kSuccess) {
return {};
}
return GeometryResult{
.type = PrimitiveType::kTriangle,
.vertex_buffer =
vertex_builder.CreateVertexBuffer(renderer.GetTransientsBuffer()),
.transform = pass.GetOrthographicTransform() * entity.GetTransform(),
};
}
}
auto points = renderer.GetTessellator()->TessellateConvex(
path_, entity.GetTransform().GetMaxBasisLength());
VertexBufferBuilder<VS::PerVertexData> vertex_builder;
vertex_builder.Reserve(points.size());
for (auto i = 0u; i < points.size(); i++) {
VS::PerVertexData data;
data.position = points[i];
data.texture_coords = uv_transform * points[i];
vertex_builder.AppendVertex(data);
}
return GeometryResult{
.type = PrimitiveType::kTriangleStrip,
.vertex_buffer =
vertex_builder.CreateVertexBuffer(renderer.GetTransientsBuffer()),
.transform = pass.GetOrthographicTransform() * entity.GetTransform(),
.mode = GetResultMode(),
};
}
GeometryResult::Mode FillPathGeometry::GetResultMode() const {
if (!ContentContext::kEnableStencilThenCover || path_.IsConvex()) {
return GeometryResult::Mode::kNormal;
}
switch (path_.GetFillType()) {
case FillType::kNonZero:
return GeometryResult::Mode::kNonZero;
case FillType::kOdd:
return GeometryResult::Mode::kEvenOdd;
}
FML_UNREACHABLE();
}
GeometryVertexType FillPathGeometry::GetVertexType() const {
return GeometryVertexType::kPosition;
}
std::optional<Rect> FillPathGeometry::GetCoverage(
const Matrix& transform) const {
return path_.GetTransformedBoundingBox(transform);
}
bool FillPathGeometry::CoversArea(const Matrix& transform,
const Rect& rect) const {
if (!inner_rect_.has_value()) {
return false;
}
if (!transform.IsTranslationScaleOnly()) {
return false;
}
Rect coverage = inner_rect_->TransformBounds(transform);
return coverage.Contains(rect);
}
} // namespace impeller
| engine/impeller/entity/geometry/fill_path_geometry.cc/0 | {
"file_path": "engine/impeller/entity/geometry/fill_path_geometry.cc",
"repo_id": "engine",
"token_count": 2553
} | 203 |
// 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.
#ifndef FLUTTER_IMPELLER_ENTITY_GEOMETRY_VERTICES_GEOMETRY_H_
#define FLUTTER_IMPELLER_ENTITY_GEOMETRY_VERTICES_GEOMETRY_H_
#include "impeller/entity/geometry/geometry.h"
namespace impeller {
/// @brief A geometry that is created from a vertices object.
class VerticesGeometry final : public Geometry {
public:
enum class VertexMode {
kTriangles,
kTriangleStrip,
kTriangleFan,
};
VerticesGeometry(std::vector<Point> vertices,
std::vector<uint16_t> indices,
std::vector<Point> texture_coordinates,
std::vector<Color> colors,
Rect bounds,
VerticesGeometry::VertexMode vertex_mode);
~VerticesGeometry() = default;
GeometryResult GetPositionColorBuffer(const ContentContext& renderer,
const Entity& entity,
RenderPass& pass);
// |Geometry|
GeometryResult GetPositionUVBuffer(Rect texture_coverage,
Matrix effect_transform,
const ContentContext& renderer,
const Entity& entity,
RenderPass& pass) const override;
// |Geometry|
GeometryResult GetPositionBuffer(const ContentContext& renderer,
const Entity& entity,
RenderPass& pass) const override;
// |Geometry|
std::optional<Rect> GetCoverage(const Matrix& transform) const override;
// |Geometry|
GeometryVertexType GetVertexType() const override;
bool HasVertexColors() const;
bool HasTextureCoordinates() const;
std::optional<Rect> GetTextureCoordinateCoverge() const;
private:
void NormalizeIndices();
PrimitiveType GetPrimitiveType() const;
std::vector<Point> vertices_;
std::vector<Color> colors_;
std::vector<Point> texture_coordinates_;
std::vector<uint16_t> indices_;
Rect bounds_;
VerticesGeometry::VertexMode vertex_mode_ =
VerticesGeometry::VertexMode::kTriangles;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_ENTITY_GEOMETRY_VERTICES_GEOMETRY_H_
| engine/impeller/entity/geometry/vertices_geometry.h/0 | {
"file_path": "engine/impeller/entity/geometry/vertices_geometry.h",
"repo_id": "engine",
"token_count": 1021
} | 204 |
// 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.
#include <impeller/texture.glsl>
#include <impeller/types.glsl>
// Unused, see See PointFieldGeometry::GetPositionBuffer
layout(local_size_x = 16) in;
layout(std430) readonly buffer PointData {
// Size of this input data is frame_info.count;
vec2 points[];
}
point_data;
layout(std430) writeonly buffer GeometryData {
// Size of this output data is frame_info.count * points_per_circle;
vec2 geometry[];
}
geometry_data;
uniform FrameInfo {
uint count;
float16_t radius;
float16_t radian_start;
float16_t radian_step;
uint points_per_circle;
int divisions_per_circle;
}
frame_info;
void main() {
uint ident = gl_GlobalInvocationID.x;
if (ident >= frame_info.count) {
return;
}
vec2 center = point_data.points[ident];
uint bufer_offset = ident * frame_info.points_per_circle;
float16_t elapsed_angle = frame_info.radian_start;
vec2 origin =
center + vec2(cos(elapsed_angle), sin(elapsed_angle)) * frame_info.radius;
geometry_data.geometry[bufer_offset++] = origin;
elapsed_angle += frame_info.radian_step;
vec2 pt1 =
center + vec2(cos(elapsed_angle), sin(elapsed_angle)) * frame_info.radius;
geometry_data.geometry[bufer_offset++] = pt1;
elapsed_angle += frame_info.radian_step;
vec2 pt2 =
center + vec2(cos(elapsed_angle), sin(elapsed_angle)) * frame_info.radius;
geometry_data.geometry[bufer_offset++] = pt2;
for (int i = 0; i < frame_info.divisions_per_circle - 3; i++) {
geometry_data.geometry[bufer_offset++] = origin;
geometry_data.geometry[bufer_offset++] = pt2;
elapsed_angle += frame_info.radian_step;
pt2 = center +
vec2(cos(elapsed_angle), sin(elapsed_angle)) * frame_info.radius;
geometry_data.geometry[bufer_offset++] = pt2;
}
}
| engine/impeller/entity/shaders/geometry/points.comp/0 | {
"file_path": "engine/impeller/entity/shaders/geometry/points.comp",
"repo_id": "engine",
"token_count": 707
} | 205 |
// 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.
#include <impeller/types.glsl>
uniform FrameInfo {
mat4 mvp;
float depth;
}
frame_info;
in vec2 position;
out vec2 v_position;
void main() {
gl_Position = frame_info.mvp * vec4(position, 0.0, 1.0);
gl_Position /= gl_Position.w;
gl_Position.z = frame_info.depth;
// The fragment stage uses local coordinates to compute the blur.
v_position = position;
}
| engine/impeller/entity/shaders/rrect_blur.vert/0 | {
"file_path": "engine/impeller/entity/shaders/rrect_blur.vert",
"repo_id": "engine",
"token_count": 180
} | 206 |
// 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.
#ifndef FLUTTER_IMPELLER_GEOMETRY_HALF_H_
#define FLUTTER_IMPELLER_GEOMETRY_HALF_H_
#include <cstdint>
#include "flutter/fml/build_config.h"
#include "impeller/geometry/color.h"
#include "impeller/geometry/point.h"
#include "impeller/geometry/scalar.h"
#include "impeller/geometry/vector.h"
// NOLINTBEGIN(google-explicit-constructor)
#if defined(FML_OS_MACOSX) || defined(FML_OS_IOS) || \
defined(FML_OS_IOS_SIMULATOR)
using InternalHalf = _Float16;
#else
using InternalHalf = uint16_t;
#endif
namespace impeller {
/// @brief Convert a scalar to a half precision float.
///
/// See also: https://clang.llvm.org/docs/LanguageExtensions.html
/// This is not currently supported on Windows toolchains.
inline constexpr InternalHalf ScalarToHalf(Scalar f) {
#ifdef FML_OS_WIN
return static_cast<InternalHalf>(0);
#else
return static_cast<InternalHalf>(f);
#endif
}
/// @brief A storage only class for half precision floating point.
struct Half {
InternalHalf x = 0;
constexpr Half() {}
constexpr Half(double value) : x(ScalarToHalf(static_cast<Scalar>(value))) {}
constexpr Half(Scalar value) : x(ScalarToHalf(value)) {}
constexpr Half(int value) : x(ScalarToHalf(static_cast<Scalar>(value))) {}
constexpr Half(InternalHalf x) : x(x) {}
constexpr bool operator==(const Half& v) const { return v.x == x; }
constexpr bool operator!=(const Half& v) const { return v.x != x; }
};
/// @brief A storage only class for half precision floating point vector 4.
struct HalfVector4 {
union {
struct {
InternalHalf x = 0;
InternalHalf y = 0;
InternalHalf z = 0;
InternalHalf w = 0;
};
InternalHalf e[4];
};
constexpr HalfVector4() {}
constexpr HalfVector4(const Color& a)
: x(ScalarToHalf(a.red)),
y(ScalarToHalf(a.green)),
z(ScalarToHalf(a.blue)),
w(ScalarToHalf(a.alpha)) {}
constexpr HalfVector4(const Vector4& a)
: x(ScalarToHalf(a.x)),
y(ScalarToHalf(a.y)),
z(ScalarToHalf(a.z)),
w(ScalarToHalf(a.w)) {}
constexpr HalfVector4(InternalHalf x,
InternalHalf y,
InternalHalf z,
InternalHalf w)
: x(x), y(y), z(z), w(w) {}
constexpr bool operator==(const HalfVector4& v) const {
return v.x == x && v.y == y && v.z == z && v.w == w;
}
constexpr bool operator!=(const HalfVector4& v) const {
return v.x != x || v.y != y || v.z != z || v.w != w;
}
};
/// @brief A storage only class for half precision floating point vector 3.
struct HalfVector3 {
union {
struct {
InternalHalf x = 0;
InternalHalf y = 0;
InternalHalf z = 0;
};
InternalHalf e[3];
};
constexpr HalfVector3() {}
constexpr HalfVector3(const Vector3& a)
: x(ScalarToHalf(a.x)), y(ScalarToHalf(a.y)), z(ScalarToHalf(a.z)) {}
constexpr HalfVector3(InternalHalf x, InternalHalf y, InternalHalf z)
: x(x), y(y), z(z) {}
constexpr bool operator==(const HalfVector3& v) const {
return v.x == x && v.y == y && v.z == z;
}
constexpr bool operator!=(const HalfVector3& v) const {
return v.x != x || v.y != y || v.z != z;
}
};
/// @brief A storage only class for half precision floating point vector 2.
struct HalfVector2 {
union {
struct {
InternalHalf x = 0;
InternalHalf y = 0;
};
InternalHalf e[2];
};
constexpr HalfVector2() {}
constexpr HalfVector2(const Vector2& a)
: x(ScalarToHalf(a.x)), y(ScalarToHalf(a.y)) {}
constexpr HalfVector2(InternalHalf x, InternalHalf y) : x(x), y(y){};
constexpr bool operator==(const HalfVector2& v) const {
return v.x == x && v.y == y;
}
constexpr bool operator!=(const HalfVector2& v) const {
return v.x != x || v.y != y;
}
};
static_assert(sizeof(Half) == sizeof(uint16_t));
static_assert(sizeof(HalfVector2) == 2 * sizeof(Half));
static_assert(sizeof(HalfVector3) == 3 * sizeof(Half));
static_assert(sizeof(HalfVector4) == 4 * sizeof(Half));
} // namespace impeller
namespace std {
inline std::ostream& operator<<(std::ostream& out, const impeller::Half& p) {
out << "(" << static_cast<impeller::Scalar>(p.x) << ")";
return out;
}
inline std::ostream& operator<<(std::ostream& out,
const impeller::HalfVector2& p) {
out << "(" << static_cast<impeller::Scalar>(p.x) << ", "
<< static_cast<impeller::Scalar>(p.y) << ")";
return out;
}
inline std::ostream& operator<<(std::ostream& out,
const impeller::HalfVector3& p) {
out << "(" << static_cast<impeller::Scalar>(p.x) << ", "
<< static_cast<impeller::Scalar>(p.y) << ", "
<< static_cast<impeller::Scalar>(p.z) << ")";
return out;
}
inline std::ostream& operator<<(std::ostream& out,
const impeller::HalfVector4& p) {
out << "(" << static_cast<impeller::Scalar>(p.x) << ", "
<< static_cast<impeller::Scalar>(p.y) << ", "
<< static_cast<impeller::Scalar>(p.z) << ", "
<< static_cast<impeller::Scalar>(p.w) << ")";
return out;
}
// NOLINTEND(google-explicit-constructor)
} // namespace std
#endif // FLUTTER_IMPELLER_GEOMETRY_HALF_H_
| engine/impeller/geometry/half.h/0 | {
"file_path": "engine/impeller/geometry/half.h",
"repo_id": "engine",
"token_count": 2233
} | 207 |
// 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.
#ifndef FLUTTER_IMPELLER_GEOMETRY_QUATERNION_H_
#define FLUTTER_IMPELLER_GEOMETRY_QUATERNION_H_
#include <ostream>
#include "impeller/geometry/vector.h"
namespace impeller {
struct Quaternion {
union {
struct {
Scalar x = 0.0;
Scalar y = 0.0;
Scalar z = 0.0;
Scalar w = 1.0;
};
Scalar e[4];
};
Quaternion() {}
Quaternion(Scalar px, Scalar py, Scalar pz, Scalar pw)
: x(px), y(py), z(pz), w(pw) {}
Quaternion(const Vector3& axis, Scalar angle) {
const auto sine = sin(angle * 0.5f);
x = sine * axis.x;
y = sine * axis.y;
z = sine * axis.z;
w = cos(angle * 0.5f);
}
Scalar Dot(const Quaternion& q) const {
return x * q.x + y * q.y + z * q.z + w * q.w;
}
Scalar Length() const { return sqrt(x * x + y * y + z * z + w * w); }
Quaternion Normalize() const {
auto m = 1.0f / Length();
return {x * m, y * m, z * m, w * m};
}
Quaternion Invert() const { return {-x, -y, -z, w}; }
Quaternion Slerp(const Quaternion& to, double time) const;
Quaternion operator*(const Quaternion& o) const {
return {
w * o.x + x * o.w + y * o.z - z * o.y,
w * o.y + y * o.w + z * o.x - x * o.z,
w * o.z + z * o.w + x * o.y - y * o.x,
w * o.w - x * o.x - y * o.y - z * o.z,
};
}
Quaternion operator*(Scalar scale) const {
return {scale * x, scale * y, scale * z, scale * w};
}
Vector3 operator*(Vector3 vector) const {
Vector3 v(x, y, z);
return v * v.Dot(vector) * 2 + //
vector * (w * w - v.Dot(v)) + //
v.Cross(vector) * 2 * w;
}
Quaternion operator+(const Quaternion& o) const {
return {x + o.x, y + o.y, z + o.z, w + o.w};
}
Quaternion operator-(const Quaternion& o) const {
return {x - o.x, y - o.y, z - o.z, w - o.w};
}
bool operator==(const Quaternion& o) const {
return x == o.x && y == o.y && z == o.z && w == o.w;
}
bool operator!=(const Quaternion& o) const {
return x != o.x || y != o.y || z != o.z || w != o.w;
}
};
} // namespace impeller
namespace std {
inline std::ostream& operator<<(std::ostream& out,
const impeller::Quaternion& q) {
out << "(" << q.x << ", " << q.y << ", " << q.z << ", " << q.w << ")";
return out;
}
} // namespace std
#endif // FLUTTER_IMPELLER_GEOMETRY_QUATERNION_H_
| engine/impeller/geometry/quaternion.h/0 | {
"file_path": "engine/impeller/geometry/quaternion.h",
"repo_id": "engine",
"token_count": 1184
} | 208 |
// 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.
#include <math.h>
#include "fml/logging.h"
#include "gtest/gtest.h"
#include "flutter/impeller/geometry/trig.h"
namespace impeller {
namespace testing {
TEST(TrigTest, TrigAngles) {
{
Trig trig(Degrees(0.0));
EXPECT_EQ(trig.cos, 1.0);
EXPECT_EQ(trig.sin, 0.0);
}
{
Trig trig(Radians(0.0));
EXPECT_EQ(trig.cos, 1.0);
EXPECT_EQ(trig.sin, 0.0);
}
{
Trig trig(Degrees(30.0));
EXPECT_NEAR(trig.cos, sqrt(0.75), kEhCloseEnough);
EXPECT_NEAR(trig.sin, 0.5, kEhCloseEnough);
}
{
Trig trig(Radians(kPi / 6.0));
EXPECT_NEAR(trig.cos, sqrt(0.75), kEhCloseEnough);
EXPECT_NEAR(trig.sin, 0.5, kEhCloseEnough);
}
{
Trig trig(Degrees(60.0));
EXPECT_NEAR(trig.cos, 0.5, kEhCloseEnough);
EXPECT_NEAR(trig.sin, sqrt(0.75), kEhCloseEnough);
}
{
Trig trig(Radians(kPi / 3.0));
EXPECT_NEAR(trig.cos, 0.5, kEhCloseEnough);
EXPECT_NEAR(trig.sin, sqrt(0.75), kEhCloseEnough);
}
{
Trig trig(Degrees(90.0));
EXPECT_NEAR(trig.cos, 0.0, kEhCloseEnough);
EXPECT_NEAR(trig.sin, 1.0, kEhCloseEnough);
}
{
Trig trig(Radians(kPi / 2.0));
EXPECT_NEAR(trig.cos, 0.0, kEhCloseEnough);
EXPECT_NEAR(trig.sin, 1.0, kEhCloseEnough);
}
}
TEST(TrigTest, MultiplyByScalarRadius) {
for (int i = 0; i <= 360; i++) {
for (int i = 1; i <= 10; i++) {
Scalar radius = i * 5.0f;
EXPECT_EQ(Trig(Degrees(i)) * radius,
Point(radius * std::cos(i * kPi / 180),
radius * std::sin(i * kPi / 180)))
<< "at " << i << " degrees and radius " << radius;
}
}
}
} // namespace testing
} // namespace impeller
| engine/impeller/geometry/trig_unittests.cc/0 | {
"file_path": "engine/impeller/geometry/trig_unittests.cc",
"repo_id": "engine",
"token_count": 890
} | 209 |
// 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.
#ifndef FLUTTER_IMPELLER_GOLDEN_TESTS_METAL_SCREENSHOTTER_H_
#define FLUTTER_IMPELLER_GOLDEN_TESTS_METAL_SCREENSHOTTER_H_
#include "flutter/fml/macros.h"
#include "flutter/impeller/aiks/picture.h"
#include "flutter/impeller/golden_tests/metal_screenshot.h"
#include "flutter/impeller/golden_tests/screenshotter.h"
#include "flutter/impeller/playground/playground_impl.h"
namespace impeller {
namespace testing {
/// Converts `Picture`s and `DisplayList`s to `MetalScreenshot`s with the
/// playground backend.
class MetalScreenshotter : public Screenshotter {
public:
MetalScreenshotter();
std::unique_ptr<Screenshot> MakeScreenshot(
AiksContext& aiks_context,
const Picture& picture,
const ISize& size = {300, 300},
bool scale_content = true) override;
PlaygroundImpl& GetPlayground() override { return *playground_; }
private:
std::unique_ptr<PlaygroundImpl> playground_;
};
} // namespace testing
} // namespace impeller
#endif // FLUTTER_IMPELLER_GOLDEN_TESTS_METAL_SCREENSHOTTER_H_
| engine/impeller/golden_tests/metal_screenshotter.h/0 | {
"file_path": "engine/impeller/golden_tests/metal_screenshotter.h",
"repo_id": "engine",
"token_count": 427
} | 210 |
// 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.
#include "flutter/impeller/playground/backend/vulkan/swiftshader_utilities.h"
#include <cstdlib>
#include "flutter/fml/build_config.h"
#include "flutter/fml/file.h"
#include "flutter/fml/logging.h"
#include "flutter/fml/paths.h"
#if FML_OS_WIN
#include <Windows.h>
#endif // FML_OS_WIN
namespace impeller {
static void FindSwiftShaderICDAtKnownPaths() {
static constexpr const char* kSwiftShaderICDJSON = "vk_swiftshader_icd.json";
static constexpr const char* kVulkanICDFileNamesEnvVariableKey =
"VK_ICD_FILENAMES";
const auto executable_directory_path =
fml::paths::GetExecutableDirectoryPath();
FML_CHECK(executable_directory_path.first);
const auto executable_directory =
fml::OpenDirectory(executable_directory_path.second.c_str(), false,
fml::FilePermission::kRead);
FML_CHECK(executable_directory.is_valid());
if (fml::FileExists(executable_directory, kSwiftShaderICDJSON)) {
const auto icd_path = fml::paths::JoinPaths(
{executable_directory_path.second, kSwiftShaderICDJSON});
#if FML_OS_WIN
const auto success =
::SetEnvironmentVariableA(kVulkanICDFileNamesEnvVariableKey, //
icd_path.c_str() //
) != 0;
#else // FML_OS_WIN
const auto success = ::setenv(kVulkanICDFileNamesEnvVariableKey, //
icd_path.c_str(), //
1 // overwrite
) == 0;
#endif // FML_OS_WIN
FML_CHECK(success)
<< "Could not set the environment variable to use SwiftShader.";
} else {
FML_CHECK(false)
<< "Was asked to use SwiftShader but could not find the installable "
"client driver (ICD) for the locally built SwiftShader.";
}
}
void SetupSwiftshaderOnce(bool use_swiftshader) {
static bool swiftshader_preference = false;
static std::once_flag sOnceInitializer;
std::call_once(sOnceInitializer, [use_swiftshader]() {
if (use_swiftshader) {
FindSwiftShaderICDAtKnownPaths();
swiftshader_preference = use_swiftshader;
}
});
FML_CHECK(swiftshader_preference == use_swiftshader)
<< "The option to use SwiftShader in a process can only be set once and "
"may not be changed later.";
}
} // namespace impeller
| engine/impeller/playground/backend/vulkan/swiftshader_utilities.cc/0 | {
"file_path": "engine/impeller/playground/backend/vulkan/swiftshader_utilities.cc",
"repo_id": "engine",
"token_count": 1095
} | 211 |
// 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.
uniform UniformBuffer {
mat4 mvp;
}
uniform_buffer;
in vec2 vertex_position;
in vec2 texture_coordinates;
in vec4 vertex_color;
out vec2 frag_texture_coordinates;
out vec4 frag_vertex_color;
void main() {
gl_Position = uniform_buffer.mvp * vec4(vertex_position.xy, 0.0, 1.0);
frag_texture_coordinates = texture_coordinates;
frag_vertex_color = vertex_color;
}
| engine/impeller/playground/imgui/imgui_raster.vert/0 | {
"file_path": "engine/impeller/playground/imgui/imgui_raster.vert",
"repo_id": "engine",
"token_count": 178
} | 212 |
// 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.
#include "impeller/renderer/backend/gles/blit_command_gles.h"
#include "flutter/fml/closure.h"
#include "impeller/base/validation.h"
#include "impeller/renderer/backend/gles/device_buffer_gles.h"
#include "impeller/renderer/backend/gles/texture_gles.h"
namespace impeller {
BlitEncodeGLES::~BlitEncodeGLES() = default;
static void DeleteFBO(const ProcTableGLES& gl, GLuint fbo, GLenum type) {
if (fbo != GL_NONE) {
gl.BindFramebuffer(type, GL_NONE);
gl.DeleteFramebuffers(1u, &fbo);
}
};
static std::optional<GLuint> ConfigureFBO(
const ProcTableGLES& gl,
const std::shared_ptr<Texture>& texture,
GLenum fbo_type) {
auto handle = TextureGLES::Cast(texture.get())->GetGLHandle();
if (!handle.has_value()) {
return std::nullopt;
}
if (TextureGLES::Cast(*texture).IsWrapped()) {
// The texture is attached to the default FBO, so there's no need to
// create/configure one.
gl.BindFramebuffer(fbo_type, 0);
return 0;
}
GLuint fbo;
gl.GenFramebuffers(1u, &fbo);
gl.BindFramebuffer(fbo_type, fbo);
if (!TextureGLES::Cast(*texture).SetAsFramebufferAttachment(
fbo_type, TextureGLES::AttachmentType::kColor0)) {
VALIDATION_LOG << "Could not attach texture to framebuffer.";
DeleteFBO(gl, fbo, fbo_type);
return std::nullopt;
}
if (gl.CheckFramebufferStatus(fbo_type) != GL_FRAMEBUFFER_COMPLETE) {
VALIDATION_LOG << "Could not create a complete framebuffer.";
DeleteFBO(gl, fbo, fbo_type);
return std::nullopt;
}
return fbo;
};
BlitCopyTextureToTextureCommandGLES::~BlitCopyTextureToTextureCommandGLES() =
default;
std::string BlitCopyTextureToTextureCommandGLES::GetLabel() const {
return label;
}
bool BlitCopyTextureToTextureCommandGLES::Encode(
const ReactorGLES& reactor) const {
const auto& gl = reactor.GetProcTable();
// glBlitFramebuffer is a GLES3 proc. Since we target GLES2, we need to
// emulate the blit when it's not available in the driver.
if (!gl.BlitFramebuffer.IsAvailable()) {
// TODO(bdero): Emulate the blit using a raster draw call here.
FML_LOG(ERROR) << "Texture blit fallback not implemented yet for GLES2.";
return false;
}
GLuint read_fbo = GL_NONE;
GLuint draw_fbo = GL_NONE;
fml::ScopedCleanupClosure delete_fbos([&gl, &read_fbo, &draw_fbo]() {
DeleteFBO(gl, read_fbo, GL_READ_FRAMEBUFFER);
DeleteFBO(gl, draw_fbo, GL_DRAW_FRAMEBUFFER);
});
{
auto read = ConfigureFBO(gl, source, GL_READ_FRAMEBUFFER);
if (!read.has_value()) {
return false;
}
read_fbo = read.value();
}
{
auto draw = ConfigureFBO(gl, destination, GL_DRAW_FRAMEBUFFER);
if (!draw.has_value()) {
return false;
}
draw_fbo = draw.value();
}
gl.Disable(GL_SCISSOR_TEST);
gl.Disable(GL_DEPTH_TEST);
gl.Disable(GL_STENCIL_TEST);
gl.BlitFramebuffer(source_region.GetX(), // srcX0
source_region.GetY(), // srcY0
source_region.GetWidth(), // srcX1
source_region.GetHeight(), // srcY1
destination_origin.x, // dstX0
destination_origin.y, // dstY0
source_region.GetWidth(), // dstX1
source_region.GetHeight(), // dstY1
GL_COLOR_BUFFER_BIT, // mask
GL_NEAREST // filter
);
return true;
};
BlitCopyTextureToBufferCommandGLES::~BlitCopyTextureToBufferCommandGLES() =
default;
std::string BlitCopyTextureToBufferCommandGLES::GetLabel() const {
return label;
}
bool BlitCopyTextureToBufferCommandGLES::Encode(
const ReactorGLES& reactor) const {
if (source->GetTextureDescriptor().format != PixelFormat::kR8G8B8A8UNormInt) {
VALIDATION_LOG << "Only textures with pixel format RGBA are supported yet.";
return false;
}
const auto& gl = reactor.GetProcTable();
GLuint read_fbo = GL_NONE;
fml::ScopedCleanupClosure delete_fbos(
[&gl, &read_fbo]() { DeleteFBO(gl, read_fbo, GL_READ_FRAMEBUFFER); });
{
auto read = ConfigureFBO(gl, source, GL_READ_FRAMEBUFFER);
if (!read.has_value()) {
return false;
}
read_fbo = read.value();
}
DeviceBufferGLES::Cast(*destination)
.UpdateBufferData([&gl, this](uint8_t* data, size_t length) {
gl.ReadPixels(source_region.GetX(), source_region.GetY(),
source_region.GetWidth(), source_region.GetHeight(),
GL_RGBA, GL_UNSIGNED_BYTE, data + destination_offset);
});
return true;
};
BlitGenerateMipmapCommandGLES::~BlitGenerateMipmapCommandGLES() = default;
std::string BlitGenerateMipmapCommandGLES::GetLabel() const {
return label;
}
bool BlitGenerateMipmapCommandGLES::Encode(const ReactorGLES& reactor) const {
auto texture_gles = TextureGLES::Cast(texture.get());
if (!texture_gles->GenerateMipmap()) {
return false;
}
return true;
};
} // namespace impeller
| engine/impeller/renderer/backend/gles/blit_command_gles.cc/0 | {
"file_path": "engine/impeller/renderer/backend/gles/blit_command_gles.cc",
"repo_id": "engine",
"token_count": 2142
} | 213 |
// 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.
#include "impeller/renderer/backend/gles/formats_gles.h"
namespace impeller {
std::string DebugToFramebufferError(int status) {
switch (status) {
case GL_FRAMEBUFFER_UNDEFINED:
return "GL_FRAMEBUFFER_UNDEFINED";
case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
return "GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT";
case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
return "GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";
case GL_FRAMEBUFFER_UNSUPPORTED:
return "GL_FRAMEBUFFER_UNSUPPORTED";
case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE:
return "GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE";
default:
return "Unknown error code: " + std::to_string(status);
}
}
} // namespace impeller
| engine/impeller/renderer/backend/gles/formats_gles.cc/0 | {
"file_path": "engine/impeller/renderer/backend/gles/formats_gles.cc",
"repo_id": "engine",
"token_count": 352
} | 214 |
// 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.
#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_RENDER_PASS_GLES_H_
#define FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_RENDER_PASS_GLES_H_
#include <memory>
#include "flutter/impeller/renderer/backend/gles/reactor_gles.h"
#include "flutter/impeller/renderer/render_pass.h"
namespace impeller {
class RenderPassGLES final
: public RenderPass,
public std::enable_shared_from_this<RenderPassGLES> {
public:
// |RenderPass|
~RenderPassGLES() override;
private:
friend class CommandBufferGLES;
ReactorGLES::Ref reactor_;
std::string label_;
bool is_valid_ = false;
RenderPassGLES(std::shared_ptr<const Context> context,
const RenderTarget& target,
ReactorGLES::Ref reactor);
// |RenderPass|
bool IsValid() const override;
// |RenderPass|
void OnSetLabel(std::string label) override;
// |RenderPass|
bool OnEncodeCommands(const Context& context) const override;
RenderPassGLES(const RenderPassGLES&) = delete;
RenderPassGLES& operator=(const RenderPassGLES&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_RENDER_PASS_GLES_H_
| engine/impeller/renderer/backend/gles/render_pass_gles.h/0 | {
"file_path": "engine/impeller/renderer/backend/gles/render_pass_gles.h",
"repo_id": "engine",
"token_count": 486
} | 215 |
// 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.
#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_TEST_MOCK_GLES_H_
#define FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_TEST_MOCK_GLES_H_
#include <memory>
#include <optional>
#include "fml/macros.h"
#include "impeller/renderer/backend/gles/proc_table_gles.h"
namespace impeller {
namespace testing {
extern const ProcTableGLES::Resolver kMockResolverGLES;
/// @brief Provides a mocked version of the |ProcTableGLES| class.
///
/// Typically, Open GLES at runtime will be provided the host's GLES bindings
/// (as function pointers). This class maintains a set of function pointers that
/// appear to be GLES functions, but are actually just stubs that record
/// invocations.
///
/// See `README.md` for more information.
class MockGLES final {
public:
/// @brief Returns an initialized |MockGLES| instance.
///
/// This method overwrites mocked global GLES function pointers to record
/// invocations on this instance of |MockGLES|. As such, it should only be
/// called once per test.
static std::shared_ptr<MockGLES> Init(
const std::optional<std::vector<const unsigned char*>>& extensions =
std::nullopt,
const char* version_string = "OpenGL ES 3.0",
ProcTableGLES::Resolver resolver = kMockResolverGLES);
/// @brief Returns a configured |ProcTableGLES| instance.
const ProcTableGLES& GetProcTable() const { return proc_table_; }
/// @brief Returns a vector of the names of all recorded calls.
///
/// Calls are cleared after this method is called.
std::vector<std::string> GetCapturedCalls() {
std::vector<std::string> calls = captured_calls_;
captured_calls_.clear();
return calls;
}
~MockGLES();
private:
friend void RecordGLCall(const char* name);
explicit MockGLES(ProcTableGLES::Resolver resolver = kMockResolverGLES);
void RecordCall(const char* name) { captured_calls_.emplace_back(name); }
ProcTableGLES proc_table_;
std::vector<std::string> captured_calls_;
MockGLES(const MockGLES&) = delete;
MockGLES& operator=(const MockGLES&) = delete;
};
} // namespace testing
} // namespace impeller
#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_TEST_MOCK_GLES_H_
| engine/impeller/renderer/backend/gles/test/mock_gles.h/0 | {
"file_path": "engine/impeller/renderer/backend/gles/test/mock_gles.h",
"repo_id": "engine",
"token_count": 801
} | 216 |
// 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.
#include "impeller/renderer/backend/metal/compute_pass_bindings_cache_mtl.h"
namespace impeller {
void ComputePassBindingsCacheMTL::SetComputePipelineState(
id<MTLComputePipelineState> pipeline) {
if (pipeline == pipeline_) {
return;
}
pipeline_ = pipeline;
[encoder_ setComputePipelineState:pipeline_];
}
id<MTLComputePipelineState> ComputePassBindingsCacheMTL::GetPipeline() const {
return pipeline_;
}
void ComputePassBindingsCacheMTL::SetEncoder(
id<MTLComputeCommandEncoder> encoder) {
encoder_ = encoder;
}
void ComputePassBindingsCacheMTL::SetBuffer(uint64_t index,
uint64_t offset,
id<MTLBuffer> buffer) {
auto found = buffers_.find(index);
if (found != buffers_.end() && found->second.buffer == buffer) {
// The right buffer is bound. Check if its offset needs to be updated.
if (found->second.offset == offset) {
// Buffer and its offset is identical. Nothing to do.
return;
}
// Only the offset needs to be updated.
found->second.offset = offset;
[encoder_ setBufferOffset:offset atIndex:index];
return;
}
buffers_[index] = {buffer, static_cast<size_t>(offset)};
[encoder_ setBuffer:buffer offset:offset atIndex:index];
}
void ComputePassBindingsCacheMTL::SetTexture(uint64_t index,
id<MTLTexture> texture) {
auto found = textures_.find(index);
if (found != textures_.end() && found->second == texture) {
// Already bound.
return;
}
textures_[index] = texture;
[encoder_ setTexture:texture atIndex:index];
return;
}
void ComputePassBindingsCacheMTL::SetSampler(uint64_t index,
id<MTLSamplerState> sampler) {
auto found = samplers_.find(index);
if (found != samplers_.end() && found->second == sampler) {
// Already bound.
return;
}
samplers_[index] = sampler;
[encoder_ setSamplerState:sampler atIndex:index];
return;
}
} // namespace impeller
| engine/impeller/renderer/backend/metal/compute_pass_bindings_cache_mtl.mm/0 | {
"file_path": "engine/impeller/renderer/backend/metal/compute_pass_bindings_cache_mtl.mm",
"repo_id": "engine",
"token_count": 891
} | 217 |
// 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.
#include "impeller/renderer/backend/metal/pass_bindings_cache_mtl.h"
namespace impeller {
void PassBindingsCacheMTL::SetEncoder(id<MTLRenderCommandEncoder> encoder) {
encoder_ = encoder;
}
void PassBindingsCacheMTL::SetRenderPipelineState(
id<MTLRenderPipelineState> pipeline) {
if (pipeline == pipeline_) {
return;
}
pipeline_ = pipeline;
[encoder_ setRenderPipelineState:pipeline_];
}
void PassBindingsCacheMTL::SetDepthStencilState(
id<MTLDepthStencilState> depth_stencil) {
if (depth_stencil_ == depth_stencil) {
return;
}
depth_stencil_ = depth_stencil;
[encoder_ setDepthStencilState:depth_stencil_];
}
bool PassBindingsCacheMTL::SetBuffer(ShaderStage stage,
uint64_t index,
uint64_t offset,
id<MTLBuffer> buffer) {
auto& buffers_map = buffers_[stage];
auto found = buffers_map.find(index);
if (found != buffers_map.end() && found->second.buffer == buffer) {
// The right buffer is bound. Check if its offset needs to be updated.
if (found->second.offset == offset) {
// Buffer and its offset is identical. Nothing to do.
return true;
}
// Only the offset needs to be updated.
found->second.offset = offset;
switch (stage) {
case ShaderStage::kVertex:
[encoder_ setVertexBufferOffset:offset atIndex:index];
return true;
case ShaderStage::kFragment:
[encoder_ setFragmentBufferOffset:offset atIndex:index];
return true;
default:
VALIDATION_LOG << "Cannot update buffer offset of an unknown stage.";
return false;
}
return true;
}
buffers_map[index] = {buffer, static_cast<size_t>(offset)};
switch (stage) {
case ShaderStage::kVertex:
[encoder_ setVertexBuffer:buffer offset:offset atIndex:index];
return true;
case ShaderStage::kFragment:
[encoder_ setFragmentBuffer:buffer offset:offset atIndex:index];
return true;
default:
VALIDATION_LOG << "Cannot bind buffer to unknown shader stage.";
return false;
}
return false;
}
bool PassBindingsCacheMTL::SetTexture(ShaderStage stage,
uint64_t index,
id<MTLTexture> texture) {
auto& texture_map = textures_[stage];
auto found = texture_map.find(index);
if (found != texture_map.end() && found->second == texture) {
// Already bound.
return true;
}
texture_map[index] = texture;
switch (stage) {
case ShaderStage::kVertex:
[encoder_ setVertexTexture:texture atIndex:index];
return true;
case ShaderStage::kFragment:
[encoder_ setFragmentTexture:texture atIndex:index];
return true;
default:
VALIDATION_LOG << "Cannot bind buffer to unknown shader stage.";
return false;
}
return false;
}
bool PassBindingsCacheMTL::SetSampler(ShaderStage stage,
uint64_t index,
id<MTLSamplerState> sampler) {
auto& sampler_map = samplers_[stage];
auto found = sampler_map.find(index);
if (found != sampler_map.end() && found->second == sampler) {
// Already bound.
return true;
}
sampler_map[index] = sampler;
switch (stage) {
case ShaderStage::kVertex:
[encoder_ setVertexSamplerState:sampler atIndex:index];
return true;
case ShaderStage::kFragment:
[encoder_ setFragmentSamplerState:sampler atIndex:index];
return true;
default:
VALIDATION_LOG << "Cannot bind buffer to unknown shader stage.";
return false;
}
return false;
}
void PassBindingsCacheMTL::SetViewport(const Viewport& viewport) {
if (viewport_.has_value() && viewport_.value() == viewport) {
return;
}
[encoder_ setViewport:MTLViewport{
.originX = viewport.rect.GetX(),
.originY = viewport.rect.GetY(),
.width = viewport.rect.GetWidth(),
.height = viewport.rect.GetHeight(),
.znear = viewport.depth_range.z_near,
.zfar = viewport.depth_range.z_far,
}];
viewport_ = viewport;
}
void PassBindingsCacheMTL::SetScissor(const IRect& scissor) {
if (scissor_.has_value() && scissor_.value() == scissor) {
return;
}
[encoder_
setScissorRect:MTLScissorRect{
.x = static_cast<NSUInteger>(scissor.GetX()),
.y = static_cast<NSUInteger>(scissor.GetY()),
.width = static_cast<NSUInteger>(scissor.GetWidth()),
.height = static_cast<NSUInteger>(scissor.GetHeight()),
}];
scissor_ = scissor;
}
} // namespace impeller
| engine/impeller/renderer/backend/metal/pass_bindings_cache_mtl.mm/0 | {
"file_path": "engine/impeller/renderer/backend/metal/pass_bindings_cache_mtl.mm",
"repo_id": "engine",
"token_count": 2243
} | 218 |
// 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.
#include "impeller/renderer/backend/metal/surface_mtl.h"
#include "flutter/fml/trace_event.h"
#include "flutter/impeller/renderer/command_buffer.h"
#include "impeller/base/validation.h"
#include "impeller/core/texture_descriptor.h"
#include "impeller/renderer/backend/metal/context_mtl.h"
#include "impeller/renderer/backend/metal/formats_mtl.h"
#include "impeller/renderer/backend/metal/texture_mtl.h"
#include "impeller/renderer/render_target.h"
@protocol FlutterMetalDrawable <MTLDrawable>
- (void)flutterPrepareForPresent:(nonnull id<MTLCommandBuffer>)commandBuffer;
@end
namespace impeller {
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunguarded-availability-new"
id<CAMetalDrawable> SurfaceMTL::GetMetalDrawableAndValidate(
const std::shared_ptr<Context>& context,
CAMetalLayer* layer) {
TRACE_EVENT0("impeller", "SurfaceMTL::WrapCurrentMetalLayerDrawable");
if (context == nullptr || !context->IsValid() || layer == nil) {
return nullptr;
}
id<CAMetalDrawable> current_drawable = nil;
{
TRACE_EVENT0("impeller", "WaitForNextDrawable");
current_drawable = [layer nextDrawable];
}
if (!current_drawable) {
VALIDATION_LOG << "Could not acquire current drawable.";
return nullptr;
}
return current_drawable;
}
static std::optional<RenderTarget> WrapTextureWithRenderTarget(
Allocator& allocator,
id<MTLTexture> texture,
bool requires_blit,
std::optional<IRect> clip_rect) {
// compositor_context.cc will offset the rendering by the clip origin. Here we
// shrink to the size of the clip. This has the same effect as clipping the
// rendering but also creates smaller intermediate passes.
ISize root_size;
if (requires_blit) {
if (!clip_rect.has_value()) {
VALIDATION_LOG << "Missing clip rectangle.";
return std::nullopt;
}
root_size = ISize(clip_rect->GetWidth(), clip_rect->GetHeight());
} else {
root_size = {static_cast<ISize::Type>(texture.width),
static_cast<ISize::Type>(texture.height)};
}
TextureDescriptor resolve_tex_desc;
resolve_tex_desc.format = FromMTLPixelFormat(texture.pixelFormat);
resolve_tex_desc.size = root_size;
resolve_tex_desc.usage =
TextureUsage::kRenderTarget | TextureUsage::kShaderRead;
resolve_tex_desc.sample_count = SampleCount::kCount1;
resolve_tex_desc.storage_mode = StorageMode::kDevicePrivate;
if (resolve_tex_desc.format == PixelFormat::kUnknown) {
VALIDATION_LOG << "Unknown drawable color format.";
return std::nullopt;
}
// Create color resolve texture.
std::shared_ptr<Texture> resolve_tex;
if (requires_blit) {
resolve_tex_desc.compression_type = CompressionType::kLossy;
resolve_tex = allocator.CreateTexture(resolve_tex_desc);
} else {
resolve_tex = TextureMTL::Create(resolve_tex_desc, texture);
}
if (!resolve_tex) {
VALIDATION_LOG << "Could not wrap resolve texture.";
return std::nullopt;
}
resolve_tex->SetLabel("ImpellerOnscreenResolve");
TextureDescriptor msaa_tex_desc;
msaa_tex_desc.storage_mode = StorageMode::kDeviceTransient;
msaa_tex_desc.type = TextureType::kTexture2DMultisample;
msaa_tex_desc.sample_count = SampleCount::kCount4;
msaa_tex_desc.format = resolve_tex->GetTextureDescriptor().format;
msaa_tex_desc.size = resolve_tex->GetSize();
msaa_tex_desc.usage = TextureUsage::kRenderTarget;
auto msaa_tex = allocator.CreateTexture(msaa_tex_desc);
if (!msaa_tex) {
VALIDATION_LOG << "Could not allocate MSAA color texture.";
return std::nullopt;
}
msaa_tex->SetLabel("ImpellerOnscreenColorMSAA");
ColorAttachment color0;
color0.texture = msaa_tex;
color0.clear_color = Color::DarkSlateGray();
color0.load_action = LoadAction::kClear;
color0.store_action = StoreAction::kMultisampleResolve;
color0.resolve_texture = std::move(resolve_tex);
auto render_target_desc = std::make_optional<RenderTarget>();
render_target_desc->SetColorAttachment(color0, 0u);
return render_target_desc;
}
std::unique_ptr<SurfaceMTL> SurfaceMTL::MakeFromMetalLayerDrawable(
const std::shared_ptr<Context>& context,
id<CAMetalDrawable> drawable,
std::optional<IRect> clip_rect) {
return SurfaceMTL::MakeFromTexture(context, drawable.texture, clip_rect,
drawable);
}
std::unique_ptr<SurfaceMTL> SurfaceMTL::MakeFromTexture(
const std::shared_ptr<Context>& context,
id<MTLTexture> texture,
std::optional<IRect> clip_rect,
id<CAMetalDrawable> drawable) {
bool partial_repaint_blit_required = ShouldPerformPartialRepaint(clip_rect);
// The returned render target is the texture that Impeller will render the
// root pass to. If partial repaint is in use, this may be a new texture which
// is smaller than the given MTLTexture.
auto render_target =
WrapTextureWithRenderTarget(*context->GetResourceAllocator(), texture,
partial_repaint_blit_required, clip_rect);
if (!render_target) {
return nullptr;
}
// If partial repainting, set a "source" texture. The presence of a source
// texture and clip rect instructs the surface to blit this texture to the
// destination texture.
auto source_texture = partial_repaint_blit_required
? render_target->GetRenderTargetTexture()
: nullptr;
// The final "destination" texture is the texture that will be presented. In
// this case, it's always the given drawable.
std::shared_ptr<Texture> destination_texture;
if (partial_repaint_blit_required) {
// If blitting for partial repaint, we need to wrap the drawable. Simply
// reuse the texture descriptor that was already formed for the new render
// target, but override the size with the drawable's size.
auto destination_descriptor =
render_target->GetRenderTargetTexture()->GetTextureDescriptor();
destination_descriptor.size = {static_cast<ISize::Type>(texture.width),
static_cast<ISize::Type>(texture.height)};
destination_texture = TextureMTL::Wrapper(destination_descriptor, texture);
} else {
// When not partial repaint blit is needed, the render target texture _is_
// the drawable texture.
destination_texture = render_target->GetRenderTargetTexture();
}
return std::unique_ptr<SurfaceMTL>(new SurfaceMTL(
context, // context
*render_target, // target
render_target->GetRenderTargetTexture(), // resolve_texture
drawable, // drawable
source_texture, // source_texture
destination_texture, // destination_texture
partial_repaint_blit_required, // requires_blit
clip_rect // clip_rect
));
}
SurfaceMTL::SurfaceMTL(const std::weak_ptr<Context>& context,
const RenderTarget& target,
std::shared_ptr<Texture> resolve_texture,
id<CAMetalDrawable> drawable,
std::shared_ptr<Texture> source_texture,
std::shared_ptr<Texture> destination_texture,
bool requires_blit,
std::optional<IRect> clip_rect)
: Surface(target),
context_(context),
resolve_texture_(std::move(resolve_texture)),
drawable_(drawable),
source_texture_(std::move(source_texture)),
destination_texture_(std::move(destination_texture)),
requires_blit_(requires_blit),
clip_rect_(clip_rect) {}
// |Surface|
SurfaceMTL::~SurfaceMTL() = default;
bool SurfaceMTL::ShouldPerformPartialRepaint(std::optional<IRect> damage_rect) {
// compositor_context.cc will conditionally disable partial repaint if the
// damage region is large. If that happened, then a nullopt damage rect
// will be provided here.
if (!damage_rect.has_value()) {
return false;
}
// If the damage rect is 0 in at least one dimension, partial repaint isn't
// performed as we skip right to present.
if (damage_rect->IsEmpty()) {
return false;
}
return true;
}
// |Surface|
IRect SurfaceMTL::coverage() const {
return IRect::MakeSize(resolve_texture_->GetSize());
}
// |Surface|
bool SurfaceMTL::Present() const {
auto context = context_.lock();
if (!context) {
return false;
}
if (requires_blit_) {
if (!(source_texture_ && destination_texture_)) {
return false;
}
auto blit_command_buffer = context->CreateCommandBuffer();
if (!blit_command_buffer) {
return false;
}
auto blit_pass = blit_command_buffer->CreateBlitPass();
if (!clip_rect_.has_value()) {
VALIDATION_LOG << "Missing clip rectangle.";
return false;
}
blit_pass->AddCopy(source_texture_, destination_texture_, std::nullopt,
clip_rect_->GetOrigin());
blit_pass->EncodeCommands(context->GetResourceAllocator());
if (!context->GetCommandQueue()->Submit({blit_command_buffer}).ok()) {
return false;
}
}
#ifdef IMPELLER_DEBUG
ContextMTL::Cast(context.get())->GetGPUTracer()->MarkFrameEnd();
#endif // IMPELLER_DEBUG
if (drawable_) {
id<MTLCommandBuffer> command_buffer =
ContextMTL::Cast(context.get())
->CreateMTLCommandBuffer("Present Waiter Command Buffer");
id<CAMetalDrawable> metal_drawable =
reinterpret_cast<id<CAMetalDrawable>>(drawable_);
if ([metal_drawable conformsToProtocol:@protocol(FlutterMetalDrawable)]) {
[(id<FlutterMetalDrawable>)metal_drawable
flutterPrepareForPresent:command_buffer];
}
// If the threads have been merged, or there is a pending frame capture,
// then block on cmd buffer scheduling to ensure that the
// transaction/capture work correctly.
if ([[NSThread currentThread] isMainThread] ||
[[MTLCaptureManager sharedCaptureManager] isCapturing]) {
TRACE_EVENT0("flutter", "waitUntilScheduled");
[command_buffer commit];
[command_buffer waitUntilScheduled];
[drawable_ present];
} else {
// The drawable may come from a FlutterMetalLayer, so it can't be
// presented through the command buffer.
id<CAMetalDrawable> drawable = drawable_;
[command_buffer addScheduledHandler:^(id<MTLCommandBuffer> buffer) {
[drawable present];
}];
[command_buffer commit];
}
}
return true;
}
#pragma GCC diagnostic pop
} // namespace impeller
| engine/impeller/renderer/backend/metal/surface_mtl.mm/0 | {
"file_path": "engine/impeller/renderer/backend/metal/surface_mtl.mm",
"repo_id": "engine",
"token_count": 4086
} | 219 |
// 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.
#include "impeller/renderer/backend/vulkan/blit_command_vk.h"
#include <cstdint>
#include "impeller/renderer/backend/vulkan/command_encoder_vk.h"
#include "impeller/renderer/backend/vulkan/texture_vk.h"
namespace impeller {
BlitEncodeVK::~BlitEncodeVK() = default;
//------------------------------------------------------------------------------
/// BlitCopyTextureToTextureCommandVK
///
BlitCopyTextureToTextureCommandVK::~BlitCopyTextureToTextureCommandVK() =
default;
std::string BlitCopyTextureToTextureCommandVK::GetLabel() const {
return label;
}
bool BlitCopyTextureToTextureCommandVK::Encode(
CommandEncoderVK& encoder) const {
const auto& cmd_buffer = encoder.GetCommandBuffer();
const auto& src = TextureVK::Cast(*source);
const auto& dst = TextureVK::Cast(*destination);
if (!encoder.Track(source) || !encoder.Track(destination)) {
return false;
}
BarrierVK src_barrier;
src_barrier.cmd_buffer = cmd_buffer;
src_barrier.new_layout = vk::ImageLayout::eTransferSrcOptimal;
src_barrier.src_access = vk::AccessFlagBits::eTransferWrite |
vk::AccessFlagBits::eShaderWrite |
vk::AccessFlagBits::eColorAttachmentWrite;
src_barrier.src_stage = vk::PipelineStageFlagBits::eTransfer |
vk::PipelineStageFlagBits::eFragmentShader |
vk::PipelineStageFlagBits::eColorAttachmentOutput;
src_barrier.dst_access = vk::AccessFlagBits::eTransferRead;
src_barrier.dst_stage = vk::PipelineStageFlagBits::eTransfer;
BarrierVK dst_barrier;
dst_barrier.cmd_buffer = cmd_buffer;
dst_barrier.new_layout = vk::ImageLayout::eTransferDstOptimal;
dst_barrier.src_access = {};
dst_barrier.src_stage = vk::PipelineStageFlagBits::eTopOfPipe;
dst_barrier.dst_access =
vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eTransferWrite;
dst_barrier.dst_stage = vk::PipelineStageFlagBits::eFragmentShader |
vk::PipelineStageFlagBits::eTransfer;
if (!src.SetLayout(src_barrier) || !dst.SetLayout(dst_barrier)) {
VALIDATION_LOG << "Could not complete layout transitions.";
return false;
}
vk::ImageCopy image_copy;
image_copy.setSrcSubresource(
vk::ImageSubresourceLayers(vk::ImageAspectFlagBits::eColor, 0, 0, 1));
image_copy.setDstSubresource(
vk::ImageSubresourceLayers(vk::ImageAspectFlagBits::eColor, 0, 0, 1));
image_copy.srcOffset =
vk::Offset3D(source_region.GetX(), source_region.GetY(), 0);
image_copy.dstOffset =
vk::Offset3D(destination_origin.x, destination_origin.y, 0);
image_copy.extent =
vk::Extent3D(source_region.GetWidth(), source_region.GetHeight(), 1);
// Issue the copy command now that the images are already in the right
// layouts.
cmd_buffer.copyImage(src.GetImage(), //
src_barrier.new_layout, //
dst.GetImage(), //
dst_barrier.new_layout, //
image_copy //
);
// If this is an onscreen texture, do not transition the layout
// back to shader read.
if (dst.IsSwapchainImage()) {
return true;
}
BarrierVK barrier;
barrier.cmd_buffer = cmd_buffer;
barrier.new_layout = vk::ImageLayout::eShaderReadOnlyOptimal;
barrier.src_access = {};
barrier.src_stage = vk::PipelineStageFlagBits::eTopOfPipe;
barrier.dst_access = vk::AccessFlagBits::eShaderRead;
barrier.dst_stage = vk::PipelineStageFlagBits::eFragmentShader;
return dst.SetLayout(barrier);
}
//------------------------------------------------------------------------------
/// BlitCopyTextureToBufferCommandVK
///
BlitCopyTextureToBufferCommandVK::~BlitCopyTextureToBufferCommandVK() = default;
std::string BlitCopyTextureToBufferCommandVK::GetLabel() const {
return label;
}
bool BlitCopyTextureToBufferCommandVK::Encode(CommandEncoderVK& encoder) const {
const auto& cmd_buffer = encoder.GetCommandBuffer();
// cast source and destination to TextureVK
const auto& src = TextureVK::Cast(*source);
if (!encoder.Track(source) || !encoder.Track(destination)) {
return false;
}
BarrierVK barrier;
barrier.cmd_buffer = cmd_buffer;
barrier.new_layout = vk::ImageLayout::eTransferSrcOptimal;
barrier.src_access = vk::AccessFlagBits::eShaderWrite |
vk::AccessFlagBits::eTransferWrite |
vk::AccessFlagBits::eColorAttachmentWrite;
barrier.src_stage = vk::PipelineStageFlagBits::eFragmentShader |
vk::PipelineStageFlagBits::eTransfer |
vk::PipelineStageFlagBits::eColorAttachmentOutput;
barrier.dst_access = vk::AccessFlagBits::eShaderRead;
barrier.dst_stage = vk::PipelineStageFlagBits::eVertexShader |
vk::PipelineStageFlagBits::eFragmentShader;
const auto& dst = DeviceBufferVK::Cast(*destination);
vk::BufferImageCopy image_copy;
image_copy.setBufferOffset(destination_offset);
image_copy.setBufferRowLength(0);
image_copy.setBufferImageHeight(0);
image_copy.setImageSubresource(
vk::ImageSubresourceLayers(vk::ImageAspectFlagBits::eColor, 0, 0, 1));
image_copy.setImageOffset(
vk::Offset3D(source_region.GetX(), source_region.GetY(), 0));
image_copy.setImageExtent(
vk::Extent3D(source_region.GetWidth(), source_region.GetHeight(), 1));
if (!src.SetLayout(barrier)) {
VALIDATION_LOG << "Could not encode layout transition.";
return false;
}
cmd_buffer.copyImageToBuffer(src.GetImage(), //
barrier.new_layout, //
dst.GetBuffer(), //
image_copy //
);
// If the buffer is used for readback, then apply a transfer -> host memory
// barrier.
if (destination->GetDeviceBufferDescriptor().readback) {
vk::MemoryBarrier barrier;
barrier.srcAccessMask = vk::AccessFlagBits::eTransferWrite;
barrier.dstAccessMask = vk::AccessFlagBits::eHostRead;
cmd_buffer.pipelineBarrier(vk::PipelineStageFlagBits::eTransfer,
vk::PipelineStageFlagBits::eHost, {}, 1,
&barrier, 0, {}, 0, {});
}
return true;
}
//------------------------------------------------------------------------------
/// BlitCopyBufferToTextureCommandVK
///
BlitCopyBufferToTextureCommandVK::~BlitCopyBufferToTextureCommandVK() = default;
std::string BlitCopyBufferToTextureCommandVK::GetLabel() const {
return label;
}
bool BlitCopyBufferToTextureCommandVK::Encode(CommandEncoderVK& encoder) const {
const auto& cmd_buffer = encoder.GetCommandBuffer();
// cast destination to TextureVK
const auto& dst = TextureVK::Cast(*destination);
const auto& src = DeviceBufferVK::Cast(*source.buffer);
if (!encoder.Track(source.buffer) || !encoder.Track(destination)) {
return false;
}
BarrierVK dst_barrier;
dst_barrier.cmd_buffer = cmd_buffer;
dst_barrier.new_layout = vk::ImageLayout::eTransferDstOptimal;
dst_barrier.src_access = {};
dst_barrier.src_stage = vk::PipelineStageFlagBits::eTopOfPipe;
dst_barrier.dst_access =
vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eTransferWrite;
dst_barrier.dst_stage = vk::PipelineStageFlagBits::eFragmentShader |
vk::PipelineStageFlagBits::eTransfer;
vk::BufferImageCopy image_copy;
image_copy.setBufferOffset(source.range.offset);
image_copy.setBufferRowLength(0);
image_copy.setBufferImageHeight(0);
image_copy.setImageSubresource(
vk::ImageSubresourceLayers(vk::ImageAspectFlagBits::eColor, 0, 0, 1));
image_copy.setImageOffset(
vk::Offset3D(destination_origin.x, destination_origin.y, 0));
image_copy.setImageExtent(vk::Extent3D(destination->GetSize().width,
destination->GetSize().height, 1));
if (!dst.SetLayout(dst_barrier)) {
VALIDATION_LOG << "Could not encode layout transition.";
return false;
}
cmd_buffer.copyBufferToImage(src.GetBuffer(), //
dst.GetImage(), //
dst_barrier.new_layout, //
image_copy //
);
return true;
}
//------------------------------------------------------------------------------
/// BlitGenerateMipmapCommandVK
///
BlitGenerateMipmapCommandVK::~BlitGenerateMipmapCommandVK() = default;
std::string BlitGenerateMipmapCommandVK::GetLabel() const {
return label;
}
static void InsertImageMemoryBarrier(const vk::CommandBuffer& cmd,
const vk::Image& image,
vk::AccessFlags src_access_mask,
vk::AccessFlags dst_access_mask,
vk::ImageLayout old_layout,
vk::ImageLayout new_layout,
vk::PipelineStageFlags src_stage,
vk::PipelineStageFlags dst_stage,
uint32_t base_mip_level,
uint32_t mip_level_count = 1u) {
if (old_layout == new_layout) {
return;
}
vk::ImageMemoryBarrier barrier;
barrier.srcAccessMask = src_access_mask;
barrier.dstAccessMask = dst_access_mask;
barrier.oldLayout = old_layout;
barrier.newLayout = new_layout;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.image = image;
barrier.subresourceRange.aspectMask = vk::ImageAspectFlagBits::eColor;
barrier.subresourceRange.baseMipLevel = base_mip_level;
barrier.subresourceRange.levelCount = mip_level_count;
barrier.subresourceRange.baseArrayLayer = 0u;
barrier.subresourceRange.layerCount = 1u;
cmd.pipelineBarrier(src_stage, dst_stage, {}, nullptr, nullptr, barrier);
}
bool BlitGenerateMipmapCommandVK::Encode(CommandEncoderVK& encoder) const {
auto& src = TextureVK::Cast(*texture);
const auto size = src.GetTextureDescriptor().size;
uint32_t mip_count = src.GetTextureDescriptor().mip_count;
if (mip_count < 2u) {
return true;
}
const auto& image = src.GetImage();
const auto& cmd = encoder.GetCommandBuffer();
if (!encoder.Track(texture)) {
return false;
}
// Transition the base mip level to transfer-src layout so we can read from
// it and transition the rest to dst-optimal since they are going to be
// written to.
InsertImageMemoryBarrier(
cmd, // command buffer
image, // image
vk::AccessFlagBits::eTransferWrite, // src access mask
vk::AccessFlagBits::eTransferRead, // dst access mask
src.GetLayout(), // old layout
vk::ImageLayout::eTransferSrcOptimal, // new layout
vk::PipelineStageFlagBits::eTransfer, // src stage
vk::PipelineStageFlagBits::eTransfer, // dst stage
0u // mip level
);
InsertImageMemoryBarrier(
cmd, // command buffer
image, // image
{}, // src access mask
vk::AccessFlagBits::eTransferWrite, // dst access mask
vk::ImageLayout::eUndefined, // old layout
vk::ImageLayout::eTransferDstOptimal, // new layout
vk::PipelineStageFlagBits::eTransfer, // src stage
vk::PipelineStageFlagBits::eTransfer, // dst stage
1u, // mip level
mip_count - 1 // mip level count
);
// Blit from the base mip level to all other levels.
for (size_t mip_level = 1u; mip_level < mip_count; mip_level++) {
vk::ImageBlit blit;
blit.srcSubresource.aspectMask = vk::ImageAspectFlagBits::eColor;
blit.srcSubresource.baseArrayLayer = 0u;
blit.srcSubresource.layerCount = 1u;
blit.srcSubresource.mipLevel = 0u;
blit.dstSubresource.aspectMask = vk::ImageAspectFlagBits::eColor;
blit.dstSubresource.baseArrayLayer = 0u;
blit.dstSubresource.layerCount = 1u;
blit.dstSubresource.mipLevel = mip_level;
// offsets[0] is origin.
blit.srcOffsets[1].x = size.width;
blit.srcOffsets[1].y = size.height;
blit.srcOffsets[1].z = 1u;
// offsets[0] is origin.
blit.dstOffsets[1].x = std::max<int32_t>(size.width >> mip_level, 1u);
blit.dstOffsets[1].y = std::max<int32_t>(size.height >> mip_level, 1u);
blit.dstOffsets[1].z = 1u;
cmd.blitImage(image, // src image
vk::ImageLayout::eTransferSrcOptimal, // src layout
image, // dst image
vk::ImageLayout::eTransferDstOptimal, // dst layout
1u, // region count
&blit, // regions
vk::Filter::eLinear // filter
);
}
// Transition all mip levels to shader read. The base mip level has a
// different "old" layout than the rest now.
InsertImageMemoryBarrier(
cmd, // command buffer
image, // image
vk::AccessFlagBits::eTransferWrite, // src access mask
vk::AccessFlagBits::eShaderRead, // dst access mask
vk::ImageLayout::eTransferSrcOptimal, // old layout
vk::ImageLayout::eShaderReadOnlyOptimal, // new layout
vk::PipelineStageFlagBits::eTransfer, // src stage
vk::PipelineStageFlagBits::eFragmentShader, // dst stage
0u // mip level
);
InsertImageMemoryBarrier(
cmd, // command buffer
image, // image
vk::AccessFlagBits::eTransferWrite, // src access mask
vk::AccessFlagBits::eShaderRead, // dst access mask
vk::ImageLayout::eTransferDstOptimal, // old layout
vk::ImageLayout::eShaderReadOnlyOptimal, // new layout
vk::PipelineStageFlagBits::eTransfer, // src stage
vk::PipelineStageFlagBits::eFragmentShader, // dst stage
1u, // mip level
mip_count - 1 // mip level count
);
// We modified the layouts of this image from underneath it. Tell it its new
// state so it doesn't try to perform redundant transitions under the hood.
src.SetLayoutWithoutEncoding(vk::ImageLayout::eShaderReadOnlyOptimal);
src.SetMipMapGenerated();
return true;
}
} // namespace impeller
| engine/impeller/renderer/backend/vulkan/blit_command_vk.cc/0 | {
"file_path": "engine/impeller/renderer/backend/vulkan/blit_command_vk.cc",
"repo_id": "engine",
"token_count": 6643
} | 220 |
// 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.
#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_COMMAND_QUEUE_VK_H_
#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_COMMAND_QUEUE_VK_H_
#include "impeller/renderer/command_queue.h"
namespace impeller {
class ContextVK;
class CommandQueueVK : public CommandQueue {
public:
explicit CommandQueueVK(const std::weak_ptr<ContextVK>& context);
~CommandQueueVK() override;
fml::Status Submit(
const std::vector<std::shared_ptr<CommandBuffer>>& buffers,
const CompletionCallback& completion_callback = {}) override;
private:
std::weak_ptr<ContextVK> context_;
CommandQueueVK(const CommandQueueVK&) = delete;
CommandQueueVK& operator=(const CommandQueueVK&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_COMMAND_QUEUE_VK_H_
| engine/impeller/renderer/backend/vulkan/command_queue_vk.h/0 | {
"file_path": "engine/impeller/renderer/backend/vulkan/command_queue_vk.h",
"repo_id": "engine",
"token_count": 341
} | 221 |
// 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.
#include "impeller/renderer/backend/vulkan/driver_info_vk.h"
namespace impeller {
constexpr VendorVK IdentifyVendor(uint32_t vendor) {
// Check if the vendor has a PCI ID:
// https://pcisig.com/membership/member-companies
switch (vendor) {
case 0x1AE0:
return VendorVK::kGoogle;
case 0x168C:
case 0x17CB:
case 0x1969:
case 0x5143:
return VendorVK::kQualcomm;
case 0x13B5:
return VendorVK::kARM;
case 0x1010:
return VendorVK::kImgTec;
case 0x1002:
case 0x1022:
return VendorVK::kAMD;
case 0x10DE:
return VendorVK::kNvidia;
case 0x8086: // :)
return VendorVK::kIntel;
case 0x106B:
return VendorVK::kApple;
}
// Check if the ID is a known Khronos vendor.
switch (vendor) {
case VK_VENDOR_ID_MESA:
return VendorVK::kMesa;
// There are others but have never been observed. These can be added as
// needed.
}
return VendorVK::kUnknown;
}
constexpr DeviceTypeVK ToDeviceType(const vk::PhysicalDeviceType& type) {
switch (type) {
case vk::PhysicalDeviceType::eOther:
return DeviceTypeVK::kUnknown;
case vk::PhysicalDeviceType::eIntegratedGpu:
return DeviceTypeVK::kIntegratedGPU;
case vk::PhysicalDeviceType::eDiscreteGpu:
return DeviceTypeVK::kDiscreteGPU;
case vk::PhysicalDeviceType::eVirtualGpu:
return DeviceTypeVK::kVirtualGPU;
case vk::PhysicalDeviceType::eCpu:
return DeviceTypeVK::kCPU;
break;
}
return DeviceTypeVK::kUnknown;
}
DriverInfoVK::DriverInfoVK(const vk::PhysicalDevice& device) {
auto props = device.getProperties();
api_version_ = Version{VK_API_VERSION_MAJOR(props.apiVersion),
VK_API_VERSION_MINOR(props.apiVersion),
VK_API_VERSION_PATCH(props.apiVersion)};
vendor_ = IdentifyVendor(props.vendorID);
if (vendor_ == VendorVK::kUnknown) {
FML_LOG(WARNING) << "Unknown GPU Driver Vendor: " << props.vendorID
<< ". This is not an error.";
}
type_ = ToDeviceType(props.deviceType);
if (props.deviceName.data() != nullptr) {
driver_name_ = props.deviceName.data();
}
}
DriverInfoVK::~DriverInfoVK() = default;
const Version& DriverInfoVK::GetAPIVersion() const {
return api_version_;
}
const VendorVK& DriverInfoVK::GetVendor() const {
return vendor_;
}
const DeviceTypeVK& DriverInfoVK::GetDeviceType() const {
return type_;
}
const std::string& DriverInfoVK::GetDriverName() const {
return driver_name_;
}
} // namespace impeller
| engine/impeller/renderer/backend/vulkan/driver_info_vk.cc/0 | {
"file_path": "engine/impeller/renderer/backend/vulkan/driver_info_vk.cc",
"repo_id": "engine",
"token_count": 1078
} | 222 |
// 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.
#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_PIPELINE_VK_H_
#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_PIPELINE_VK_H_
#include <future>
#include <memory>
#include "impeller/base/backend_cast.h"
#include "impeller/base/thread.h"
#include "impeller/core/texture.h"
#include "impeller/renderer/backend/vulkan/device_holder_vk.h"
#include "impeller/renderer/backend/vulkan/formats_vk.h"
#include "impeller/renderer/backend/vulkan/pipeline_cache_vk.h"
#include "impeller/renderer/backend/vulkan/sampler_vk.h"
#include "impeller/renderer/backend/vulkan/vk.h"
#include "impeller/renderer/backend/vulkan/yuv_conversion_vk.h"
#include "impeller/renderer/pipeline.h"
namespace impeller {
// Limit on the total number of buffer and image bindings that allow the Vulkan
// backend to avoid dynamic heap allocations.
static constexpr size_t kMaxBindings = 32;
class PipelineVK final
: public Pipeline<PipelineDescriptor>,
public BackendCast<PipelineVK, Pipeline<PipelineDescriptor>> {
public:
static std::unique_ptr<PipelineVK> Create(
const PipelineDescriptor& desc,
const std::shared_ptr<DeviceHolderVK>& device_holder,
const std::weak_ptr<PipelineLibrary>& weak_library,
std::shared_ptr<SamplerVK> immutable_sampler = {});
// |Pipeline|
~PipelineVK() override;
vk::Pipeline GetPipeline() const;
const vk::PipelineLayout& GetPipelineLayout() const;
const vk::DescriptorSetLayout& GetDescriptorSetLayout() const;
std::shared_ptr<PipelineVK> CreateVariantForImmutableSamplers(
const std::shared_ptr<SamplerVK>& immutable_sampler) const;
private:
friend class PipelineLibraryVK;
using ImmutableSamplerVariants =
std::unordered_map<ImmutableSamplerKeyVK,
std::shared_ptr<PipelineVK>,
ComparableHash<ImmutableSamplerKeyVK>,
ComparableEqual<ImmutableSamplerKeyVK>>;
std::weak_ptr<DeviceHolderVK> device_holder_;
vk::UniquePipeline pipeline_;
vk::UniqueRenderPass render_pass_;
vk::UniquePipelineLayout layout_;
vk::UniqueDescriptorSetLayout descriptor_set_layout_;
std::shared_ptr<SamplerVK> immutable_sampler_;
mutable Mutex immutable_sampler_variants_mutex_;
mutable ImmutableSamplerVariants immutable_sampler_variants_ IPLR_GUARDED_BY(
immutable_sampler_variants_mutex_);
bool is_valid_ = false;
PipelineVK(std::weak_ptr<DeviceHolderVK> device_holder,
std::weak_ptr<PipelineLibrary> library,
const PipelineDescriptor& desc,
vk::UniquePipeline pipeline,
vk::UniqueRenderPass render_pass,
vk::UniquePipelineLayout layout,
vk::UniqueDescriptorSetLayout descriptor_set_layout,
std::shared_ptr<SamplerVK> immutable_sampler);
// |Pipeline|
bool IsValid() const override;
PipelineVK(const PipelineVK&) = delete;
PipelineVK& operator=(const PipelineVK&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_PIPELINE_VK_H_
| engine/impeller/renderer/backend/vulkan/pipeline_vk.h/0 | {
"file_path": "engine/impeller/renderer/backend/vulkan/pipeline_vk.h",
"repo_id": "engine",
"token_count": 1258
} | 223 |
// 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.
#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SHADER_FUNCTION_VK_H_
#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SHADER_FUNCTION_VK_H_
#include "flutter/fml/macros.h"
#include "impeller/base/backend_cast.h"
#include "impeller/renderer/backend/vulkan/device_holder_vk.h"
#include "impeller/renderer/backend/vulkan/shader_function_vk.h"
#include "impeller/renderer/backend/vulkan/vk.h"
#include "impeller/renderer/shader_function.h"
namespace impeller {
class ShaderFunctionVK final
: public ShaderFunction,
public BackendCast<ShaderFunctionVK, ShaderFunction> {
public:
// |ShaderFunction|
~ShaderFunctionVK() override;
const vk::ShaderModule& GetModule() const;
private:
friend class ShaderLibraryVK;
vk::UniqueShaderModule module_;
std::weak_ptr<DeviceHolderVK> device_holder_;
ShaderFunctionVK(const std::weak_ptr<DeviceHolderVK>& device_holder,
UniqueID parent_library_id,
std::string name,
ShaderStage stage,
vk::UniqueShaderModule module);
ShaderFunctionVK(const ShaderFunctionVK&) = delete;
ShaderFunctionVK& operator=(const ShaderFunctionVK&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SHADER_FUNCTION_VK_H_
| engine/impeller/renderer/backend/vulkan/shader_function_vk.h/0 | {
"file_path": "engine/impeller/renderer/backend/vulkan/shader_function_vk.h",
"repo_id": "engine",
"token_count": 580
} | 224 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.