text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
#!/bin/bash # Gather information from a core dump. # # This script can be invoked by the run_tests.py script after an # engine test crashes. BUILDROOT=$1 EXE=$2 CORE=$3 OUTPUT=$4 UNAME=$(uname) if [ "$UNAME" == "Linux" ]; then if [ -x "$(command -v gdb)" ]; then GDB=gdb else GDB=$BUILDROOT/third_party/android_tools/ndk/prebuilt/linux-x86_64/bin/gdb fi echo "GDB=$GDB" $GDB $EXE $CORE --batch -ex "thread apply all bt" > $OUTPUT fi
engine/testing/analyze_core_dump.sh/0
{ "file_path": "engine/testing/analyze_core_dump.sh", "repo_id": "engine", "token_count": 197 }
439
This is a Dart project that runs the engine benchmarks, and send the metrics to the cloud for storage and analysis.
engine/testing/benchmark/README.md/0
{ "file_path": "engine/testing/benchmark/README.md", "repo_id": "engine", "token_count": 25 }
440
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:typed_data'; import 'dart:ui'; import 'package:litetest/litetest.dart'; import 'impeller_enabled.dart'; const Color transparent = Color(0x00000000); const Color red = Color(0xFFAA0000); const Color green = Color(0xFF00AA00); const int greenRedColorBlend = 0xFF3131DB; const int greenRedColorBlendInverted = 0xFFCECE24; const int greenGreyscaled = 0xFF7A7A7A; const int greenInvertedGreyscaled = 0xFF858585; const int greenLinearToSrgbGamma = 0xFF00D500; const int greenLinearToSrgbGammaInverted = 0xFFFF2AFF; const int greenSrgbToLinearGamma = 0xFF006700; const int greenSrgbToLinearGammaInverted = 0xFFFF98FF; const List<double> greyscaleColorMatrix = <double>[ 0.2126, 0.7152, 0.0722, 0, 0, // 0.2126, 0.7152, 0.0722, 0, 0, // 0.2126, 0.7152, 0.0722, 0, 0, // 0, 0, 0, 1, 0, // ]; const List<double> identityColorMatrix = <double>[ 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, ]; void main() { Future<Uint32List> getBytesForPaint(Paint paint, {int width = 1, int height = 1}) async { final PictureRecorder recorder = PictureRecorder(); final Canvas recorderCanvas = Canvas(recorder); recorderCanvas.drawPaint(paint); final Picture picture = recorder.endRecording(); final Image image = await picture.toImage(width, height); final ByteData bytes = (await image.toByteData())!; expect(bytes.lengthInBytes, width * height * 4); return bytes.buffer.asUint32List(); } test('ColorFilter - mode', () async { final Paint paint = Paint() ..color = green ..colorFilter = const ColorFilter.mode(red, BlendMode.color); Uint32List bytes = await getBytesForPaint(paint); expect(bytes[0], greenRedColorBlend); // TODO(135699): enable this if (impellerEnabled) { return; } paint.invertColors = true; bytes = await getBytesForPaint(paint); expect(bytes[0], greenRedColorBlendInverted); }); test('ColorFilter - NOP mode does not crash', () async { final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); final Paint paint = Paint() ..color = green ..colorFilter = const ColorFilter.mode(transparent, BlendMode.srcOver); canvas.saveLayer(const Rect.fromLTRB(-100, -100, 200, 200), paint); canvas.drawRect(const Rect.fromLTRB(0, 0, 100, 100), Paint()); canvas.restore(); final Picture picture = recorder.endRecording(); final SceneBuilder builder = SceneBuilder(); builder.addPicture(Offset.zero, picture); final Scene scene = builder.build(); await scene.toImage(100, 100); }); test('ColorFilter - matrix', () async { final Paint paint = Paint() ..color = green ..colorFilter = const ColorFilter.matrix(greyscaleColorMatrix); Uint32List bytes = await getBytesForPaint(paint); expect(bytes[0], greenGreyscaled); // TODO(135699): enable this if (impellerEnabled) { return; } paint.invertColors = true; bytes = await getBytesForPaint(paint); expect(bytes[0], greenInvertedGreyscaled); }); test('ColorFilter - NOP matrix does not crash', () async { final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); final Paint paint = Paint() ..color = const Color(0xff00AA00) ..colorFilter = const ColorFilter.matrix(identityColorMatrix); canvas.saveLayer(const Rect.fromLTRB(-100, -100, 200, 200), paint); canvas.drawRect(const Rect.fromLTRB(0, 0, 100, 100), Paint()); canvas.restore(); final Picture picture = recorder.endRecording(); final SceneBuilder builder = SceneBuilder(); builder.addPicture(Offset.zero, picture); final Scene scene = builder.build(); await scene.toImage(100, 100); }); test('ColorFilter - linearToSrgbGamma', () async { final Paint paint = Paint() ..color = green ..colorFilter = const ColorFilter.linearToSrgbGamma(); Uint32List bytes = await getBytesForPaint(paint); expect(bytes[0], greenLinearToSrgbGamma); // TODO(135699): enable this if (impellerEnabled) { return; } paint.invertColors = true; bytes = await getBytesForPaint(paint); expect(bytes[0], greenLinearToSrgbGammaInverted); }); test('ColorFilter - srgbToLinearGamma', () async { final Paint paint = Paint() ..color = green ..colorFilter = const ColorFilter.srgbToLinearGamma(); Uint32List bytes = await getBytesForPaint(paint); expect(bytes[0], greenSrgbToLinearGamma); // TODO(135699): enable this if (impellerEnabled) { return; } paint.invertColors = true; bytes = await getBytesForPaint(paint); expect(bytes[0], greenSrgbToLinearGammaInverted); }); }
engine/testing/dart/color_filter_test.dart/0
{ "file_path": "engine/testing/dart/color_filter_test.dart", "repo_id": "engine", "token_count": 1835 }
441
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:typed_data'; import 'dart:ui'; import 'package:litetest/litetest.dart'; import 'impeller_enabled.dart'; const Color red = Color(0xFFAA0000); const Color green = Color(0xFF00AA00); const int greenCenterBlurred = 0x1C001300; const int greenSideBlurred = 0x15000E00; const int greenCornerBlurred = 0x10000A00; const int greenCenterScaled = 0xFF00AA00; const int greenSideScaled = 0x80005500; const int greenCornerScaled = 0x40002B00; const List<double> grayscaleColorMatrix = <double>[ 0.2126, 0.7152, 0.0722, 0, 0, 0.2126, 0.7152, 0.0722, 0, 0, 0.2126, 0.7152, 0.0722, 0, 0, 0, 0, 0, 1, 0, ]; const List<double> constValueColorMatrix = <double>[ 0, 0, 0, 0, 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 255, ]; const List<double> halvesBrightnessColorMatrix = <double>[ 0.5, 0, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 0, 1, 0, ]; void main() { Future<Uint32List> getBytesForPaint(Paint paint, {int width = 3, int height = 3}) async { final PictureRecorder recorder = PictureRecorder(); final Canvas recorderCanvas = Canvas(recorder); recorderCanvas.drawRect(const Rect.fromLTRB(1.0, 1.0, 2.0, 2.0), paint); final Picture picture = recorder.endRecording(); final Image image = await picture.toImage(width, height); final ByteData bytes = (await image.toByteData())!; expect(bytes.lengthInBytes, equals(width * height * 4)); return bytes.buffer.asUint32List(); } Future<Uint32List> getBytesForColorPaint(Paint paint, {int width = 1, int height = 1}) async { final PictureRecorder recorder = PictureRecorder(); final Canvas recorderCanvas = Canvas(recorder); recorderCanvas.drawPaint(paint); final Picture picture = recorder.endRecording(); final Image image = await picture.toImage(width, height); final ByteData bytes = (await image.toByteData())!; expect(bytes.lengthInBytes, width * height * 4); return bytes.buffer.asUint32List(); } ImageFilter makeBlur(double sigmaX, double sigmaY, [TileMode tileMode = TileMode.clamp]) => ImageFilter.blur(sigmaX: sigmaX, sigmaY: sigmaY, tileMode: tileMode); ImageFilter makeDilate(double radiusX, double radiusY) => ImageFilter.dilate(radiusX: radiusX, radiusY: radiusY); ImageFilter makeErode(double radiusX, double radiusY) => ImageFilter.erode(radiusX: radiusX, radiusY: radiusY); ImageFilter makeScale(double scX, double scY, [double trX = 0.0, double trY = 0.0, FilterQuality quality = FilterQuality.low]) { trX *= 1.0 - scX; trY *= 1.0 - scY; return ImageFilter.matrix(Float64List.fromList(<double>[ scX, 0.0, 0.0, 0.0, 0.0, scY, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, trX, trY, 0.0, 1.0, ]), filterQuality: quality); } List<ColorFilter> colorFilters() { // Create new color filter instances on each invocation. return <ColorFilter> [ // ignore: prefer_const_constructors ColorFilter.mode(green, BlendMode.color), // ignore: prefer_const_constructors ColorFilter.mode(red, BlendMode.color), // ignore: prefer_const_constructors ColorFilter.mode(red, BlendMode.screen), // ignore: prefer_const_constructors ColorFilter.matrix(grayscaleColorMatrix), // ignore: prefer_const_constructors ColorFilter.linearToSrgbGamma(), // ignore: prefer_const_constructors ColorFilter.srgbToLinearGamma(), // ignore: prefer_const_constructors ]; } List<ImageFilter> makeList() { return <ImageFilter>[ makeBlur(10.0, 10.0), makeBlur(10.0, 10.0, TileMode.decal), makeBlur(10.0, 20.0), makeBlur(20.0, 20.0), makeDilate(10.0, 20.0), makeDilate(20.0, 20.0), makeDilate(20.0, 10.0), makeErode(10.0, 20.0), makeErode(20.0, 20.0), makeErode(20.0, 10.0), makeScale(10.0, 10.0), makeScale(10.0, 20.0), makeScale(20.0, 10.0), makeScale(10.0, 10.0, 1.0, 1.0), makeScale(10.0, 10.0, 0.0, 0.0, FilterQuality.medium), makeScale(10.0, 10.0, 0.0, 0.0, FilterQuality.high), makeScale(10.0, 10.0, 0.0, 0.0, FilterQuality.none), ...colorFilters(), ]; } void checkEquality(List<ImageFilter> a, List<ImageFilter> b) { for (int i = 0; i < a.length; i++) { for(int j = 0; j < a.length; j++) { if (i == j) { expect(a[i], equals(b[j])); expect(a[i].hashCode, equals(b[j].hashCode)); expect(a[i].toString(), equals(b[j].toString())); } else { expect(a[i], notEquals(b[j])); // No expectations on hashCode if objects are not equal expect(a[i].toString(), notEquals(b[j].toString())); } } } } List<ImageFilter> composed(List<ImageFilter> a, List<ImageFilter> b) { return <ImageFilter>[for (final ImageFilter x in a) for (final ImageFilter y in b) ImageFilter.compose(outer: x, inner: y)]; } test('ImageFilter - equals', () async { final List<ImageFilter> A = makeList(); final List<ImageFilter> B = makeList(); checkEquality(A, A); checkEquality(A, B); checkEquality(B, B); checkEquality(composed(A, A), composed(A, A)); checkEquality(composed(A, B), composed(B, A)); checkEquality(composed(B, B), composed(B, B)); }); void checkBytes(Uint32List bytes, int center, int side, int corner) { expect(bytes[0], equals(corner)); expect(bytes[1], equals(side)); expect(bytes[2], equals(corner)); expect(bytes[3], equals(side)); expect(bytes[4], equals(center)); expect(bytes[5], equals(side)); expect(bytes[6], equals(corner)); expect(bytes[7], equals(side)); expect(bytes[8], equals(corner)); } test('ImageFilter - blur', () async { if (impellerEnabled) { print('Disabled - see https://github.com/flutter/flutter/issues/135712'); return; } final Paint paint = Paint() ..color = green ..imageFilter = makeBlur(1.0, 1.0, TileMode.decal); final Uint32List bytes = await getBytesForPaint(paint); checkBytes(bytes, greenCenterBlurred, greenSideBlurred, greenCornerBlurred); }); test('ImageFilter - dilate', () async { final Paint paint = Paint() ..color = green ..imageFilter = makeDilate(1.0, 1.0); final Uint32List bytes = await getBytesForPaint(paint); checkBytes(bytes, green.value, green.value, green.value); }); test('ImageFilter - erode', () async { final Paint paint = Paint() ..color = green ..imageFilter = makeErode(1.0, 1.0); final Uint32List bytes = await getBytesForPaint(paint); checkBytes(bytes, 0, 0, 0); }); test('ImageFilter - matrix', () async { if (impellerEnabled) { print('Disabled - see https://github.com/flutter/flutter/issues/135712'); return; } final Paint paint = Paint() ..color = green ..imageFilter = makeScale(2.0, 2.0, 1.5, 1.5); final Uint32List bytes = await getBytesForPaint(paint); checkBytes(bytes, greenCenterScaled, greenSideScaled, greenCornerScaled); }); test('ImageFilter - matrix: copies the list', () async { final Float64List matrix = Float64List.fromList(<double>[ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, ]); final ImageFilter filter = ImageFilter.matrix(matrix); final String originalDescription = filter.toString(); // Modify the matrix. matrix[0] = 12345; expect(filter.toString(), contains('[1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0]')); expect(filter.toString(), originalDescription); }); test('ImageFilter - from color filters', () async { if (impellerEnabled) { print('Disabled - see https://github.com/flutter/flutter/issues/135712'); return; } final Paint paint = Paint() ..color = green ..imageFilter = const ColorFilter.matrix(constValueColorMatrix); final Uint32List bytes = await getBytesForColorPaint(paint); expect(bytes[0], 0xFF020202); }); test('ImageFilter - color filter composition', () async { if (impellerEnabled) { print('Disabled - see https://github.com/flutter/flutter/issues/135712'); return; } final ImageFilter compOrder1 = ImageFilter.compose( outer: const ColorFilter.matrix(halvesBrightnessColorMatrix), inner: const ColorFilter.matrix(constValueColorMatrix), ); final ImageFilter compOrder2 = ImageFilter.compose( outer: const ColorFilter.matrix(constValueColorMatrix), inner: const ColorFilter.matrix(halvesBrightnessColorMatrix), ); final Paint paint = Paint() ..color = green ..imageFilter = compOrder1; Uint32List bytes = await getBytesForColorPaint(paint); expect(bytes[0], 0xFF010101); paint ..color = green ..imageFilter = compOrder2; bytes = await getBytesForColorPaint(paint); expect(bytes[0], 0xFF020202); }); test('Composite ImageFilter toString', () { expect( ImageFilter.compose(outer: makeBlur(20.0, 20.0, TileMode.decal), inner: makeBlur(10.0, 10.0)).toString(), contains('blur(10.0, 10.0, clamp) -> blur(20.0, 20.0, decal)'), ); // Produces a flat list of filters expect( ImageFilter.compose( outer: ImageFilter.compose(outer: makeBlur(30.0, 30.0, TileMode.mirror), inner: makeBlur(20.0, 20.0, TileMode.repeated)), inner: ImageFilter.compose( outer: const ColorFilter.mode(Color(0xFFABCDEF), BlendMode.color), inner: makeScale(10.0, 10.0), ), ).toString(), contains( 'matrix([10.0, 0.0, 0.0, 0.0, 0.0, 10.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, -0.0, -0.0, 0.0, 1.0], FilterQuality.low) -> ' 'ColorFilter.mode(Color(0xffabcdef), BlendMode.color) -> ' 'blur(20.0, 20.0, repeated) -> ' 'blur(30.0, 30.0, mirror)' ), ); }); }
engine/testing/dart/image_filter_test.dart/0
{ "file_path": "engine/testing/dart/image_filter_test.dart", "repo_id": "engine", "token_count": 4288 }
442
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:typed_data'; import 'dart:ui'; import 'package:litetest/litetest.dart'; typedef CanvasCallback = void Function(Canvas canvas); void main() { test('Vertices checks', () { try { Vertices( VertexMode.triangles, const <Offset>[Offset.zero, Offset.zero, Offset.zero], indices: Uint16List.fromList(const <int>[0, 2, 5]), ); throw 'Vertices did not throw the expected error.'; } on ArgumentError catch (e) { expect('$e', 'Invalid argument(s): "indices" values must be valid indices in the positions list (i.e. numbers in the range 0..2), but indices[2] is 5, which is too big.'); } Vertices( // This one does not throw. VertexMode.triangles, const <Offset>[Offset.zero], ).dispose(); Vertices( // This one should not throw. VertexMode.triangles, const <Offset>[Offset.zero, Offset.zero, Offset.zero], indices: Uint16List.fromList(const <int>[0, 2, 1, 2, 0, 1, 2, 0]), // Uint16List implements List<int> so this is ok. ).dispose(); }); test('Vertices.raw checks', () { try { Vertices.raw( VertexMode.triangles, Float32List.fromList(const <double>[0.0]), ); throw 'Vertices.raw did not throw the expected error.'; } on ArgumentError catch (e) { expect('$e', 'Invalid argument(s): "positions" must have an even number of entries (each coordinate is an x,y pair).'); } try { Vertices.raw( VertexMode.triangles, Float32List.fromList(const <double>[0.0, 0.0, 0.0, 0.0, 0.0, 0.0]), indices: Uint16List.fromList(const <int>[0, 2, 5]), ); throw 'Vertices.raw did not throw the expected error.'; } on ArgumentError catch (e) { expect('$e', 'Invalid argument(s): "indices" values must be valid indices in the positions list (i.e. numbers in the range 0..2), but indices[2] is 5, which is too big.'); } Vertices.raw( // This one does not throw. VertexMode.triangles, Float32List.fromList(const <double>[0.0, 0.0]), ).dispose(); Vertices.raw( // This one should not throw. VertexMode.triangles, Float32List.fromList(const <double>[0.0, 0.0, 0.0, 0.0, 0.0, 0.0]), indices: Uint16List.fromList(const <int>[0, 2, 1, 2, 0, 1, 2, 0]), ).dispose(); }); test('BackdropFilter with multiple clips', () async { // Regression test for https://github.com/flutter/flutter/issues/144211 Picture makePicture(CanvasCallback callback) { final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); callback(canvas); return recorder.endRecording(); } final SceneBuilder sceneBuilder = SceneBuilder(); final Picture redClippedPicture = makePicture((Canvas canvas) { canvas.clipRect(const Rect.fromLTRB(10, 10, 200, 200)); canvas.clipRect(const Rect.fromLTRB(11, 10, 300, 200)); canvas.drawPaint(Paint()..color = const Color(0xFFFF0000)); }); sceneBuilder.addPicture(Offset.zero, redClippedPicture); final Float64List matrix = Float64List(16); sceneBuilder.pushBackdropFilter(ImageFilter.matrix(matrix)); final Picture whitePicture = makePicture((Canvas canvas) { canvas.drawPaint(Paint()..color = const Color(0xFFFFFFFF)); }); sceneBuilder.addPicture(Offset.zero, whitePicture); final Scene scene = sceneBuilder.build(); final Image image = scene.toImageSync(20, 20); final ByteData data = (await image.toByteData())!; expect(data.buffer.asUint32List().length, 20 * 20); // If clipping went wrong as in the linked issue, there will be red pixels. for (final int color in data.buffer.asUint32List()) { expect(color, 0xFFFFFFFF); } scene.dispose(); image.dispose(); whitePicture.dispose(); redClippedPicture.dispose(); }); }
engine/testing/dart/painting_test.dart/0
{ "file_path": "engine/testing/dart/painting_test.dart", "repo_id": "engine", "token_count": 1526 }
443
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:typed_data'; import 'dart:ui'; import 'package:litetest/litetest.dart'; final Uint8List imageData = Uint8List.fromList(<int>[ // Small WebP file 0x52, 0x49, 0x46, 0x46, 0x12, 0x00, 0x00, 0x00, 0x57, 0x45, 0x42, 0x50, 0x56, 0x50, 0x38, 0x4c, // |RIFF....WEBPVP8L| 0x06, 0x00, 0x00, 0x00, 0x2f, 0x41, 0x6c, 0x6f, 0x00, 0x6b, // |..../Alo.k| ]); void main() { test('Stringification of native objects exposed in Dart', () async { expect(SemanticsUpdateBuilder().toString(), 'SemanticsUpdateBuilder'); expect(SemanticsUpdateBuilder().build().toString(), 'SemanticsUpdate'); expect(ParagraphBuilder(ParagraphStyle()).toString(), 'ParagraphBuilder'); expect(ParagraphBuilder(ParagraphStyle()).build().toString(), 'Paragraph(dirty)'); expect((await instantiateImageCodec(imageData)).toString(), 'Codec()'); expect(Path().toString(), 'Path'); final PictureRecorder recorder = PictureRecorder(); expect(recorder.toString(), 'PictureRecorder(recording: false)'); final Canvas canvas = Canvas(recorder); expect(recorder.toString(), 'PictureRecorder(recording: true)'); expect(canvas.toString(), 'Canvas(recording: true)'); final Picture picture = recorder.endRecording(); expect(recorder.toString(), 'PictureRecorder(recording: false)'); expect(canvas.toString(), 'Canvas(recording: false)'); expect(picture.toString(), 'Picture'); expect( ImageDescriptor.raw( await ImmutableBuffer.fromUint8List(Uint8List.fromList(<int>[0, 0, 0, 0])), width: 1, height: 1, pixelFormat: PixelFormat.rgba8888, ).toString(), 'ImageDescriptor(width: 1, height: 1, bytes per pixel: 4)', ); expect(SceneBuilder().toString(), 'SceneBuilder'); expect(SceneBuilder().build().toString(), 'Scene'); }); }
engine/testing/dart/stringification_test.dart/0
{ "file_path": "engine/testing/dart/stringification_test.dart", "repo_id": "engine", "token_count": 774 }
444
{ include: [ "sys/component/realm_builder_absolute.shard.cml", ], facets: { // shell_unittests and embedder_unittests require vulkan to function. "fuchsia.test": { type: "vulkan" }, }, program: { // TODO(fxbug.dev/80338): Switch to gtest_runner after the filters in // `gtest_filters.yaml` are supported by `--test-filter` and // deprecated-ambient-replace-as-executable is available. // Equivalent to the "deprecated-ambient-replace-as-executable" sandbox // feature in cfv1. runner: "elf_test_ambient_exec_runner", binary: "bin/app", // Part of //sdk/lib/diagnostics/syslog/elf_stdio.shard.cml. forward_stderr_to: "log", forward_stdout_to: "log", }, capabilities: [ { protocol: "fuchsia.test.Suite" }, ], expose: [ { protocol: "fuchsia.test.Suite", from: "self", }, ], use: [ { protocol: [ "fuchsia.logger.LogSink", "fuchsia.process.Launcher", "fuchsia.tracing.provider.Registry", "fuchsia.vulkan.loader.Loader", ], }, { storage: "tmp", path: "/tmp", }, ], }
engine/testing/fuchsia/meta/test_suite.cml/0
{ "file_path": "engine/testing/fuchsia/meta/test_suite.cml", "repo_id": "engine", "token_count": 677 }
445
// 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 "AppDelegate.h" @interface AppDelegate () @end @implementation AppDelegate - (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions { return YES; } - (void)applicationWillResignActive:(UIApplication*)application { } - (void)applicationDidEnterBackground:(UIApplication*)application { } - (void)applicationWillEnterForeground:(UIApplication*)application { } - (void)applicationDidBecomeActive:(UIApplication*)application { } - (void)applicationWillTerminate:(UIApplication*)application { } @end
engine/testing/ios/IosUnitTests/App/AppDelegate.m/0
{ "file_path": "engine/testing/ios/IosUnitTests/App/AppDelegate.m", "repo_id": "engine", "token_count": 219 }
446
# package:litetest This is a wrapper around `package:async_helper` from the Dart SDK source repo at `//pkg/async_helper` that works in the environment of `flutter_tester`. This wrapper is needed to ensure that all tests run to completion before the process exits. This is accomplished by opening a `ReceivePort` for each test, which is only closed when the test finishes running. ## Limitations This package is intended only for use in the `flutter/engine` repo by unit tests that run on `flutter_tester`. Even though the API resembles the API provided by `package:test`, it has all the same limitations that `package:async_helper` has.
engine/testing/litetest/README.md/0
{ "file_path": "engine/testing/litetest/README.md", "repo_id": "engine", "token_count": 170 }
447
TESTING_DIRECTORY=$(cd $(dirname "${BASH_SOURCE[0]}"); pwd -P) ENGINE_BUILDROOT=$(cd $TESTING_DIRECTORY/../..; pwd -P) case "$(uname -s)" in Linux) BUILDTOOLS_DIRECTORY="${ENGINE_BUILDROOT}/buildtools/linux-x64" ;; Darwin) BUILDTOOLS_DIRECTORY="${ENGINE_BUILDROOT}/buildtools/mac-x64" ;; esac TSAN_SUPPRESSIONS_FILE="${TESTING_DIRECTORY}/tsan_suppressions.txt" export TSAN_OPTIONS="suppressions=${TSAN_SUPPRESSIONS_FILE}" echo "Using Thread Sanitizer suppressions in ${TSAN_SUPPRESSIONS_FILE}" LSAN_SUPPRESSIONS_FILE="${TESTING_DIRECTORY}/lsan_suppressions.txt" export LSAN_OPTIONS="suppressions=${LSAN_SUPPRESSIONS_FILE}" echo "Using Leak Sanitizer suppressions in ${LSAN_SUPPRESSIONS_FILE}" UBSAN_SUPPRESSIONS_FILE="${TESTING_DIRECTORY}/ubsan_suppressions.txt" export UBSAN_OPTIONS="suppressions=${UBSAN_SUPPRESSIONS_FILE}" echo "Using Undefined Behavior suppressions in ${UBSAN_SUPPRESSIONS_FILE}" export ASAN_OPTIONS="symbolize=1:detect_leaks=1:intercept_tls_get_addr=0" export ASAN_SYMBOLIZER_PATH="${BUILDTOOLS_DIRECTORY}/clang/bin/llvm-symbolizer"
engine/testing/sanitizer_suppressions.sh/0
{ "file_path": "engine/testing/sanitizer_suppressions.sh", "repo_id": "engine", "token_count": 455 }
448
// 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. package dev.flutter.scenariosui; import android.content.Intent; import androidx.annotation.NonNull; import androidx.test.filters.LargeTest; import androidx.test.rule.ActivityTestRule; import androidx.test.runner.AndroidJUnit4; import dev.flutter.scenarios.PlatformViewsActivity; import leakcanary.FailTestOnLeak; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(AndroidJUnit4.class) @LargeTest public class MemoryLeakTests { @Rule @NonNull public ActivityTestRule<PlatformViewsActivity> activityRule = new ActivityTestRule<>( PlatformViewsActivity.class, /*initialTouchMode=*/ false, /*launchActivity=*/ false); @Test @FailTestOnLeak public void platformViewHybridComposition_launchActivityFinishAndLaunchAgain() throws Exception { Intent intent = new Intent(Intent.ACTION_MAIN); intent.putExtra("scenario_name", "platform_view"); intent.putExtra("use_android_view", true); intent.putExtra("view_type", PlatformViewsActivity.TEXT_VIEW_PV); activityRule.launchActivity(intent); } }
engine/testing/scenario_app/android/app/src/androidTest/java/dev/flutter/scenariosui/MemoryLeakTests.java/0
{ "file_path": "engine/testing/scenario_app/android/app/src/androidTest/java/dev/flutter/scenariosui/MemoryLeakTests.java", "repo_id": "engine", "token_count": 394 }
449
// 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. package dev.flutter.scenarios; import android.content.Context; import androidx.annotation.NonNull; import io.flutter.embedding.engine.FlutterEngine; import io.flutter.embedding.engine.FlutterEngineGroup; public class SpawnMultiEngineActivity extends TestActivity { static final String TAG = "Scenarios"; @Override @NonNull public FlutterEngine provideFlutterEngine(@NonNull Context context) { FlutterEngineGroup engineGroup = new FlutterEngineGroup(context); FlutterEngineGroup.Options options = new FlutterEngineGroup.Options(context).setAutomaticallyRegisterPlugins(false); FlutterEngine firstEngine = engineGroup.createAndRunEngine(options); FlutterEngine secondEngine = engineGroup.createAndRunEngine(options); // Check that a new engine can be spawned from the group even if the group's // original engine has been destroyed. firstEngine.destroy(); FlutterEngine thirdEngine = engineGroup.createAndRunEngine(options); return thirdEngine; } }
engine/testing/scenario_app/android/app/src/main/java/dev/flutter/scenarios/SpawnMultiEngineActivity.java/0
{ "file_path": "engine/testing/scenario_app/android/app/src/main/java/dev/flutter/scenarios/SpawnMultiEngineActivity.java", "repo_id": "engine", "token_count": 329 }
450
include ':app'
engine/testing/scenario_app/android/settings.gradle/0
{ "file_path": "engine/testing/scenario_app/android/settings.gradle", "repo_id": "engine", "token_count": 6 }
451
// 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 "AppDelegate.h" @interface AppDelegate () @end @implementation AppDelegate - (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions { // Override point for customization after application launch. return YES; } #pragma mark - UISceneSession lifecycle - (UISceneConfiguration*)application:(UIApplication*)application configurationForConnectingSceneSession:(UISceneSession*)connectingSceneSession options:(UISceneConnectionOptions*)options { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return [[UISceneConfiguration alloc] initWithName:@"Default Configuration" sessionRole:connectingSceneSession.role]; } - (void)application:(UIApplication*)application didDiscardSceneSessions:(NSSet<UISceneSession*>*)sceneSessions { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called // shortly after application:didFinishLaunchingWithOptions. Use this method to release any // resources that were specific to the discarded scenes, as they will not return. } @end
engine/testing/scenario_app/ios/FlutterAppExtensionTestHost/FlutterAppExtensionTestHost/AppDelegate.m/0
{ "file_path": "engine/testing/scenario_app/ios/FlutterAppExtensionTestHost/FlutterAppExtensionTestHost/AppDelegate.m", "repo_id": "engine", "token_count": 443 }
452
<?xml version="1.0" encoding="UTF-8"?> <Workspace version = "1.0"> <FileRef location = "container:Scenarios/Scenarios.xcodeproj"> </FileRef> </Workspace>
engine/testing/scenario_app/ios/Scenarios.xcworkspace/contents.xcworkspacedata/0
{ "file_path": "engine/testing/scenario_app/ios/Scenarios.xcworkspace/contents.xcworkspacedata", "repo_id": "engine", "token_count": 73 }
453
// 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 "FlutterEngine+ScenariosTest.h" @implementation FlutterEngine (ScenariosTest) - (instancetype)initWithScenario:(NSString*)scenario withCompletion:(nullable void (^)(void))engineRunCompletion { NSAssert([scenario length] != 0, @"You need to provide a scenario"); self = [self initWithName:[NSString stringWithFormat:@"Test engine for %@", scenario] project:nil]; [self run]; [self.binaryMessenger setMessageHandlerOnChannel:@"waiting_for_status" binaryMessageHandler:^(NSData* message, FlutterBinaryReply reply) { FlutterMethodChannel* channel = [FlutterMethodChannel methodChannelWithName:@"driver" binaryMessenger:self.binaryMessenger codec:[FlutterJSONMethodCodec sharedInstance]]; [channel invokeMethod:@"set_scenario" arguments:@{@"name" : scenario}]; if (engineRunCompletion != nil) { engineRunCompletion(); } }]; return self; } @end
engine/testing/scenario_app/ios/Scenarios/Scenarios/FlutterEngine+ScenariosTest.m/0
{ "file_path": "engine/testing/scenario_app/ios/Scenarios/Scenarios/FlutterEngine+ScenariosTest.m", "repo_id": "engine", "token_count": 736 }
454
// Copyright 2020 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/Flutter.h> #import <XCTest/XCTest.h> @interface RenderingSelectionTest : XCTestCase @property(nonatomic, strong) XCUIApplication* application; @end @implementation RenderingSelectionTest - (void)setUp { [super setUp]; self.continueAfterFailure = NO; self.application = [[XCUIApplication alloc] init]; } - (void)testSoftwareRendering { self.application.launchArguments = @[ @"--animated-color-square", @"--assert-ca-layer-type", @"--enable-software-rendering" ]; [self.application launch]; // App asserts that the rendering API is CALayer } - (void)testMetalRendering { self.application.launchArguments = @[ @"--animated-color-square", @"--assert-ca-layer-type" ]; [self.application launch]; // App asserts that the rendering API is CAMetalLayer } @end
engine/testing/scenario_app/ios/Scenarios/ScenariosUITests/RenderingSelectionTest.m/0
{ "file_path": "engine/testing/scenario_app/ios/Scenarios/ScenariosUITests/RenderingSelectionTest.m", "repo_id": "engine", "token_count": 313 }
455
// Copyright 2020 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 <XCTest/XCTest.h> static const NSInteger kSecondsToWaitForFlutterView = 30; @interface iPadGestureTests : XCTestCase @end @implementation iPadGestureTests - (void)setUp { [super setUp]; self.continueAfterFailure = NO; } static BOOL performBoolSelector(id target, SEL selector) { NSInvocation* invocation = [NSInvocation invocationWithMethodSignature:[[target class] instanceMethodSignatureForSelector:selector]]; [invocation setSelector:selector]; [invocation setTarget:target]; [invocation invoke]; BOOL returnValue; [invocation getReturnValue:&returnValue]; return returnValue; } static int assertOneMessageAndGetSequenceNumber(NSMutableDictionary* messages, NSString* message) { NSMutableArray<NSNumber*>* matchingMessages = messages[message]; XCTAssertNotNil(matchingMessages, @"Did not receive \"%@\" message", message); XCTAssertEqual(matchingMessages.count, 1, @"More than one \"%@\" message", message); return matchingMessages.firstObject.intValue; } // TODO(85810): Remove reflection in this test when Xcode version is upgraded to 13. #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wundeclared-selector" #pragma clang diagnostic ignored "-Warc-performSelector-leaks" - (void)testPointerButtons { BOOL supportsPointerInteraction = NO; SEL supportsPointerInteractionSelector = @selector(supportsPointerInteraction); if ([XCUIDevice.sharedDevice respondsToSelector:supportsPointerInteractionSelector]) { supportsPointerInteraction = performBoolSelector(XCUIDevice.sharedDevice, supportsPointerInteractionSelector); } XCTSkipUnless(supportsPointerInteraction, "Device does not support pointer interaction."); XCUIApplication* app = [[XCUIApplication alloc] init]; app.launchArguments = @[ @"--pointer-events" ]; [app launch]; NSPredicate* predicateToFindFlutterView = [NSPredicate predicateWithFormat:@"identifier BEGINSWITH 'flutter_view'"]; XCUIElement* flutterView = [[app descendantsMatchingType:XCUIElementTypeAny] elementMatchingPredicate:predicateToFindFlutterView]; if (![flutterView waitForExistenceWithTimeout:kSecondsToWaitForFlutterView]) { NSLog(@"%@", app.debugDescription); XCTFail(@"Failed due to not able to find any flutterView with %@ seconds", @(kSecondsToWaitForFlutterView)); } XCTAssertNotNil(flutterView); [flutterView tap]; // Initial add event should have buttons = 0 XCTAssertTrue( [app.textFields[@"0,PointerChange.add,device=0,buttons=0"] waitForExistenceWithTimeout:1], @"PointerChange.add event did not occur for a normal tap"); // Normal tap should have buttons = 0, the flutter framework will ensure it has buttons = 1 XCTAssertTrue( [app.textFields[@"1,PointerChange.down,device=0,buttons=0"] waitForExistenceWithTimeout:1], @"PointerChange.down event did not occur for a normal tap"); XCTAssertTrue( [app.textFields[@"2,PointerChange.up,device=0,buttons=0"] waitForExistenceWithTimeout:1], @"PointerChange.up event did not occur for a normal tap"); XCTAssertTrue( [app.textFields[@"3,PointerChange.remove,device=0,buttons=0"] waitForExistenceWithTimeout:1], @"PointerChange.remove event did not occur for a normal tap"); SEL rightClick = @selector(rightClick); XCTAssertTrue([flutterView respondsToSelector:rightClick], @"If supportsPointerInteraction is true, this should be true too."); [flutterView performSelector:rightClick]; // On simulated right click, a hover also occurs, so the hover pointer is added XCTAssertTrue( [app.textFields[@"4,PointerChange.add,device=1,buttons=0"] waitForExistenceWithTimeout:1], @"PointerChange.add event did not occur for a right-click's hover pointer"); // The hover pointer is removed after ~3.5 seconds, this ensures that all events are received XCTestExpectation* sleepExpectation = [self expectationWithDescription:@"never fires"]; sleepExpectation.inverted = true; [self waitForExpectations:@[ sleepExpectation ] timeout:5.0]; // The hover events are interspersed with the right-click events in a varying order. // Ensure the individual orderings are respected without hardcoding the absolute sequence. NSMutableDictionary<NSString*, NSMutableArray<NSNumber*>*>* messages = [[NSMutableDictionary alloc] init]; for (XCUIElement* element in [app.textFields allElementsBoundByIndex]) { NSString* rawMessage = element.value; // Parse out the sequence number NSUInteger commaIndex = [rawMessage rangeOfString:@","].location; NSInteger messageSequenceNumber = [rawMessage substringWithRange:NSMakeRange(0, commaIndex)].integerValue; // Parse out the rest of the message NSString* message = [rawMessage substringWithRange:NSMakeRange(commaIndex + 1, rawMessage.length - (commaIndex + 1))]; NSMutableArray<NSNumber*>* messageSequenceNumberList = messages[message]; if (messageSequenceNumberList == nil) { messageSequenceNumberList = [[NSMutableArray alloc] init]; messages[message] = messageSequenceNumberList; } [messageSequenceNumberList addObject:@(messageSequenceNumber)]; } // The number of hover events is not consistent, there could be one or many. NSMutableArray<NSNumber*>* hoverSequenceNumbers = messages[@"PointerChange.hover,device=1,buttons=0"]; int hoverRemovedSequenceNumber = assertOneMessageAndGetSequenceNumber(messages, @"PointerChange.remove,device=1,buttons=0"); // Right click should have buttons = 2 int rightClickAddedSequenceNumber; int rightClickDownSequenceNumber; int rightClickUpSequenceNumber; if (messages[@"PointerChange.add,device=2,buttons=0"] == nil) { // Sometimes the tap pointer has the same device as the right-click (the UITouch is reused) rightClickAddedSequenceNumber = 0; rightClickDownSequenceNumber = assertOneMessageAndGetSequenceNumber(messages, @"PointerChange.down,device=0,buttons=2"); rightClickUpSequenceNumber = assertOneMessageAndGetSequenceNumber(messages, @"PointerChange.up,device=0,buttons=2"); } else { rightClickAddedSequenceNumber = assertOneMessageAndGetSequenceNumber(messages, @"PointerChange.add,device=2,buttons=0"); rightClickDownSequenceNumber = assertOneMessageAndGetSequenceNumber(messages, @"PointerChange.down,device=2,buttons=2"); rightClickUpSequenceNumber = assertOneMessageAndGetSequenceNumber(messages, @"PointerChange.up,device=2,buttons=2"); } XCTAssertGreaterThan(rightClickDownSequenceNumber, rightClickAddedSequenceNumber, @"Right-click pointer was pressed before it was added"); XCTAssertGreaterThan(rightClickUpSequenceNumber, rightClickDownSequenceNumber, @"Right-click pointer was released before it was pressed"); XCTAssertGreaterThan([[hoverSequenceNumbers firstObject] intValue], 4, @"Hover occured before hover pointer was added"); XCTAssertGreaterThan(hoverRemovedSequenceNumber, [[hoverSequenceNumbers lastObject] intValue], @"Hover occured after hover pointer was removed"); } - (void)testPointerHover { BOOL supportsPointerInteraction = NO; SEL supportsPointerInteractionSelector = @selector(supportsPointerInteraction); if ([XCUIDevice.sharedDevice respondsToSelector:supportsPointerInteractionSelector]) { supportsPointerInteraction = performBoolSelector(XCUIDevice.sharedDevice, supportsPointerInteractionSelector); } XCTSkipUnless(supportsPointerInteraction, "Device does not support pointer interaction."); XCUIApplication* app = [[XCUIApplication alloc] init]; app.launchArguments = @[ @"--pointer-events" ]; [app launch]; NSPredicate* predicateToFindFlutterView = [NSPredicate predicateWithFormat:@"identifier BEGINSWITH 'flutter_view'"]; XCUIElement* flutterView = [[app descendantsMatchingType:XCUIElementTypeAny] elementMatchingPredicate:predicateToFindFlutterView]; if (![flutterView waitForExistenceWithTimeout:kSecondsToWaitForFlutterView]) { NSLog(@"%@", app.debugDescription); XCTFail(@"Failed due to not able to find any flutterView with %@ seconds", @(kSecondsToWaitForFlutterView)); } XCTAssertNotNil(flutterView); SEL hover = @selector(hover); XCTAssertTrue([flutterView respondsToSelector:hover], @"If supportsPointerInteraction is true, this should be true too."); [flutterView performSelector:hover]; XCTAssertTrue( [app.textFields[@"0,PointerChange.add,device=0,buttons=0"] waitForExistenceWithTimeout:1], @"PointerChange.add event did not occur for a hover"); XCTAssertTrue( [app.textFields[@"1,PointerChange.hover,device=0,buttons=0"] waitForExistenceWithTimeout:1], @"PointerChange.hover event did not occur for a hover"); // The number of hover events fired is not always the same NSInteger lastHoverSequenceNumber = -1; NSPredicate* predicateToFindHoverEvents = [NSPredicate predicateWithFormat:@"value ENDSWITH ',PointerChange.hover,device=0,buttons=0'"]; for (XCUIElement* textField in [[app.textFields matchingPredicate:predicateToFindHoverEvents] allElementsBoundByIndex]) { NSInteger messageSequenceNumber = [[textField.value componentsSeparatedByString:@","] firstObject].integerValue; if (messageSequenceNumber > lastHoverSequenceNumber) { lastHoverSequenceNumber = messageSequenceNumber; } } XCTAssertNotEqual(lastHoverSequenceNumber, -1, @"PointerChange.hover event did not occur for a hover"); NSString* removeMessage = [NSString stringWithFormat:@"%ld,PointerChange.remove,device=0,buttons=0", lastHoverSequenceNumber + 1]; XCTAssertTrue([app.textFields[removeMessage] waitForExistenceWithTimeout:1], @"PointerChange.remove event did not occur for a hover"); } - (void)testPointerScroll { BOOL supportsPointerInteraction = NO; SEL supportsPointerInteractionSelector = @selector(supportsPointerInteraction); if ([XCUIDevice.sharedDevice respondsToSelector:supportsPointerInteractionSelector]) { supportsPointerInteraction = performBoolSelector(XCUIDevice.sharedDevice, supportsPointerInteractionSelector); } XCTSkipUnless(supportsPointerInteraction, "Device does not support pointer interaction."); XCUIApplication* app = [[XCUIApplication alloc] init]; app.launchArguments = @[ @"--pointer-events" ]; [app launch]; NSPredicate* predicateToFindFlutterView = [NSPredicate predicateWithFormat:@"identifier BEGINSWITH 'flutter_view'"]; XCUIElement* flutterView = [[app descendantsMatchingType:XCUIElementTypeAny] elementMatchingPredicate:predicateToFindFlutterView]; if (![flutterView waitForExistenceWithTimeout:kSecondsToWaitForFlutterView]) { XCTFail(@"Failed due to not able to find any flutterView with %@ seconds", @(kSecondsToWaitForFlutterView)); } XCTAssertNotNil(flutterView); SEL scroll = @selector(scrollByDeltaX:deltaY:); XCTAssertTrue([flutterView respondsToSelector:scroll], @"If supportsPointerInteraction is true, this should be true too."); // Need to use NSInvocation in order to send primitive arguments to selector. NSInvocation* invocation = [NSInvocation invocationWithMethodSignature:[XCUIElement instanceMethodSignatureForSelector:scroll]]; [invocation setSelector:scroll]; CGFloat deltaX = 0.0; CGFloat deltaY = 1000.0; [invocation setArgument:&deltaX atIndex:2]; [invocation setArgument:&deltaY atIndex:3]; [invocation invokeWithTarget:flutterView]; // Hover immediately following the scroll to cause an inertia cancel event. SEL hover = @selector(hover:); XCTAssertTrue([flutterView respondsToSelector:hover], @"If supportsPointerInteraction is true, this should be true too."); [flutterView performSelector:hover]; // The hover pointer is observed to be removed by the system after ~3.5 seconds of inactivity. // While this is not a documented behavior, it is the only way to test for the removal of the // hover pointer. Waiting for 5 seconds will ensure that all events are received before // processing. XCTestExpectation* sleepExpectation = [self expectationWithDescription:@"never fires"]; sleepExpectation.inverted = true; [self waitForExpectations:@[ sleepExpectation ] timeout:5.0]; // There are hover events interspersed with the scroll events in a varying order. // Ensure the individual orderings are respected without hardcoding the absolute sequence. NSMutableDictionary<NSString*, NSMutableArray<NSNumber*>*>* messages = [[NSMutableDictionary alloc] init]; for (XCUIElement* element in [app.textFields allElementsBoundByIndex]) { NSString* rawMessage = element.value; // Parse out the sequence number NSUInteger commaIndex = [rawMessage rangeOfString:@","].location; NSInteger messageSequenceNumber = [rawMessage substringWithRange:NSMakeRange(0, commaIndex)].integerValue; // Parse out the rest of the message NSString* message = [rawMessage substringWithRange:NSMakeRange(commaIndex + 1, rawMessage.length - (commaIndex + 1))]; NSMutableArray<NSNumber*>* messageSequenceNumberList = messages[message]; if (messageSequenceNumberList == nil) { messageSequenceNumberList = [[NSMutableArray alloc] init]; messages[message] = messageSequenceNumberList; } [messageSequenceNumberList addObject:@(messageSequenceNumber)]; } // The number of hover events is not consistent, there could be one or many. int hoverAddedSequenceNumber = assertOneMessageAndGetSequenceNumber( messages, @"PointerChange.add,device=0,buttons=0,signalKind=PointerSignalKind.none"); NSMutableArray<NSNumber*>* hoverSequenceNumbers = messages[@"PointerChange.hover,device=0,buttons=0,signalKind=PointerSignalKind.none"]; int hoverRemovedSequenceNumber = assertOneMessageAndGetSequenceNumber( messages, @"PointerChange.remove,device=0,buttons=0,signalKind=PointerSignalKind.none"); int panZoomAddedSequenceNumber = assertOneMessageAndGetSequenceNumber( messages, @"PointerChange.add,device=1,buttons=0,signalKind=PointerSignalKind.none"); int panZoomStartSequenceNumber = assertOneMessageAndGetSequenceNumber( messages, @"PointerChange.panZoomStart,device=1,buttons=0,signalKind=PointerSignalKind.none"); // The number of pan/zoom update events is not consistent, there could be one or many. NSMutableArray<NSNumber*>* panZoomUpdateSequenceNumbers = messages[@"PointerChange.panZoomUpdate,device=1,buttons=0,signalKind=PointerSignalKind.none"]; int panZoomEndSequenceNumber = assertOneMessageAndGetSequenceNumber( messages, @"PointerChange.panZoomEnd,device=1,buttons=0,signalKind=PointerSignalKind.none"); int inertiaCancelSequenceNumber = assertOneMessageAndGetSequenceNumber( messages, @"PointerChange.cancel,device=2,buttons=0,signalKind=PointerSignalKind.scrollInertiaCancel"); XCTAssertGreaterThan(panZoomStartSequenceNumber, panZoomAddedSequenceNumber, @"PanZoomStart occured before pointer was added"); XCTAssertGreaterThan([[panZoomUpdateSequenceNumbers firstObject] intValue], panZoomStartSequenceNumber, @"PanZoomUpdate occured before PanZoomStart"); XCTAssertGreaterThan(panZoomEndSequenceNumber, [[panZoomUpdateSequenceNumbers lastObject] intValue], @"PanZoomUpdate occured after PanZoomEnd"); XCTAssertGreaterThan(inertiaCancelSequenceNumber, panZoomEndSequenceNumber, @"ScrollInertiaCancel occured before PanZoomEnd"); XCTAssertGreaterThan([[hoverSequenceNumbers firstObject] intValue], hoverAddedSequenceNumber, @"Hover occured before pointer was added"); XCTAssertGreaterThan(hoverRemovedSequenceNumber, [[hoverSequenceNumbers lastObject] intValue], @"Hover occured after pointer was removed"); } #pragma clang diagnostic pop @end
engine/testing/scenario_app/ios/Scenarios/ScenariosUITests/iPadGestureTests.m/0
{ "file_path": "engine/testing/scenario_app/ios/Scenarios/ScenariosUITests/iPadGestureTests.m", "repo_id": "engine", "token_count": 5561 }
456
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:ui'; import 'channel_util.dart'; import 'scenario.dart'; import 'scenarios.dart'; /// Displays a platform texture with the given width and height. class DisplayTexture extends Scenario { /// Creates the DisplayTexture scenario. DisplayTexture(super.view); int get _textureId => scenarioParams['texture_id'] as int; double get _textureWidth => (scenarioParams['texture_width'] as num).toDouble(); double get _textureHeight => (scenarioParams['texture_height'] as num).toDouble(); @override void onBeginFrame(Duration duration) { final SceneBuilder builder = SceneBuilder(); builder.addTexture( _textureId, offset: Offset( (view.physicalSize.width / 2.0) - (_textureWidth / 2.0), 0.0, ), width: _textureWidth, height: _textureHeight, ); final Scene scene = builder.build(); view.render(scene); scene.dispose(); sendJsonMessage( dispatcher: view.platformDispatcher, channel: 'display_data', json: <String, dynamic>{ 'data': 'ready', }, ); } }
engine/testing/scenario_app/lib/src/texture.dart/0
{ "file_path": "engine/testing/scenario_app/lib/src/texture.dart", "repo_id": "engine", "token_count": 449 }
457
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io'; import 'package:args/args.dart'; import 'package:engine_repo_tools/engine_repo_tools.dart'; import 'package:git_repo_tools/git_repo_tools.dart'; import 'package:path/path.dart' as path; /// Takes the images in `source_images`, writes text on them (i.e. git hash) /// and saves them in `e2e_fixtures`. By default, no arguments are needed but /// ImageMagick must be installed. void main(List<String> args) async { final Engine? engine = Engine.tryFindWithin(); final ArgParser parser = ArgParser() ..addFlag( 'help', abbr: 'h', help: 'Prints usage information.', negatable: false, ) ..addOption( 'image-magick-convert-bin', help: 'The path to the ImageMagick `convert` executable.', defaultsTo: 'convert', hide: true, ) ..addOption( 'annotation', abbr: 'a', help: 'The text to write on the images.', defaultsTo: engine == null ? null : await GitRepo.fromRoot(engine.flutterDir).headSha(short: true), ) ..addOption( 'source', abbr: 's', help: 'The directory containing the images to be modified.', defaultsTo: engine == null ? null : path.join( engine.flutterDir.path, 'testing', 'skia_gold_client', 'tool', 'source_images', ), ) ..addOption( 'output', abbr: 'o', help: 'The directory to save the modified images in.', defaultsTo: engine == null ? null : path.join( engine.flutterDir.path, 'testing', 'skia_gold_client', 'tool', 'e2e_fixtures', ), ); final ArgResults results = parser.parse(args); if (results['help'] as bool) { print(parser.usage); return; } final String relativeDir = engine?.flutterDir.path ?? ''; final String imageMagickConvertBin = results['image-magick-convert-bin'] as String; final String annotation = results['annotation'] as String; final String source = results['source'] as String; final String output = results['output'] as String; print( 'Writing annotation "$annotation" on images in ' '${path.relative(source, from: relativeDir)} and saving them in ' '${path.relative(output, from: relativeDir)}.', ); final List<String> sourceImages = Directory(source) .listSync() .whereType<File>() .map((File file) => file.path) .toList(); // For each source image, write the annotation and save it in the output directory. for (final String sourceImage in sourceImages) { final String outputImage = path.join( output, '${path.basenameWithoutExtension(sourceImage)}.png', ); print('Writing to ${path.relative(outputImage, from: relativeDir)}'); await Process.run( imageMagickConvertBin, <String>[ sourceImage, '-fill', 'white', '-undercolor', 'black', '-gravity', 'SouthEast', '-pointsize', '24', '-annotate', '+10+10', annotation, outputImage, ], ); } print('Done: wrote ${sourceImages.length} image.'); }
engine/testing/skia_gold_client/tool/generate.dart/0
{ "file_path": "engine/testing/skia_gold_client/tool/generate.dart", "repo_id": "engine", "token_count": 1434 }
458
// 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_TESTING_TEST_GL_SURFACE_H_ #define FLUTTER_TESTING_TEST_GL_SURFACE_H_ #include <cstdint> #include "flutter/fml/macros.h" #include "third_party/skia/include/core/SkSurface.h" #include "third_party/skia/include/gpu/GrDirectContext.h" namespace flutter { namespace testing { class TestGLSurface { public: explicit TestGLSurface(SkISize surface_size); ~TestGLSurface(); const SkISize& GetSurfaceSize() const; bool MakeCurrent(); bool ClearCurrent(); bool Present(); uint32_t GetFramebuffer(uint32_t width, uint32_t height) const; bool MakeResourceCurrent(); void* GetProcAddress(const char* name) const; sk_sp<SkSurface> GetOnscreenSurface(); sk_sp<GrDirectContext> GetGrContext(); sk_sp<GrDirectContext> CreateGrContext(); sk_sp<SkImage> GetRasterSurfaceSnapshot(); uint32_t GetWindowFBOId() const; private: // Importing the EGL.h pulls in platform headers which are problematic // (especially X11 which #defineds types like Bool). Any TUs importing // this header then become susceptible to failures because of platform // specific craziness. Don't expose EGL internals via this header. using EGLDisplay = void*; using EGLContext = void*; using EGLSurface = void*; const SkISize surface_size_; EGLDisplay display_; EGLContext onscreen_context_; EGLContext offscreen_context_; EGLSurface onscreen_surface_; EGLSurface offscreen_surface_; sk_sp<GrDirectContext> context_; FML_DISALLOW_COPY_AND_ASSIGN(TestGLSurface); }; } // namespace testing } // namespace flutter #endif // FLUTTER_TESTING_TEST_GL_SURFACE_H_
engine/testing/test_gl_surface.h/0
{ "file_path": "engine/testing/test_gl_surface.h", "repo_id": "engine", "token_count": 601 }
459
// 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 "testing.h" #include <utility> #include "flutter/fml/file.h" #include "flutter/fml/paths.h" namespace flutter { namespace testing { std::string GetCurrentTestName() { return ::testing::UnitTest::GetInstance()->current_test_info()->name(); } std::string GetDefaultKernelFilePath() { return fml::paths::JoinPaths({GetFixturesPath(), "kernel_blob.bin"}); } fml::UniqueFD OpenFixturesDirectory() { auto fixtures_directory = OpenDirectory(GetFixturesPath(), // path false, // create fml::FilePermission::kRead // permission ); if (!fixtures_directory.is_valid()) { FML_LOG(ERROR) << "Could not open fixtures directory."; return {}; } return fixtures_directory; } fml::UniqueFD OpenFixture(const std::string& fixture_name) { if (fixture_name.size() == 0) { FML_LOG(ERROR) << "Invalid fixture name."; return {}; } auto fixtures_directory = OpenFixturesDirectory(); auto fixture_fd = fml::OpenFile(fixtures_directory, // base directory fixture_name.c_str(), // path false, // create fml::FilePermission::kRead // permission ); if (!fixture_fd.is_valid()) { FML_LOG(ERROR) << "Could not open fixture for path: " << GetFixturesPath() << "/" << fixture_name << "."; return {}; } return fixture_fd; } std::unique_ptr<fml::Mapping> OpenFixtureAsMapping( const std::string& fixture_name) { return fml::FileMapping::CreateReadOnly(OpenFixture(fixture_name)); } sk_sp<SkData> OpenFixtureAsSkData(const std::string& fixture_name) { auto mapping = flutter::testing::OpenFixtureAsMapping(fixture_name); if (!mapping) { return nullptr; } auto data = SkData::MakeWithProc( mapping->GetMapping(), mapping->GetSize(), [](const void* ptr, void* context) { delete reinterpret_cast<fml::Mapping*>(context); }, mapping.get()); mapping.release(); return data; } bool MemsetPatternSetOrCheck(uint8_t* buffer, size_t size, MemsetPatternOp op) { if (buffer == nullptr) { return false; } auto pattern = reinterpret_cast<const uint8_t*>("dErP"); constexpr auto pattern_length = 4; uint8_t* start = buffer; uint8_t* p = buffer; while ((start + size) - p >= pattern_length) { switch (op) { case MemsetPatternOp::kMemsetPatternOpSetBuffer: memmove(p, pattern, pattern_length); break; case MemsetPatternOp::kMemsetPatternOpCheckBuffer: if (memcmp(pattern, p, pattern_length) != 0) { return false; } break; }; p += pattern_length; } if ((start + size) - p != 0) { switch (op) { case MemsetPatternOp::kMemsetPatternOpSetBuffer: memmove(p, pattern, (start + size) - p); break; case MemsetPatternOp::kMemsetPatternOpCheckBuffer: if (memcmp(pattern, p, (start + size) - p) != 0) { return false; } break; } } return true; } bool MemsetPatternSetOrCheck(std::vector<uint8_t>& buffer, MemsetPatternOp op) { return MemsetPatternSetOrCheck(buffer.data(), buffer.size(), op); } } // namespace testing } // namespace flutter
engine/testing/testing.cc/0
{ "file_path": "engine/testing/testing.cc", "repo_id": "engine", "token_count": 1441 }
460
// Copyright 2016 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. #ifndef UI_ACCESSIBILITY_AX_ACTION_DATA_H_ #define UI_ACCESSIBILITY_AX_ACTION_DATA_H_ #include "ax_enums.h" #include "ax_export.h" #include "ax_tree_id.h" #include "gfx/geometry/point.h" #include "gfx/geometry/rect.h" namespace ui { // A compact representation of an accessibility action and the arguments // associated with that action. struct AX_EXPORT AXActionData { AXActionData(); AXActionData(const AXActionData& other); ~AXActionData(); // This is a simple serializable struct. All member variables should be // public and copyable. // See the ax::mojom::Action enums in ax_enums.mojom for explanations of which // parameters apply. // The action to take. ax::mojom::Action action; // The ID of the tree that this action should be performed on. ui::AXTreeID target_tree_id = ui::AXTreeIDUnknown(); // The source extension id (if any) of this action. std::string source_extension_id; // The ID of the node that this action should be performed on. int target_node_id = -1; // The request id of this action tracked by the client. int request_id = -1; // Use enums from ax::mojom::ActionFlags int flags = 0; // For an action that creates a selection, the selection anchor and focus // (see ax_tree_data.h for definitions). int anchor_node_id = -1; int anchor_offset = -1; int focus_node_id = -1; int focus_offset = -1; // Start index of the text which should be queried for. int32_t start_index = -1; // End index of the text which should be queried for. int32_t end_index = -1; // For custom action. int custom_action_id = -1; // The target rect for the action. gfx::Rect target_rect; // The target point for the action. gfx::Point target_point; // The new value for a node, for the SET_VALUE action. UTF-8 encoded. std::string value; // The event to fire in response to a HIT_TEST action. ax::mojom::Event hit_test_event_to_fire; // The scroll alignment to use for a SCROLL_TO_MAKE_VISIBLE action. The // scroll alignment controls where a node is scrolled within the viewport. ax::mojom::ScrollAlignment horizontal_scroll_alignment; ax::mojom::ScrollAlignment vertical_scroll_alignment; // The behavior to use for a SCROLL_TO_MAKE_VISIBLE. This controls whether or // not the viewport is scrolled when the node is already visible. ax::mojom::ScrollBehavior scroll_behavior; }; } // namespace ui #endif // UI_ACCESSIBILITY_AX_ACTION_DATA_H_
engine/third_party/accessibility/ax/ax_action_data.h/0
{ "file_path": "engine/third_party/accessibility/ax/ax_action_data.h", "repo_id": "engine", "token_count": 842 }
461
// Copyright 2017 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. #ifndef UI_ACCESSIBILITY_AX_EVENT_GENERATOR_H_ #define UI_ACCESSIBILITY_AX_EVENT_GENERATOR_H_ #include <bitset> #include <map> #include <ostream> #include <set> #include <vector> #include "ax_event_intent.h" #include "ax_export.h" #include "ax_tree.h" #include "ax_tree_observer.h" namespace ui { // Subclass of AXTreeObserver that automatically generates AXEvents to fire // based on changes to an accessibility tree. Every platform // tends to want different events, so this class lets each platform // handle the events it wants and ignore the others. class AX_EXPORT AXEventGenerator : public AXTreeObserver { public: enum class Event : int32_t { ACCESS_KEY_CHANGED, ACTIVE_DESCENDANT_CHANGED, ALERT, // ATK treats alignment, indentation, and other format-related attributes as // text attributes even when they are only applicable to the entire object. // And it lacks an event for object attributes changing. ATK_TEXT_OBJECT_ATTRIBUTE_CHANGED, ATOMIC_CHANGED, AUTO_COMPLETE_CHANGED, BUSY_CHANGED, CHECKED_STATE_CHANGED, CHILDREN_CHANGED, CLASS_NAME_CHANGED, COLLAPSED, CONTROLS_CHANGED, DESCRIBED_BY_CHANGED, DESCRIPTION_CHANGED, DOCUMENT_SELECTION_CHANGED, DOCUMENT_TITLE_CHANGED, DROPEFFECT_CHANGED, ENABLED_CHANGED, EXPANDED, FOCUS_CHANGED, FLOW_FROM_CHANGED, FLOW_TO_CHANGED, GRABBED_CHANGED, HASPOPUP_CHANGED, HIERARCHICAL_LEVEL_CHANGED, IGNORED_CHANGED, IMAGE_ANNOTATION_CHANGED, INVALID_STATUS_CHANGED, KEY_SHORTCUTS_CHANGED, LABELED_BY_CHANGED, LANGUAGE_CHANGED, LAYOUT_INVALIDATED, // Fired when aria-busy goes false LIVE_REGION_CHANGED, // Fired on the root of a live region. LIVE_REGION_CREATED, LIVE_REGION_NODE_CHANGED, // Fired on a node within a live region. LIVE_RELEVANT_CHANGED, LIVE_STATUS_CHANGED, LOAD_COMPLETE, LOAD_START, MENU_ITEM_SELECTED, MULTILINE_STATE_CHANGED, MULTISELECTABLE_STATE_CHANGED, NAME_CHANGED, OBJECT_ATTRIBUTE_CHANGED, OTHER_ATTRIBUTE_CHANGED, PLACEHOLDER_CHANGED, PORTAL_ACTIVATED, POSITION_IN_SET_CHANGED, RELATED_NODE_CHANGED, READONLY_CHANGED, REQUIRED_STATE_CHANGED, ROLE_CHANGED, ROW_COUNT_CHANGED, SCROLL_HORIZONTAL_POSITION_CHANGED, SCROLL_VERTICAL_POSITION_CHANGED, SELECTED_CHANGED, SELECTED_CHILDREN_CHANGED, SET_SIZE_CHANGED, SORT_CHANGED, STATE_CHANGED, SUBTREE_CREATED, TEXT_ATTRIBUTE_CHANGED, VALUE_CHANGED, VALUE_MAX_CHANGED, VALUE_MIN_CHANGED, VALUE_STEP_CHANGED, // This event is for the exact set of attributes that affect // the MSAA/IAccessible state on Windows. Not needed on other platforms, // but very natural to compute here. WIN_IACCESSIBLE_STATE_CHANGED, }; // For distinguishing between show and hide state when a node has // IGNORED_CHANGED event. enum class IgnoredChangedState : uint8_t { kShow, kHide, kCount = 2 }; struct EventParams { EventParams(Event event, ax::mojom::EventFrom event_from, const std::vector<AXEventIntent>& event_intents); ~EventParams(); Event event; ax::mojom::EventFrom event_from; std::vector<AXEventIntent> event_intents; bool operator==(const EventParams& rhs); bool operator<(const EventParams& rhs) const; }; struct TargetedEvent { // |node| must not be null TargetedEvent(ui::AXNode* node, const EventParams& event_params); ui::AXNode* node; const EventParams& event_params; }; class AX_EXPORT Iterator : public std::iterator<std::input_iterator_tag, TargetedEvent> { public: Iterator( const std::map<AXNode*, std::set<EventParams>>& map, const std::map<AXNode*, std::set<EventParams>>::const_iterator& head); Iterator(const Iterator& other); ~Iterator(); bool operator!=(const Iterator& rhs) const; Iterator& operator++(); TargetedEvent operator*() const; private: const std::map<AXNode*, std::set<EventParams>>& map_; std::map<AXNode*, std::set<EventParams>>::const_iterator map_iter_; std::set<EventParams>::const_iterator set_iter_; }; // For storing ignored changed states for a particular node. We use bitset as // the underlying data structure to improve memory usage. // We use the index of AXEventGenerator::IgnoredChangedState enum // to access the bitset data. // e.g. AXEventGenerator::IgnoredChangedState::kShow has index 0 in the // IgnoredChangedState enum. If |IgnoredChangedStatesBitset[0]| is set, it // means IgnoredChangedState::kShow is present. Similarly, kHide has index 1 // in the enum, and it corresponds to |IgnoredChangedStatesBitset[1]|. using IgnoredChangedStatesBitset = std::bitset<static_cast<size_t>(IgnoredChangedState::kCount)>; using const_iterator = Iterator; using iterator = Iterator; using value_type = TargetedEvent; // If you use this constructor, you must call SetTree // before using this class. AXEventGenerator(); // Automatically registers itself as the observer of |tree| and // clears it on destruction. |tree| must be valid for the lifetime // of this object. explicit AXEventGenerator(AXTree* tree); ~AXEventGenerator() override; // Clears this class as the observer of the previous tree that was // being monitored, if any, and starts monitoring |new_tree|, if not // nullptr. Note that |new_tree| must be valid for the lifetime of // this object or until you call SetTree again. void SetTree(AXTree* new_tree); // Null |tree_| without accessing it or destroying it. void ReleaseTree(); Iterator begin() const { return Iterator(tree_events_, tree_events_.begin()); } Iterator end() const { return Iterator(tree_events_, tree_events_.end()); } // Clear any previously added events. void ClearEvents(); // This is called automatically based on changes to the tree observed // by AXTreeObserver, but you can also call it directly to add events // and retrieve them later. // // Note that events are organized by node and then by event id to // efficiently remove duplicates, so events won't be retrieved in the // same order they were added. void AddEvent(ui::AXNode* node, Event event); void set_always_fire_load_complete(bool val) { always_fire_load_complete_ = val; } protected: // AXTreeObserver overrides. void OnNodeDataChanged(AXTree* tree, const AXNodeData& old_node_data, const AXNodeData& new_node_data) override; void OnRoleChanged(AXTree* tree, AXNode* node, ax::mojom::Role old_role, ax::mojom::Role new_role) override; void OnStateChanged(AXTree* tree, AXNode* node, ax::mojom::State state, bool new_value) override; void OnStringAttributeChanged(AXTree* tree, AXNode* node, ax::mojom::StringAttribute attr, const std::string& old_value, const std::string& new_value) override; void OnIntAttributeChanged(AXTree* tree, AXNode* node, ax::mojom::IntAttribute attr, int32_t old_value, int32_t new_value) override; void OnFloatAttributeChanged(AXTree* tree, AXNode* node, ax::mojom::FloatAttribute attr, float old_value, float new_value) override; void OnBoolAttributeChanged(AXTree* tree, AXNode* node, ax::mojom::BoolAttribute attr, bool new_value) override; void OnIntListAttributeChanged( AXTree* tree, AXNode* node, ax::mojom::IntListAttribute attr, const std::vector<int32_t>& old_value, const std::vector<int32_t>& new_value) override; void OnTreeDataChanged(AXTree* tree, const ui::AXTreeData& old_data, const ui::AXTreeData& new_data) override; void OnNodeWillBeDeleted(AXTree* tree, AXNode* node) override; void OnSubtreeWillBeDeleted(AXTree* tree, AXNode* node) override; void OnNodeWillBeReparented(AXTree* tree, AXNode* node) override; void OnSubtreeWillBeReparented(AXTree* tree, AXNode* node) override; void OnAtomicUpdateFinished(AXTree* tree, bool root_changed, const std::vector<Change>& changes) override; private: void FireLiveRegionEvents(AXNode* node); void FireActiveDescendantEvents(); void FireRelationSourceEvents(AXTree* tree, AXNode* target_node); bool ShouldFireLoadEvents(AXNode* node); // Remove excessive events for a tree update containing node. // We remove certain events on a node when it flips its IGNORED state to // either show/hide and one of the node's ancestor has also flipped its // IGNORED state in the same way (show/hide) in the tree update. // |ancestor_has_ignored_map| contains if a node's ancestor has changed to // IGNORED state. // Map's key is an AXNode. // Map's value is a std::bitset containing IgnoredChangedStates(kShow/kHide). // - Map's value IgnoredChangedStatesBitset contains kShow if an ancestor // of node removed its IGNORED state. // - Map's value IgnoredChangedStatesBitset contains kHide if an ancestor // of node changed to IGNORED state. // - When IgnoredChangedStatesBitset is not set, it means neither the // node nor its ancestor has IGNORED_CHANGED. void TrimEventsDueToAncestorIgnoredChanged( AXNode* node, std::map<AXNode*, IgnoredChangedStatesBitset>& ancestor_ignored_changed_map); void PostprocessEvents(); static void GetRestrictionStates(ax::mojom::Restriction restriction, bool* is_enabled, bool* is_readonly); // Returns a vector of values unique to either |lhs| or |rhs| static std::vector<int32_t> ComputeIntListDifference( const std::vector<int32_t>& lhs, const std::vector<int32_t>& rhs); AXTree* tree_ = nullptr; // Not owned. std::map<AXNode*, std::set<EventParams>> tree_events_; // Valid between the call to OnIntAttributeChanged and the call to // OnAtomicUpdateFinished. List of nodes whose active descendant changed. std::vector<AXNode*> active_descendant_changed_; bool always_fire_load_complete_ = false; }; AX_EXPORT std::ostream& operator<<(std::ostream& os, AXEventGenerator::Event event); AX_EXPORT const char* ToString(AXEventGenerator::Event event); } // namespace ui #endif // UI_ACCESSIBILITY_AX_EVENT_GENERATOR_H_
engine/third_party/accessibility/ax/ax_event_generator.h/0
{ "file_path": "engine/third_party/accessibility/ax/ax_event_generator.h", "repo_id": "engine", "token_count": 4542 }
462
// 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. #include "ax_node_text_styles.h" constexpr int kUnsetValue = -1; namespace ui { AXNodeTextStyles::AXNodeTextStyles() : background_color(kUnsetValue), color(kUnsetValue), invalid_state(kUnsetValue), overline_style(kUnsetValue), strikethrough_style(kUnsetValue), text_direction(kUnsetValue), text_position(kUnsetValue), text_style(kUnsetValue), underline_style(kUnsetValue), font_size(kUnsetValue), font_weight(kUnsetValue) {} AXNodeTextStyles::AXNodeTextStyles(AXNodeTextStyles&& other) : background_color(other.background_color), color(other.color), invalid_state(other.invalid_state), overline_style(other.overline_style), strikethrough_style(other.strikethrough_style), text_direction(other.text_direction), text_position(other.text_position), text_style(other.text_style), underline_style(other.underline_style), font_size(other.font_size), font_weight(other.font_weight), font_family(std::move(other.font_family)) {} AXNodeTextStyles& AXNodeTextStyles::operator=(AXNodeTextStyles&& other) { background_color = other.background_color; color = other.color; invalid_state = other.invalid_state; overline_style = other.overline_style; strikethrough_style = other.strikethrough_style; text_direction = other.text_direction; text_position = other.text_position; text_style = other.text_style; underline_style = other.underline_style; font_size = other.font_size; font_weight = other.font_weight; font_family = other.font_family; return *this; } bool AXNodeTextStyles::operator==(const AXNodeTextStyles& other) const { return (background_color == other.background_color && color == other.color && invalid_state == other.invalid_state && overline_style == other.overline_style && strikethrough_style == other.strikethrough_style && text_direction == other.text_direction && text_position == other.text_position && font_size == other.font_size && font_weight == other.font_weight && text_style == other.text_style && underline_style == other.underline_style && font_family == other.font_family); } bool AXNodeTextStyles::operator!=(const AXNodeTextStyles& other) const { return !operator==(other); } bool AXNodeTextStyles::IsUnset() const { return (background_color == kUnsetValue && invalid_state == kUnsetValue && overline_style == kUnsetValue && strikethrough_style == kUnsetValue && text_position == kUnsetValue && font_size == kUnsetValue && font_weight == kUnsetValue && text_style == kUnsetValue && underline_style == kUnsetValue && font_family.length() == 0); } } // namespace ui
engine/third_party/accessibility/ax/ax_node_text_styles.cc/0
{ "file_path": "engine/third_party/accessibility/ax/ax_node_text_styles.cc", "repo_id": "engine", "token_count": 1110 }
463
// Copyright 2015 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. #include "ax_tree_data.h" #include <set> #include "ax_enum_util.h" #include "ax_enums.h" #include "base/string_utils.h" namespace ui { AXTreeData::AXTreeData() : sel_anchor_affinity(ax::mojom::TextAffinity::kDownstream), sel_focus_affinity(ax::mojom::TextAffinity::kDownstream) {} AXTreeData::AXTreeData(const AXTreeData& other) = default; AXTreeData::~AXTreeData() = default; // Note that this includes an initial space character if nonempty, but // that works fine because this is normally printed by AXTree::ToString. std::string AXTreeData::ToString() const { std::string result; if (tree_id != AXTreeIDUnknown()) result += " tree_id=" + tree_id.ToString().substr(0, 8); if (parent_tree_id != AXTreeIDUnknown()) result += " parent_tree_id=" + parent_tree_id.ToString().substr(0, 8); if (focused_tree_id != AXTreeIDUnknown()) result += " focused_tree_id=" + focused_tree_id.ToString().substr(0, 8); if (!doctype.empty()) result += " doctype=" + doctype; if (loaded) result += " loaded=true"; if (loading_progress != 0.0f) result += " loading_progress=" + base::NumberToString(loading_progress); if (!mimetype.empty()) result += " mimetype=" + mimetype; if (!url.empty()) result += " url=" + url; if (!title.empty()) result += " title=" + title; if (focus_id != AXNode::kInvalidAXID) result += " focus_id=" + base::NumberToString(focus_id); if (sel_anchor_object_id != AXNode::kInvalidAXID) { result += (sel_is_backward ? " sel_is_backward=true" : " sel_is_backward=false"); result += " sel_anchor_object_id=" + base::NumberToString(sel_anchor_object_id); result += " sel_anchor_offset=" + base::NumberToString(sel_anchor_offset); result += " sel_anchor_affinity="; result += ui::ToString(sel_anchor_affinity); } if (sel_focus_object_id != AXNode::kInvalidAXID) { result += " sel_focus_object_id=" + base::NumberToString(sel_focus_object_id); result += " sel_focus_offset=" + base::NumberToString(sel_focus_offset); result += " sel_focus_affinity="; result += ui::ToString(sel_focus_affinity); } return result; } bool operator==(const AXTreeData& lhs, const AXTreeData& rhs) { return (lhs.tree_id == rhs.tree_id && lhs.parent_tree_id == rhs.parent_tree_id && lhs.focused_tree_id == rhs.focused_tree_id && lhs.doctype == rhs.doctype && lhs.loaded == rhs.loaded && lhs.loading_progress == rhs.loading_progress && lhs.mimetype == rhs.mimetype && lhs.title == rhs.title && lhs.url == rhs.url && lhs.focus_id == rhs.focus_id && lhs.sel_anchor_object_id == rhs.sel_anchor_object_id && lhs.sel_anchor_offset == rhs.sel_anchor_offset && lhs.sel_anchor_affinity == rhs.sel_anchor_affinity && lhs.sel_focus_object_id == rhs.sel_focus_object_id && lhs.sel_focus_offset == rhs.sel_focus_offset && lhs.sel_focus_affinity == rhs.sel_focus_affinity); } bool operator!=(const AXTreeData& lhs, const AXTreeData& rhs) { return !(lhs == rhs); } } // namespace ui
engine/third_party/accessibility/ax/ax_tree_data.cc/0
{ "file_path": "engine/third_party/accessibility/ax/ax_tree_data.cc", "repo_id": "engine", "token_count": 1349 }
464
// 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. #include "ax_fragment_root_win.h" #include "ax_platform_node_win.h" #include "ax_platform_node_win_unittest.h" #include "test_ax_node_wrapper.h" #include <UIAutomationClient.h> #include <UIAutomationCoreApi.h> #include "base/auto_reset.h" #include "base/win/scoped_safearray.h" #include "base/win/scoped_variant.h" #include "gtest/gtest.h" #include "uia_registrar_win.h" using base::win::ScopedVariant; using Microsoft::WRL::ComPtr; namespace ui { #define EXPECT_UIA_BSTR_EQ(node, property_id, expected) \ { \ ScopedVariant expectedVariant(expected); \ ASSERT_EQ(VT_BSTR, expectedVariant.type()); \ ASSERT_NE(nullptr, expectedVariant.ptr()->bstrVal); \ ScopedVariant actual; \ ASSERT_HRESULT_SUCCEEDED( \ node->GetPropertyValue(property_id, actual.Receive())); \ ASSERT_EQ(VT_BSTR, actual.type()); \ ASSERT_NE(nullptr, actual.ptr()->bstrVal); \ EXPECT_STREQ(expectedVariant.ptr()->bstrVal, actual.ptr()->bstrVal); \ } class AXFragmentRootTest : public AXPlatformNodeWinTest { public: AXFragmentRootTest() = default; ~AXFragmentRootTest() override = default; AXFragmentRootTest(const AXFragmentRootTest&) = delete; AXFragmentRootTest& operator=(const AXFragmentRootTest&) = delete; }; TEST_F(AXFragmentRootTest, UIAFindItemByPropertyUniqueId) { AXNodeData root; root.id = 1; root.role = ax::mojom::Role::kRootWebArea; root.SetName("root"); root.child_ids = {2, 3}; AXNodeData text1; text1.id = 2; text1.role = ax::mojom::Role::kStaticText; text1.SetName("text1"); AXNodeData button; button.id = 3; button.role = ax::mojom::Role::kButton; button.SetName("button"); button.child_ids = {4}; AXNodeData text2; text2.id = 4; text2.role = ax::mojom::Role::kStaticText; text2.SetName("text2"); Init(root, text1, button, text2); InitFragmentRoot(); ComPtr<IRawElementProviderSimple> root_raw_element_provider_simple; ax_fragment_root_->GetNativeViewAccessible()->QueryInterface( IID_PPV_ARGS(&root_raw_element_provider_simple)); ComPtr<IRawElementProviderSimple> text1_raw_element_provider_simple = GetIRawElementProviderSimpleFromChildIndex(0); ComPtr<IRawElementProviderSimple> button_raw_element_provider_simple = GetIRawElementProviderSimpleFromChildIndex(1); AXNode* text1_node = GetRootAsAXNode()->children()[0]; AXNode* button_node = GetRootAsAXNode()->children()[1]; ComPtr<IItemContainerProvider> item_container_provider; EXPECT_HRESULT_SUCCEEDED(root_raw_element_provider_simple->GetPatternProvider( UIA_ItemContainerPatternId, &item_container_provider)); ASSERT_NE(nullptr, item_container_provider.Get()); ScopedVariant unique_id_variant; int32_t unique_id; ComPtr<IRawElementProviderSimple> result; // When |start_after_element| is an invalid element, we should fail at finding // the item. { unique_id = AXPlatformNodeFromNode(GetRootAsAXNode())->GetUniqueId(); unique_id_variant.Set(SysAllocString(reinterpret_cast<const wchar_t*>( base::NumberToString16(-unique_id).c_str()))); ComPtr<IRawElementProviderSimple> invalid_element_provider_simple; EXPECT_HRESULT_SUCCEEDED( MockIRawElementProviderSimple::CreateMockIRawElementProviderSimple( &invalid_element_provider_simple)); EXPECT_HRESULT_FAILED(item_container_provider->FindItemByProperty( invalid_element_provider_simple.Get(), UiaRegistrarWin::GetInstance().GetUiaUniqueIdPropertyId(), unique_id_variant, &result)); result.Reset(); unique_id_variant.Release(); } // Fetch the AxUniqueId of "root", and verify we can retrieve its // corresponding IRawElementProviderSimple through FindItemByProperty(). { unique_id = AXPlatformNodeFromNode(GetRootAsAXNode())->GetUniqueId(); unique_id_variant.Set(SysAllocString(reinterpret_cast<const wchar_t*>( base::NumberToString16(-unique_id).c_str()))); // When |start_after_element| of FindItemByProperty() is nullptr, we should // be able to find "text1". EXPECT_HRESULT_SUCCEEDED(item_container_provider->FindItemByProperty( nullptr, UiaRegistrarWin::GetInstance().GetUiaUniqueIdPropertyId(), unique_id_variant, &result)); EXPECT_UIA_BSTR_EQ(result, UIA_NamePropertyId, L"root"); result.Reset(); // When |start_after_element| of FindItemByProperty() is "text1", there // should be no element found, since "text1" comes after the element we are // looking for. EXPECT_HRESULT_SUCCEEDED(item_container_provider->FindItemByProperty( text1_raw_element_provider_simple.Get(), UiaRegistrarWin::GetInstance().GetUiaUniqueIdPropertyId(), unique_id_variant, &result)); EXPECT_EQ(nullptr, result.Get()); result.Reset(); // When |start_after_element| of FindItemByProperty() is "button", there // should be no element found, since "button" comes after the element we are // looking for. EXPECT_HRESULT_SUCCEEDED(item_container_provider->FindItemByProperty( button_raw_element_provider_simple.Get(), UiaRegistrarWin::GetInstance().GetUiaUniqueIdPropertyId(), unique_id_variant, &result)); EXPECT_EQ(nullptr, result.Get()); result.Reset(); unique_id_variant.Release(); } // Fetch the AxUniqueId of "text1", and verify if we can retrieve its // corresponding IRawElementProviderSimple through FindItemByProperty(). { unique_id = AXPlatformNodeFromNode(text1_node)->GetUniqueId(); unique_id_variant.Set(SysAllocString(reinterpret_cast<const wchar_t*>( base::NumberToString16(-unique_id).c_str()))); // When |start_after_element| of FindItemByProperty() is nullptr, we should // be able to find "text1". EXPECT_HRESULT_SUCCEEDED(item_container_provider->FindItemByProperty( nullptr, UiaRegistrarWin::GetInstance().GetUiaUniqueIdPropertyId(), unique_id_variant, &result)); EXPECT_UIA_BSTR_EQ(result, UIA_NamePropertyId, L"text1"); result.Reset(); // When |start_after_element| of FindItemByProperty() is "text1", there // should be no element found, since "text1" equals the element we are // looking for. EXPECT_HRESULT_SUCCEEDED(item_container_provider->FindItemByProperty( text1_raw_element_provider_simple.Get(), UiaRegistrarWin::GetInstance().GetUiaUniqueIdPropertyId(), unique_id_variant, &result)); EXPECT_EQ(nullptr, result.Get()); result.Reset(); // When |start_after_element| of FindItemByProperty() is "button", there // should be no element found, since "button" comes after the element we are // looking for. EXPECT_HRESULT_SUCCEEDED(item_container_provider->FindItemByProperty( button_raw_element_provider_simple.Get(), UiaRegistrarWin::GetInstance().GetUiaUniqueIdPropertyId(), unique_id_variant, &result)); EXPECT_EQ(nullptr, result.Get()); result.Reset(); unique_id_variant.Release(); } // Fetch the AxUniqueId of "button", and verify we can retrieve its // corresponding IRawElementProviderSimple through FindItemByProperty(). { unique_id = AXPlatformNodeFromNode(button_node)->GetUniqueId(); unique_id_variant.Set(SysAllocString(reinterpret_cast<const wchar_t*>( base::NumberToString16(-unique_id).c_str()))); // When |start_after_element| of FindItemByProperty() is nullptr, we should // be able to find "button". EXPECT_HRESULT_SUCCEEDED(item_container_provider->FindItemByProperty( nullptr, UiaRegistrarWin::GetInstance().GetUiaUniqueIdPropertyId(), unique_id_variant, &result)); EXPECT_UIA_BSTR_EQ(result, UIA_NamePropertyId, L"button"); result.Reset(); // When |start_after_element| of FindItemByProperty() is "text1", we should // be able to find "button". EXPECT_HRESULT_SUCCEEDED(item_container_provider->FindItemByProperty( text1_raw_element_provider_simple.Get(), UiaRegistrarWin::GetInstance().GetUiaUniqueIdPropertyId(), unique_id_variant, &result)); EXPECT_UIA_BSTR_EQ(result, UIA_NamePropertyId, L"button"); result.Reset(); // When |start_after_element| of FindItemByProperty() is "button", there // should be no element found, since "button" equals the element we are // looking for. EXPECT_HRESULT_SUCCEEDED(item_container_provider->FindItemByProperty( button_raw_element_provider_simple.Get(), UiaRegistrarWin::GetInstance().GetUiaUniqueIdPropertyId(), unique_id_variant, &result)); EXPECT_EQ(nullptr, result.Get()); result.Reset(); unique_id_variant.Release(); } // Fetch the AxUniqueId of "text2", and verify we can retrieve its // corresponding IRawElementProviderSimple through FindItemByProperty(). { unique_id = AXPlatformNodeFromNode(button_node->children()[0])->GetUniqueId(); unique_id_variant.Set(SysAllocString(reinterpret_cast<const wchar_t*>( base::NumberToString16(-unique_id).c_str()))); // When |start_after_element| of FindItemByProperty() is nullptr, we should // be able to find "text2". EXPECT_HRESULT_SUCCEEDED(item_container_provider->FindItemByProperty( nullptr, UiaRegistrarWin::GetInstance().GetUiaUniqueIdPropertyId(), unique_id_variant, &result)); EXPECT_UIA_BSTR_EQ(result, UIA_NamePropertyId, L"text2"); // When |start_after_element| of FindItemByProperty() is root, we should // be able to find "text2". EXPECT_HRESULT_SUCCEEDED(item_container_provider->FindItemByProperty( root_raw_element_provider_simple.Get(), UiaRegistrarWin::GetInstance().GetUiaUniqueIdPropertyId(), unique_id_variant, &result)); EXPECT_UIA_BSTR_EQ(result, UIA_NamePropertyId, L"text2"); // When |start_after_element| of FindItemByProperty() is "text1", we should // be able to find "text2". EXPECT_HRESULT_SUCCEEDED(item_container_provider->FindItemByProperty( text1_raw_element_provider_simple.Get(), UiaRegistrarWin::GetInstance().GetUiaUniqueIdPropertyId(), unique_id_variant, &result)); EXPECT_UIA_BSTR_EQ(result, UIA_NamePropertyId, L"text2"); // When |start_after_element| of FindItemByProperty() is "button", we should // be able to find "text2". EXPECT_HRESULT_SUCCEEDED(item_container_provider->FindItemByProperty( button_raw_element_provider_simple.Get(), UiaRegistrarWin::GetInstance().GetUiaUniqueIdPropertyId(), unique_id_variant, &result)); EXPECT_UIA_BSTR_EQ(result, UIA_NamePropertyId, L"text2"); } } TEST_F(AXFragmentRootTest, TestUIAGetFragmentRoot) { AXNodeData root; root.id = 1; Init(root); InitFragmentRoot(); ComPtr<IRawElementProviderFragmentRoot> expected_fragment_root = GetFragmentRoot(); ComPtr<IRawElementProviderFragment> fragment_provider; expected_fragment_root.As(&fragment_provider); ComPtr<IRawElementProviderFragmentRoot> actual_fragment_root; EXPECT_HRESULT_SUCCEEDED( fragment_provider->get_FragmentRoot(&actual_fragment_root)); EXPECT_EQ(expected_fragment_root.Get(), actual_fragment_root.Get()); } TEST_F(AXFragmentRootTest, DISABLED_TestUIAElementProviderFromPoint) { AXNodeData root_data; root_data.id = 1; root_data.relative_bounds.bounds = gfx::RectF(0, 0, 80, 80); AXNodeData element1_data; element1_data.id = 2; element1_data.relative_bounds.bounds = gfx::RectF(0, 0, 50, 50); root_data.child_ids.push_back(element1_data.id); AXNodeData element2_data; element2_data.id = 3; element2_data.relative_bounds.bounds = gfx::RectF(0, 50, 30, 30); root_data.child_ids.push_back(element2_data.id); Init(root_data, element1_data, element2_data); InitFragmentRoot(); AXNode* root_node = GetRootAsAXNode(); AXNode* element1_node = root_node->children()[0]; AXNode* element2_node = root_node->children()[1]; ComPtr<IRawElementProviderFragmentRoot> fragment_root_prov(GetFragmentRoot()); ComPtr<IRawElementProviderFragment> root_provider( GetRootIRawElementProviderFragment()); ComPtr<IRawElementProviderFragment> element1_provider = QueryInterfaceFromNode<IRawElementProviderFragment>(element1_node); ComPtr<IRawElementProviderFragment> element2_provider = QueryInterfaceFromNode<IRawElementProviderFragment>(element2_node); ComPtr<IRawElementProviderFragment> provider_from_point; EXPECT_HRESULT_SUCCEEDED(fragment_root_prov->ElementProviderFromPoint( 23, 31, &provider_from_point)); EXPECT_EQ(element1_provider.Get(), provider_from_point.Get()); EXPECT_HRESULT_SUCCEEDED(fragment_root_prov->ElementProviderFromPoint( 23, 67, &provider_from_point)); EXPECT_EQ(element2_provider.Get(), provider_from_point.Get()); EXPECT_HRESULT_SUCCEEDED(fragment_root_prov->ElementProviderFromPoint( 47, 67, &provider_from_point)); EXPECT_EQ(root_provider.Get(), provider_from_point.Get()); // This is on node 1 with scale factor of 1.5. std::unique_ptr<base::AutoReset<float>> scale_factor_reset = TestAXNodeWrapper::SetScaleFactor(1.5); EXPECT_HRESULT_SUCCEEDED(fragment_root_prov->ElementProviderFromPoint( 60, 60, &provider_from_point)); EXPECT_EQ(element1_provider.Get(), provider_from_point.Get()); } TEST_F(AXFragmentRootTest, TestUIAGetFocus) { AXNodeData root_data; root_data.id = 1; AXNodeData element1_data; element1_data.id = 2; root_data.child_ids.push_back(element1_data.id); AXNodeData element2_data; element2_data.id = 3; root_data.child_ids.push_back(element2_data.id); Init(root_data, element1_data, element2_data); InitFragmentRoot(); AXNode* root_node = GetRootAsAXNode(); AXNode* element1_node = root_node->children()[0]; AXNode* element2_node = root_node->children()[1]; ComPtr<IRawElementProviderFragmentRoot> fragment_root_prov(GetFragmentRoot()); ComPtr<IRawElementProviderFragment> root_provider( GetRootIRawElementProviderFragment()); ComPtr<IRawElementProviderFragment> element1_provider = QueryInterfaceFromNode<IRawElementProviderFragment>(element1_node); ComPtr<IRawElementProviderFragment> element2_provider = QueryInterfaceFromNode<IRawElementProviderFragment>(element2_node); ComPtr<IRawElementProviderFragment> focused_fragment; EXPECT_HRESULT_SUCCEEDED(root_provider->SetFocus()); EXPECT_HRESULT_SUCCEEDED(fragment_root_prov->GetFocus(&focused_fragment)); EXPECT_EQ(root_provider.Get(), focused_fragment.Get()); EXPECT_HRESULT_SUCCEEDED(element1_provider->SetFocus()); EXPECT_HRESULT_SUCCEEDED(fragment_root_prov->GetFocus(&focused_fragment)); EXPECT_EQ(element1_provider.Get(), focused_fragment.Get()); EXPECT_HRESULT_SUCCEEDED(element2_provider->SetFocus()); EXPECT_HRESULT_SUCCEEDED(fragment_root_prov->GetFocus(&focused_fragment)); EXPECT_EQ(element2_provider.Get(), focused_fragment.Get()); } TEST_F(AXFragmentRootTest, TestUIAErrorHandling) { AXNodeData root; root.id = 1; Init(root); InitFragmentRoot(); ComPtr<IRawElementProviderSimple> simple_provider = GetRootIRawElementProviderSimple(); ComPtr<IRawElementProviderFragment> fragment_provider = GetRootIRawElementProviderFragment(); ComPtr<IRawElementProviderFragmentRoot> fragment_root_provider = GetFragmentRoot(); SetTree(std::make_unique<AXTree>()); ax_fragment_root_.reset(nullptr); ComPtr<IRawElementProviderSimple> returned_simple_provider; ComPtr<IRawElementProviderFragment> returned_fragment_provider; ComPtr<IRawElementProviderFragmentRoot> returned_fragment_root_provider; base::win::ScopedSafearray returned_runtime_id; EXPECT_EQ( static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), simple_provider->get_HostRawElementProvider(&returned_simple_provider)); EXPECT_EQ( static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), fragment_provider->get_FragmentRoot(&returned_fragment_root_provider)); EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), fragment_provider->GetRuntimeId(returned_runtime_id.Receive())); EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), fragment_root_provider->ElementProviderFromPoint( 67, 23, &returned_fragment_provider)); EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), fragment_root_provider->GetFocus(&returned_fragment_provider)); } TEST_F(AXFragmentRootTest, TestGetChildCount) { AXNodeData root; root.id = 1; Init(root); InitFragmentRoot(); AXPlatformNodeDelegate* fragment_root = ax_fragment_root_.get(); EXPECT_EQ(1, fragment_root->GetChildCount()); test_fragment_root_delegate_->child_ = nullptr; EXPECT_EQ(0, fragment_root->GetChildCount()); } TEST_F(AXFragmentRootTest, TestChildAtIndex) { AXNodeData root; root.id = 1; Init(root); InitFragmentRoot(); gfx::NativeViewAccessible native_view_accessible = AXPlatformNodeFromNode(GetRootAsAXNode())->GetNativeViewAccessible(); AXPlatformNodeDelegate* fragment_root = ax_fragment_root_.get(); EXPECT_EQ(native_view_accessible, fragment_root->ChildAtIndex(0)); EXPECT_EQ(nullptr, fragment_root->ChildAtIndex(1)); test_fragment_root_delegate_->child_ = nullptr; EXPECT_EQ(nullptr, fragment_root->ChildAtIndex(0)); } TEST_F(AXFragmentRootTest, TestGetParent) { AXNodeData root; root.id = 1; Init(root); InitFragmentRoot(); AXPlatformNodeDelegate* fragment_root = ax_fragment_root_.get(); EXPECT_EQ(nullptr, fragment_root->GetParent()); gfx::NativeViewAccessible native_view_accessible = AXPlatformNodeFromNode(GetRootAsAXNode())->GetNativeViewAccessible(); test_fragment_root_delegate_->parent_ = native_view_accessible; EXPECT_EQ(native_view_accessible, fragment_root->GetParent()); } TEST_F(AXFragmentRootTest, TestGetPropertyValue) { AXNodeData root; root.id = 1; Init(root); InitFragmentRoot(); ComPtr<IRawElementProviderSimple> root_provider; ax_fragment_root_->GetNativeViewAccessible()->QueryInterface( IID_PPV_ARGS(&root_provider)); // IsControlElement and IsContentElement should follow the setting on the // fragment root delegate. test_fragment_root_delegate_->is_control_element_ = true; ScopedVariant result; EXPECT_HRESULT_SUCCEEDED(root_provider->GetPropertyValue( UIA_IsControlElementPropertyId, result.Receive())); EXPECT_EQ(result.type(), VT_BOOL); EXPECT_EQ(result.ptr()->boolVal, VARIANT_TRUE); EXPECT_HRESULT_SUCCEEDED(root_provider->GetPropertyValue( UIA_IsContentElementPropertyId, result.Receive())); EXPECT_EQ(result.type(), VT_BOOL); EXPECT_EQ(result.ptr()->boolVal, VARIANT_TRUE); test_fragment_root_delegate_->is_control_element_ = false; EXPECT_HRESULT_SUCCEEDED(root_provider->GetPropertyValue( UIA_IsControlElementPropertyId, result.Receive())); EXPECT_EQ(result.type(), VT_BOOL); EXPECT_EQ(result.ptr()->boolVal, VARIANT_FALSE); EXPECT_HRESULT_SUCCEEDED(root_provider->GetPropertyValue( UIA_IsContentElementPropertyId, result.Receive())); EXPECT_EQ(result.type(), VT_BOOL); EXPECT_EQ(result.ptr()->boolVal, VARIANT_FALSE); // Other properties should return VT_EMPTY. EXPECT_HRESULT_SUCCEEDED(root_provider->GetPropertyValue( UIA_ControlTypePropertyId, result.Receive())); EXPECT_EQ(result.type(), VT_EMPTY); } TEST_F(AXFragmentRootTest, TestUIAMultipleFragmentRoots) { // Consider the following platform-neutral tree: // // N1 // _____/ \_____ // / \ // N2---N3---N4---N5 // / \ / \ // N6---N7 N8---N9 // // N3 and N5 are nodes for which we need a fragment root. This will correspond // to the following tree in UIA: // // U1 // _____/ \_____ // / \ // U2---R3---U4---R5 // | | // U3 U5 // / \ / \ // U6---U7 U8---U9 ui::AXNodeData top_fragment_root_n1; top_fragment_root_n1.id = 1; ui::AXNodeData sibling_n2; sibling_n2.id = 2; ui::AXNodeData child_fragment_root_n3; child_fragment_root_n3.id = 3; ui::AXNodeData sibling_n6; sibling_n6.id = 6; ui::AXNodeData sibling_n7; sibling_n7.id = 7; child_fragment_root_n3.child_ids = {6, 7}; ui::AXNodeData sibling_n4; sibling_n4.id = 4; ui::AXNodeData child_fragment_root_n5; child_fragment_root_n5.id = 5; ui::AXNodeData sibling_n8; sibling_n8.id = 8; ui::AXNodeData sibling_n9; sibling_n9.id = 9; child_fragment_root_n5.child_ids = {8, 9}; top_fragment_root_n1.child_ids = {2, 3, 4, 5}; ui::AXTreeUpdate update; update.has_tree_data = true; update.root_id = top_fragment_root_n1.id; update.nodes = {top_fragment_root_n1, sibling_n2, child_fragment_root_n3, sibling_n6, sibling_n7, sibling_n4, child_fragment_root_n5, sibling_n8, sibling_n9}; update.tree_data.tree_id = ui::AXTreeID::CreateNewAXTreeID(); Init(update); InitFragmentRoot(); AXNode* root_node = GetRootAsAXNode(); // Set up other fragment roots AXNode* child_fragment_root_n3_node = root_node->children()[1]; std::unique_ptr<TestFragmentRootDelegate> n3_fragment_root_delegate = std::make_unique<TestFragmentRootDelegate>(); std::unique_ptr<AXFragmentRootWin> n3_fragment_root(InitNodeAsFragmentRoot( child_fragment_root_n3_node, n3_fragment_root_delegate.get())); AXNode* child_fragment_root_n5_node = root_node->children()[3]; std::unique_ptr<TestFragmentRootDelegate> n5_fragment_root_delegate = std::make_unique<TestFragmentRootDelegate>(); std::unique_ptr<AXFragmentRootWin> n5_fragment_root(InitNodeAsFragmentRoot( child_fragment_root_n5_node, n5_fragment_root_delegate.get())); // Test navigation from root fragment ComPtr<IRawElementProviderFragmentRoot> root_fragment_root = GetFragmentRoot(); ComPtr<IRawElementProviderFragment> root_fragment; root_fragment_root.As(&root_fragment); ComPtr<IRawElementProviderFragment> test_fragment; EXPECT_HRESULT_SUCCEEDED( root_fragment->Navigate(NavigateDirection_Parent, &test_fragment)); EXPECT_EQ(nullptr, test_fragment.Get()); EXPECT_HRESULT_SUCCEEDED( root_fragment->Navigate(NavigateDirection_NextSibling, &test_fragment)); EXPECT_EQ(nullptr, test_fragment.Get()); EXPECT_HRESULT_SUCCEEDED(root_fragment->Navigate( NavigateDirection_PreviousSibling, &test_fragment)); EXPECT_EQ(nullptr, test_fragment.Get()); EXPECT_HRESULT_SUCCEEDED( root_fragment->Navigate(NavigateDirection_FirstChild, &test_fragment)); ComPtr<IUnknown> root_child_unknown = test_fragment_root_delegate_->child_; ComPtr<IRawElementProviderFragment> root_child_fragment; root_child_unknown.As(&root_child_fragment); EXPECT_EQ(root_child_fragment.Get(), test_fragment.Get()); EXPECT_HRESULT_SUCCEEDED( root_fragment->Navigate(NavigateDirection_LastChild, &test_fragment)); EXPECT_EQ(root_child_fragment.Get(), test_fragment.Get()); // Test navigation from first child root (R3) ComPtr<IRawElementProviderFragmentRoot> n3_fragment_root_provider; n3_fragment_root->GetNativeViewAccessible()->QueryInterface( IID_PPV_ARGS(&n3_fragment_root_provider)); ComPtr<IRawElementProviderFragment> n3_fragment; n3_fragment_root_provider.As(&n3_fragment); EXPECT_HRESULT_SUCCEEDED( n3_fragment->Navigate(NavigateDirection_Parent, &test_fragment)); EXPECT_EQ(root_child_fragment.Get(), test_fragment.Get()); AXNode* sibling_n2_node = root_node->children()[0]; EXPECT_HRESULT_SUCCEEDED( n3_fragment->Navigate(NavigateDirection_PreviousSibling, &test_fragment)); EXPECT_EQ(IRawElementProviderFragmentFromNode(sibling_n2_node).Get(), test_fragment.Get()); AXNode* sibling_n4_node = root_node->children()[2]; EXPECT_HRESULT_SUCCEEDED( n3_fragment->Navigate(NavigateDirection_NextSibling, &test_fragment)); EXPECT_EQ(IRawElementProviderFragmentFromNode(sibling_n4_node).Get(), test_fragment.Get()); EXPECT_HRESULT_SUCCEEDED( n3_fragment->Navigate(NavigateDirection_FirstChild, &test_fragment)); EXPECT_EQ( IRawElementProviderFragmentFromNode(child_fragment_root_n3_node).Get(), test_fragment.Get()); EXPECT_HRESULT_SUCCEEDED( n3_fragment->Navigate(NavigateDirection_LastChild, &test_fragment)); EXPECT_EQ( IRawElementProviderFragmentFromNode(child_fragment_root_n3_node).Get(), test_fragment.Get()); // Test navigation from second child root (R5) ComPtr<IRawElementProviderFragmentRoot> n5_fragment_root_provider; n5_fragment_root->GetNativeViewAccessible()->QueryInterface( IID_PPV_ARGS(&n5_fragment_root_provider)); ComPtr<IRawElementProviderFragment> n5_fragment; n5_fragment_root_provider.As(&n5_fragment); EXPECT_HRESULT_SUCCEEDED( n5_fragment->Navigate(NavigateDirection_Parent, &test_fragment)); EXPECT_EQ(root_child_fragment.Get(), test_fragment.Get()); EXPECT_HRESULT_SUCCEEDED( n5_fragment->Navigate(NavigateDirection_NextSibling, &test_fragment)); EXPECT_EQ(nullptr, test_fragment.Get()); EXPECT_HRESULT_SUCCEEDED( n5_fragment->Navigate(NavigateDirection_PreviousSibling, &test_fragment)); EXPECT_EQ(IRawElementProviderFragmentFromNode(sibling_n4_node).Get(), test_fragment.Get()); EXPECT_HRESULT_SUCCEEDED( n5_fragment->Navigate(NavigateDirection_FirstChild, &test_fragment)); EXPECT_EQ( IRawElementProviderFragmentFromNode(child_fragment_root_n5_node).Get(), test_fragment.Get()); EXPECT_HRESULT_SUCCEEDED( n5_fragment->Navigate(NavigateDirection_LastChild, &test_fragment)); EXPECT_EQ( IRawElementProviderFragmentFromNode(child_fragment_root_n5_node).Get(), test_fragment.Get()); } TEST_F(AXFragmentRootTest, TestFragmentRootMap) { AXNodeData root; root.id = 1; Init(root); // There should be nothing in the map before we create a fragment root. // Call GetForAcceleratedWidget() first to ensure that querying for a // fragment root doesn't inadvertently create an empty entry in the map // (https://crbug.com/1071185). EXPECT_EQ(nullptr, AXFragmentRootWin::GetForAcceleratedWidget( gfx::kMockAcceleratedWidget)); EXPECT_EQ(nullptr, AXFragmentRootWin::GetFragmentRootParentOf( GetRootIAccessible().Get())); // After initializing a fragment root, we should be able to retrieve it using // its accelerated widget, or as the parent of its child. InitFragmentRoot(); EXPECT_EQ(ax_fragment_root_.get(), AXFragmentRootWin::GetForAcceleratedWidget( gfx::kMockAcceleratedWidget)); EXPECT_EQ(ax_fragment_root_.get(), AXFragmentRootWin::GetFragmentRootParentOf( GetRootIAccessible().Get())); // After deleting a fragment root, it should no longer be reachable from the // map. ax_fragment_root_.reset(); EXPECT_EQ(nullptr, AXFragmentRootWin::GetForAcceleratedWidget( gfx::kMockAcceleratedWidget)); EXPECT_EQ(nullptr, AXFragmentRootWin::GetFragmentRootParentOf( GetRootIAccessible().Get())); } } // namespace ui
engine/third_party/accessibility/ax/platform/ax_fragment_root_win_unittest.cc/0
{ "file_path": "engine/third_party/accessibility/ax/platform/ax_fragment_root_win_unittest.cc", "repo_id": "engine", "token_count": 11101 }
465
// 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. #ifndef UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_NODE_TEXTPROVIDER_WIN_H_ #define UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_NODE_TEXTPROVIDER_WIN_H_ #include <atlbase.h> #include <atlcom.h> #include <UIAutomationCore.h> #include "ax/ax_node_position.h" #include "ax/platform/ax_platform_node_win.h" namespace ui { class AX_EXPORT __declspec(uuid("3e1c192b-4348-45ac-8eb6-4b58eeb3dcca")) AXPlatformNodeTextProviderWin : public CComObjectRootEx<CComMultiThreadModel>, public ITextEditProvider { public: BEGIN_COM_MAP(AXPlatformNodeTextProviderWin) COM_INTERFACE_ENTRY(ITextProvider) COM_INTERFACE_ENTRY(ITextEditProvider) COM_INTERFACE_ENTRY(AXPlatformNodeTextProviderWin) END_COM_MAP() AXPlatformNodeTextProviderWin(); ~AXPlatformNodeTextProviderWin(); static AXPlatformNodeTextProviderWin* Create(AXPlatformNodeWin* owner); static void CreateIUnknown(AXPlatformNodeWin* owner, IUnknown** unknown); // // ITextProvider methods. // IFACEMETHODIMP GetSelection(SAFEARRAY** selection) override; IFACEMETHODIMP GetVisibleRanges(SAFEARRAY** visible_ranges) override; IFACEMETHODIMP RangeFromChild(IRawElementProviderSimple* child, ITextRangeProvider** range) override; IFACEMETHODIMP RangeFromPoint(UiaPoint point, ITextRangeProvider** range) override; IFACEMETHODIMP get_DocumentRange(ITextRangeProvider** range) override; IFACEMETHODIMP get_SupportedTextSelection( enum SupportedTextSelection* text_selection) override; // // ITextEditProvider methods. // IFACEMETHODIMP GetActiveComposition(ITextRangeProvider** range) override; IFACEMETHODIMP GetConversionTarget(ITextRangeProvider** range) override; // ITextProvider supporting methods. static ITextRangeProvider* GetRangeFromChild( ui::AXPlatformNodeWin* ancestor, ui::AXPlatformNodeWin* descendant); // Create a dengerate text range at the start of the specified node. static ITextRangeProvider* CreateDegenerateRangeAtStart( ui::AXPlatformNodeWin* node); private: friend class AXPlatformNodeTextProviderTest; ui::AXPlatformNodeWin* owner() const; HRESULT GetTextRangeProviderFromActiveComposition(ITextRangeProvider** range); Microsoft::WRL::ComPtr<ui::AXPlatformNodeWin> owner_; }; } // namespace ui #endif // UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_NODE_TEXTPROVIDER_WIN_H_
engine/third_party/accessibility/ax/platform/ax_platform_node_textprovider_win.h/0
{ "file_path": "engine/third_party/accessibility/ax/platform/ax_platform_node_textprovider_win.h", "repo_id": "engine", "token_count": 902 }
466
// Copyright 2015 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. #include "ax_unique_id.h" #include <memory> #include "gtest/gtest.h" namespace ui { TEST(AXPlatformUniqueIdTest, IdsAreUnique) { AXUniqueId id1, id2; EXPECT_FALSE(id1 == id2); EXPECT_GT(id2.Get(), id1.Get()); } static const int32_t kMaxId = 100; class AXTestSmallBankUniqueId : public AXUniqueId { public: AXTestSmallBankUniqueId(); ~AXTestSmallBankUniqueId() override; private: friend class AXUniqueId; BASE_DISALLOW_COPY_AND_ASSIGN(AXTestSmallBankUniqueId); }; AXTestSmallBankUniqueId::AXTestSmallBankUniqueId() : AXUniqueId(kMaxId) {} AXTestSmallBankUniqueId::~AXTestSmallBankUniqueId() = default; TEST(AXPlatformUniqueIdTest, UnassignedIdsAreReused) { // Create a bank of ids that uses up all available ids. // Then remove an id and replace with a new one. Since it's the only // slot available, the id will end up having the same value, rather than // starting over at 1. std::unique_ptr<AXTestSmallBankUniqueId> ids[kMaxId]; for (int i = 0; i < kMaxId; i++) { ids[i] = std::make_unique<AXTestSmallBankUniqueId>(); } static int kIdToReplace = 10; int32_t expected_id = ids[kIdToReplace]->Get(); // Delete one of the ids and replace with a new one. ids[kIdToReplace] = nullptr; ids[kIdToReplace] = std::make_unique<AXTestSmallBankUniqueId>(); // Expect that the original Id gets reused. EXPECT_EQ(ids[kIdToReplace]->Get(), expected_id); } TEST(AXPlatformUniqueIdTest, DoesCreateCorrectId) { constexpr int kLargerThanMaxId = kMaxId * 2; std::unique_ptr<AXUniqueId> ids[kLargerThanMaxId]; // Creates and releases to fill up the internal static counter. for (int i = 0; i < kLargerThanMaxId; i++) { ids[i] = std::make_unique<AXUniqueId>(); } for (int i = 0; i < kLargerThanMaxId; i++) { ids[i].reset(nullptr); } // Creates an unique id whose max value is less than the internal // static counter. std::unique_ptr<AXTestSmallBankUniqueId> unique_id = std::make_unique<AXTestSmallBankUniqueId>(); EXPECT_LE(unique_id->Get(), kMaxId); } } // namespace ui
engine/third_party/accessibility/ax/platform/ax_unique_id_unittest.cc/0
{ "file_path": "engine/third_party/accessibility/ax/platform/ax_unique_id_unittest.cc", "repo_id": "engine", "token_count": 801 }
467
// 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 BASE_COLOR_UTILS_H_ #define BASE_COLOR_UTILS_H_ /** Returns alpha byte from color value. */ #define ColorGetA(color) (((color) >> 24) & 0xFF) /** Returns red component of color, from zero to 255. */ #define ColorGetR(color) (((color) >> 16) & 0xFF) /** Returns green component of color, from zero to 255. */ #define ColorGetG(color) (((color) >> 8) & 0xFF) /** Returns blue component of color, from zero to 255. */ #define ColorGetB(color) (((color) >> 0) & 0xFF) #endif // BASE_COLOR_UTILS_H_
engine/third_party/accessibility/base/color_utils.h/0
{ "file_path": "engine/third_party/accessibility/base/color_utils.h", "repo_id": "engine", "token_count": 227 }
468
// 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. #ifndef BASE_NUMERICS_SAFE_CONVERSIONS_H_ #define BASE_NUMERICS_SAFE_CONVERSIONS_H_ #include <cmath> #include <cstddef> #include <limits> #include <type_traits> #include "base/numerics/safe_conversions_impl.h" #if !defined(__native_client__) && (defined(__ARMEL__) || defined(__arch64__)) #include "base/numerics/safe_conversions_arm_impl.h" #define BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS (1) #else #define BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS (0) #endif #if !BASE_NUMERICS_DISABLE_OSTREAM_OPERATORS #include <ostream> #endif namespace base { namespace internal { #if !BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS template <typename Dst, typename Src> struct SaturateFastAsmOp { static constexpr bool is_supported = false; static constexpr Dst Do(Src) { // Force a compile failure if instantiated. return CheckOnFailure::template HandleFailure<Dst>(); } }; #endif // BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS #undef BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS // The following special case a few specific integer conversions where we can // eke out better performance than range checking. template <typename Dst, typename Src, typename Enable = void> struct IsValueInRangeFastOp { static constexpr bool is_supported = false; static constexpr bool Do(Src value) { // Force a compile failure if instantiated. return CheckOnFailure::template HandleFailure<bool>(); } }; // Signed to signed range comparison. template <typename Dst, typename Src> struct IsValueInRangeFastOp< Dst, Src, typename std::enable_if< std::is_integral<Dst>::value && std::is_integral<Src>::value && std::is_signed<Dst>::value && std::is_signed<Src>::value && !IsTypeInRangeForNumericType<Dst, Src>::value>::type> { static constexpr bool is_supported = true; static constexpr bool Do(Src value) { // Just downcast to the smaller type, sign extend it back to the original // type, and then see if it matches the original value. return value == static_cast<Dst>(value); } }; // Signed to unsigned range comparison. template <typename Dst, typename Src> struct IsValueInRangeFastOp< Dst, Src, typename std::enable_if< std::is_integral<Dst>::value && std::is_integral<Src>::value && !std::is_signed<Dst>::value && std::is_signed<Src>::value && !IsTypeInRangeForNumericType<Dst, Src>::value>::type> { static constexpr bool is_supported = true; static constexpr bool Do(Src value) { // We cast a signed as unsigned to overflow negative values to the top, // then compare against whichever maximum is smaller, as our upper bound. return as_unsigned(value) <= as_unsigned(CommonMax<Src, Dst>()); } }; // Convenience function that returns true if the supplied value is in range // for the destination type. template <typename Dst, typename Src> constexpr bool IsValueInRangeForNumericType(Src value) { using SrcType = typename internal::UnderlyingType<Src>::type; return internal::IsValueInRangeFastOp<Dst, SrcType>::is_supported ? internal::IsValueInRangeFastOp<Dst, SrcType>::Do( static_cast<SrcType>(value)) : internal::DstRangeRelationToSrcRange<Dst>( static_cast<SrcType>(value)) .IsValid(); } // checked_cast<> is analogous to static_cast<> for numeric types, // except that it CHECKs that the specified numeric conversion will not // overflow or underflow. NaN source will always trigger a CHECK. template <typename Dst, class CheckHandler = internal::CheckOnFailure, typename Src> constexpr Dst checked_cast(Src value) { // This throws a compile-time error on evaluating the constexpr if it can be // determined at compile-time as failing, otherwise it will CHECK at runtime. using SrcType = typename internal::UnderlyingType<Src>::type; return BASE_NUMERICS_LIKELY((IsValueInRangeForNumericType<Dst>(value))) ? static_cast<Dst>(static_cast<SrcType>(value)) : CheckHandler::template HandleFailure<Dst>(); } // Default boundaries for integral/float: max/infinity, lowest/-infinity, 0/NaN. // You may provide your own limits (e.g. to saturated_cast) so long as you // implement all of the static constexpr member functions in the class below. template <typename T> struct SaturationDefaultLimits : public std::numeric_limits<T> { static constexpr T NaN() { return std::numeric_limits<T>::has_quiet_NaN ? std::numeric_limits<T>::quiet_NaN() : T(); } using std::numeric_limits<T>::max; static constexpr T Overflow() { return std::numeric_limits<T>::has_infinity ? std::numeric_limits<T>::infinity() : std::numeric_limits<T>::max(); } using std::numeric_limits<T>::lowest; static constexpr T Underflow() { return std::numeric_limits<T>::has_infinity ? std::numeric_limits<T>::infinity() * -1 : std::numeric_limits<T>::lowest(); } }; template <typename Dst, template <typename> class S, typename Src> constexpr Dst saturated_cast_impl(Src value, RangeCheck constraint) { // For some reason clang generates much better code when the branch is // structured exactly this way, rather than a sequence of checks. return !constraint.IsOverflowFlagSet() ? (!constraint.IsUnderflowFlagSet() ? static_cast<Dst>(value) : S<Dst>::Underflow()) // Skip this check for integral Src, which cannot be NaN. : (std::is_integral<Src>::value || !constraint.IsUnderflowFlagSet() ? S<Dst>::Overflow() : S<Dst>::NaN()); } // We can reduce the number of conditions and get slightly better performance // for normal signed and unsigned integer ranges. And in the specific case of // Arm, we can use the optimized saturation instructions. template <typename Dst, typename Src, typename Enable = void> struct SaturateFastOp { static constexpr bool is_supported = false; static constexpr Dst Do(Src value) { // Force a compile failure if instantiated. return CheckOnFailure::template HandleFailure<Dst>(); } }; template <typename Dst, typename Src> struct SaturateFastOp< Dst, Src, typename std::enable_if<std::is_integral<Src>::value && std::is_integral<Dst>::value && SaturateFastAsmOp<Dst, Src>::is_supported>::type> { static constexpr bool is_supported = true; static constexpr Dst Do(Src value) { return SaturateFastAsmOp<Dst, Src>::Do(value); } }; template <typename Dst, typename Src> struct SaturateFastOp< Dst, Src, typename std::enable_if<std::is_integral<Src>::value && std::is_integral<Dst>::value && !SaturateFastAsmOp<Dst, Src>::is_supported>::type> { static constexpr bool is_supported = true; static constexpr Dst Do(Src value) { // The exact order of the following is structured to hit the correct // optimization heuristics across compilers. Do not change without // checking the emitted code. const Dst saturated = CommonMaxOrMin<Dst, Src>( IsMaxInRangeForNumericType<Dst, Src>() || (!IsMinInRangeForNumericType<Dst, Src>() && IsValueNegative(value))); return BASE_NUMERICS_LIKELY(IsValueInRangeForNumericType<Dst>(value)) ? static_cast<Dst>(value) : saturated; } }; // saturated_cast<> is analogous to static_cast<> for numeric types, except // that the specified numeric conversion will saturate by default rather than // overflow or underflow, and NaN assignment to an integral will return 0. // All boundary condition behaviors can be overridden with a custom handler. template <typename Dst, template <typename> class SaturationHandler = SaturationDefaultLimits, typename Src> constexpr Dst saturated_cast(Src value) { using SrcType = typename UnderlyingType<Src>::type; return !IsCompileTimeConstant(value) && SaturateFastOp<Dst, SrcType>::is_supported && std::is_same<SaturationHandler<Dst>, SaturationDefaultLimits<Dst>>::value ? SaturateFastOp<Dst, SrcType>::Do(static_cast<SrcType>(value)) : saturated_cast_impl<Dst, SaturationHandler, SrcType>( static_cast<SrcType>(value), DstRangeRelationToSrcRange<Dst, SaturationHandler, SrcType>( static_cast<SrcType>(value))); } // strict_cast<> is analogous to static_cast<> for numeric types, except that // it will cause a compile failure if the destination type is not large enough // to contain any value in the source type. It performs no runtime checking. template <typename Dst, typename Src> constexpr Dst strict_cast(Src value) { using SrcType = typename UnderlyingType<Src>::type; static_assert(UnderlyingType<Src>::is_numeric, "Argument must be numeric."); static_assert(std::is_arithmetic<Dst>::value, "Result must be numeric."); // If you got here from a compiler error, it's because you tried to assign // from a source type to a destination type that has insufficient range. // The solution may be to change the destination type you're assigning to, // and use one large enough to represent the source. // Alternatively, you may be better served with the checked_cast<> or // saturated_cast<> template functions for your particular use case. static_assert(StaticDstRangeRelationToSrcRange<Dst, SrcType>::value == NUMERIC_RANGE_CONTAINED, "The source type is out of range for the destination type. " "Please see strict_cast<> comments for more information."); return static_cast<Dst>(static_cast<SrcType>(value)); } // Some wrappers to statically check that a type is in range. template <typename Dst, typename Src, class Enable = void> struct IsNumericRangeContained { static constexpr bool value = false; }; template <typename Dst, typename Src> struct IsNumericRangeContained< Dst, Src, typename std::enable_if<ArithmeticOrUnderlyingEnum<Dst>::value && ArithmeticOrUnderlyingEnum<Src>::value>::type> { static constexpr bool value = StaticDstRangeRelationToSrcRange<Dst, Src>::value == NUMERIC_RANGE_CONTAINED; }; // StrictNumeric implements compile time range checking between numeric types by // wrapping assignment operations in a strict_cast. This class is intended to be // used for function arguments and return types, to ensure the destination type // can always contain the source type. This is essentially the same as enforcing // -Wconversion in gcc and C4302 warnings on MSVC, but it can be applied // incrementally at API boundaries, making it easier to convert code so that it // compiles cleanly with truncation warnings enabled. // This template should introduce no runtime overhead, but it also provides no // runtime checking of any of the associated mathematical operations. Use // CheckedNumeric for runtime range checks of the actual value being assigned. template <typename T> class StrictNumeric { public: using type = T; constexpr StrictNumeric() : value_(0) {} // Copy constructor. template <typename Src> constexpr StrictNumeric(const StrictNumeric<Src>& rhs) : value_(strict_cast<T>(rhs.value_)) {} // This is not an explicit constructor because we implicitly upgrade regular // numerics to StrictNumerics to make them easier to use. template <typename Src> constexpr StrictNumeric(Src value) // NOLINT(runtime/explicit) : value_(strict_cast<T>(value)) {} // If you got here from a compiler error, it's because you tried to assign // from a source type to a destination type that has insufficient range. // The solution may be to change the destination type you're assigning to, // and use one large enough to represent the source. // If you're assigning from a CheckedNumeric<> class, you may be able to use // the AssignIfValid() member function, specify a narrower destination type to // the member value functions (e.g. val.template ValueOrDie<Dst>()), use one // of the value helper functions (e.g. ValueOrDieForType<Dst>(val)). // If you've encountered an _ambiguous overload_ you can use a static_cast<> // to explicitly cast the result to the destination type. // If none of that works, you may be better served with the checked_cast<> or // saturated_cast<> template functions for your particular use case. template <typename Dst, typename std::enable_if< IsNumericRangeContained<Dst, T>::value>::type* = nullptr> constexpr operator Dst() const { return static_cast<typename ArithmeticOrUnderlyingEnum<Dst>::type>(value_); } private: const T value_; }; // Convience wrapper returns a StrictNumeric from the provided arithmetic type. template <typename T> constexpr StrictNumeric<typename UnderlyingType<T>::type> MakeStrictNum( const T value) { return value; } #if !BASE_NUMERICS_DISABLE_OSTREAM_OPERATORS // Overload the ostream output operator to make logging work nicely. template <typename T> std::ostream& operator<<(std::ostream& os, const StrictNumeric<T>& value) { os << static_cast<T>(value); return os; } #endif #define BASE_NUMERIC_COMPARISON_OPERATORS(CLASS, NAME, OP) \ template <typename L, typename R, \ typename std::enable_if< \ internal::Is##CLASS##Op<L, R>::value>::type* = nullptr> \ constexpr bool operator OP(const L lhs, const R rhs) { \ return SafeCompare<NAME, typename UnderlyingType<L>::type, \ typename UnderlyingType<R>::type>(lhs, rhs); \ } BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsLess, <) BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsLessOrEqual, <=) BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsGreater, >) BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsGreaterOrEqual, >=) BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsEqual, ==) BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsNotEqual, !=) } // namespace internal using internal::as_signed; using internal::as_unsigned; using internal::checked_cast; using internal::IsTypeInRangeForNumericType; using internal::IsValueInRangeForNumericType; using internal::IsValueNegative; using internal::MakeStrictNum; using internal::SafeUnsignedAbs; using internal::saturated_cast; using internal::strict_cast; using internal::StrictNumeric; // Explicitly make a shorter size_t alias for convenience. using SizeT = StrictNumeric<size_t>; // floating -> integral conversions that saturate and thus can actually return // an integral type. In most cases, these should be preferred over the std:: // versions. template <typename Dst = int, typename Src, typename = std::enable_if_t<std::is_integral<Dst>::value && std::is_floating_point<Src>::value>> Dst ClampFloor(Src value) { return saturated_cast<Dst>(std::floor(value)); } template <typename Dst = int, typename Src, typename = std::enable_if_t<std::is_integral<Dst>::value && std::is_floating_point<Src>::value>> Dst ClampCeil(Src value) { return saturated_cast<Dst>(std::ceil(value)); } template <typename Dst = int, typename Src, typename = std::enable_if_t<std::is_integral<Dst>::value && std::is_floating_point<Src>::value>> Dst ClampRound(Src value) { const Src rounded = (value >= 0.0f) ? std::floor(value + 0.5f) : std::ceil(value - 0.5f); return saturated_cast<Dst>(rounded); } } // namespace base #endif // BASE_NUMERICS_SAFE_CONVERSIONS_H_
engine/third_party/accessibility/base/numerics/safe_conversions.h/0
{ "file_path": "engine/third_party/accessibility/base/numerics/safe_conversions.h", "repo_id": "engine", "token_count": 6004 }
469
// Copyright (c) 2011 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. #ifndef UI_BASE_WIN_ATL_MODULE_H_ #define UI_BASE_WIN_ATL_MODULE_H_ namespace ui { namespace win { // Ensure that we have exactly one ATL module registered. It's safe to // call this more than once. ATL functions will crash if there's no // ATL module registered, or if you try to register two of them, so // dynamically registering one if needed makes it much easier for us // to support different build configurations like multi-dll without // worrying about which side of a module boundary each ATL module object // belongs on. // // This function must be implemented in this header file rather than a // source file so that it's inlined into the module where it's included, // rather than in the "ui" module. inline void CreateATLModuleIfNeeded() { if (_pAtlModule == NULL) { // This creates the module and automatically updates _pAtlModule. new CComModule; } } } // namespace win } // namespace ui #endif // UI_BASE_WIN_ATL_MODULE_H_
engine/third_party/accessibility/base/win/atl_module.h/0
{ "file_path": "engine/third_party/accessibility/base/win/atl_module.h", "repo_id": "engine", "token_count": 323 }
470
// Copyright (c) 2011 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. #include <wrl/client.h> #include <wrl/implements.h> #include <cstdint> #include <utility> #include "base/win/dispatch_stub.h" #include "base/win/scoped_variant.h" #include "gtest/gtest.h" using base::win::test::DispatchStub; namespace base { namespace win { namespace { constexpr wchar_t kTestString[] = L"Test string for BSTRs."; void InitializeVariantWithBstr(VARIANT* var) { if (!var) { ADD_FAILURE() << "|var| cannot be null."; return; } var->vt = VT_BSTR; V_BSTR(var) = ::SysAllocString(kTestString); } void ExpectRefCount(ULONG expected_refcount, IUnknown* object) { // In general, code should not check the values of AddRef() and Release(). // However, tests need to validate that ScopedVariant safely owns a COM object // so they are checked for this unit test. EXPECT_EQ(expected_refcount + 1, object->AddRef()); EXPECT_EQ(expected_refcount, object->Release()); } void ExpectVariantType(VARENUM var_type, const ScopedVariant& var) { EXPECT_EQ(var_type, var.type()); EXPECT_EQ(var_type, V_VT(var.ptr())); } } // namespace TEST(ScopedVariantTest, Empty) { ScopedVariant var; ExpectVariantType(VT_EMPTY, var); } TEST(ScopedVariantTest, ConstructBstr) { ScopedVariant var(kTestString); ExpectVariantType(VT_BSTR, var); EXPECT_STREQ(kTestString, V_BSTR(var.ptr())); } TEST(ScopedVariantTest, SetBstr) { ScopedVariant var; var.Set(kTestString); ExpectVariantType(VT_BSTR, var); EXPECT_STREQ(kTestString, V_BSTR(var.ptr())); } TEST(ScopedVariantTest, ReleaseBstr) { ScopedVariant var; var.Set(kTestString); VARIANT released_variant = var.Release(); ExpectVariantType(VT_EMPTY, var); EXPECT_EQ(VT_BSTR, V_VT(&released_variant)); EXPECT_STREQ(kTestString, V_BSTR(&released_variant)); ::VariantClear(&released_variant); } TEST(ScopedVariantTest, ResetToEmptyBstr) { ScopedVariant var(kTestString); ExpectVariantType(VT_BSTR, var); var.Reset(); ExpectVariantType(VT_EMPTY, var); } TEST(ScopedVariantTest, TakeOwnershipBstr) { VARIANT bstr_variant; bstr_variant.vt = VT_BSTR; bstr_variant.bstrVal = ::SysAllocString(kTestString); ScopedVariant var; var.Reset(bstr_variant); ExpectVariantType(VT_BSTR, var); EXPECT_EQ(bstr_variant.bstrVal, V_BSTR(var.ptr())); } TEST(ScopedVariantTest, SwapBstr) { ScopedVariant from(kTestString); ScopedVariant to; to.Swap(from); ExpectVariantType(VT_EMPTY, from); ExpectVariantType(VT_BSTR, to); EXPECT_STREQ(kTestString, V_BSTR(to.ptr())); } TEST(ScopedVariantTest, CompareBstr) { ScopedVariant var_bstr1; InitializeVariantWithBstr(var_bstr1.Receive()); ScopedVariant var_bstr2(V_BSTR(var_bstr1.ptr())); EXPECT_EQ(0, var_bstr1.Compare(var_bstr2)); var_bstr2.Reset(); EXPECT_NE(0, var_bstr1.Compare(var_bstr2)); } TEST(ScopedVariantTest, ReceiveAndCopyBstr) { ScopedVariant var_bstr1; InitializeVariantWithBstr(var_bstr1.Receive()); ScopedVariant var_bstr2; var_bstr2.Reset(var_bstr1.Copy()); EXPECT_EQ(0, var_bstr1.Compare(var_bstr2)); } TEST(ScopedVariantTest, SetBstrFromBstrVariant) { ScopedVariant var_bstr1; InitializeVariantWithBstr(var_bstr1.Receive()); ScopedVariant var_bstr2; var_bstr2.Set(V_BSTR(var_bstr1.ptr())); EXPECT_EQ(0, var_bstr1.Compare(var_bstr2)); } TEST(ScopedVariantTest, SetDate) { ScopedVariant var; SYSTEMTIME sys_time; ::GetSystemTime(&sys_time); DATE date; ::SystemTimeToVariantTime(&sys_time, &date); var.SetDate(date); ExpectVariantType(VT_DATE, var); EXPECT_EQ(date, V_DATE(var.ptr())); } TEST(ScopedVariantTest, SetSigned1Byte) { ScopedVariant var; var.Set(static_cast<int8_t>('v')); ExpectVariantType(VT_I1, var); EXPECT_EQ('v', V_I1(var.ptr())); } TEST(ScopedVariantTest, SetSigned2Byte) { ScopedVariant var; var.Set(static_cast<short>(123)); ExpectVariantType(VT_I2, var); EXPECT_EQ(123, V_I2(var.ptr())); } TEST(ScopedVariantTest, SetSigned4Byte) { ScopedVariant var; var.Set(123); ExpectVariantType(VT_I4, var); EXPECT_EQ(123, V_I4(var.ptr())); } TEST(ScopedVariantTest, SetSigned8Byte) { ScopedVariant var; var.Set(static_cast<int64_t>(123)); ExpectVariantType(VT_I8, var); EXPECT_EQ(123, V_I8(var.ptr())); } TEST(ScopedVariantTest, SetUnsigned1Byte) { ScopedVariant var; var.Set(static_cast<uint8_t>(123)); ExpectVariantType(VT_UI1, var); EXPECT_EQ(123u, V_UI1(var.ptr())); } TEST(ScopedVariantTest, SetUnsigned2Byte) { ScopedVariant var; var.Set(static_cast<unsigned short>(123)); ExpectVariantType(VT_UI2, var); EXPECT_EQ(123u, V_UI2(var.ptr())); } TEST(ScopedVariantTest, SetUnsigned4Byte) { ScopedVariant var; var.Set(static_cast<uint32_t>(123)); ExpectVariantType(VT_UI4, var); EXPECT_EQ(123u, V_UI4(var.ptr())); } TEST(ScopedVariantTest, SetUnsigned8Byte) { ScopedVariant var; var.Set(static_cast<uint64_t>(123)); ExpectVariantType(VT_UI8, var); EXPECT_EQ(123u, V_UI8(var.ptr())); } TEST(ScopedVariantTest, SetReal4Byte) { ScopedVariant var; var.Set(123.123f); ExpectVariantType(VT_R4, var); EXPECT_EQ(123.123f, V_R4(var.ptr())); } TEST(ScopedVariantTest, SetReal8Byte) { ScopedVariant var; var.Set(static_cast<double>(123.123)); ExpectVariantType(VT_R8, var); EXPECT_EQ(123.123, V_R8(var.ptr())); } TEST(ScopedVariantTest, SetBooleanTrue) { ScopedVariant var; var.Set(true); ExpectVariantType(VT_BOOL, var); EXPECT_EQ(VARIANT_TRUE, V_BOOL(var.ptr())); } TEST(ScopedVariantTest, SetBooleanFalse) { ScopedVariant var; var.Set(false); ExpectVariantType(VT_BOOL, var); EXPECT_EQ(VARIANT_FALSE, V_BOOL(var.ptr())); } TEST(ScopedVariantTest, SetComIDispatch) { ScopedVariant var; Microsoft::WRL::ComPtr<IDispatch> dispatch_stub = Microsoft::WRL::Make<DispatchStub>(); ExpectRefCount(1U, dispatch_stub.Get()); var.Set(dispatch_stub.Get()); ExpectVariantType(VT_DISPATCH, var); EXPECT_EQ(dispatch_stub.Get(), V_DISPATCH(var.ptr())); ExpectRefCount(2U, dispatch_stub.Get()); var.Reset(); ExpectRefCount(1U, dispatch_stub.Get()); } TEST(ScopedVariantTest, SetComNullIDispatch) { ScopedVariant var; var.Set(static_cast<IDispatch*>(nullptr)); ExpectVariantType(VT_DISPATCH, var); EXPECT_EQ(nullptr, V_DISPATCH(var.ptr())); } TEST(ScopedVariantTest, SetComIUnknown) { ScopedVariant var; Microsoft::WRL::ComPtr<IUnknown> unknown_stub = Microsoft::WRL::Make<DispatchStub>(); ExpectRefCount(1U, unknown_stub.Get()); var.Set(unknown_stub.Get()); ExpectVariantType(VT_UNKNOWN, var); EXPECT_EQ(unknown_stub.Get(), V_UNKNOWN(var.ptr())); ExpectRefCount(2U, unknown_stub.Get()); var.Reset(); ExpectRefCount(1U, unknown_stub.Get()); } TEST(ScopedVariantTest, SetComNullIUnknown) { ScopedVariant var; var.Set(static_cast<IUnknown*>(nullptr)); ExpectVariantType(VT_UNKNOWN, var); EXPECT_EQ(nullptr, V_UNKNOWN(var.ptr())); } TEST(ScopedVariant, ScopedComIDispatchConstructor) { Microsoft::WRL::ComPtr<IDispatch> dispatch_stub = Microsoft::WRL::Make<DispatchStub>(); { ScopedVariant var(dispatch_stub.Get()); ExpectVariantType(VT_DISPATCH, var); EXPECT_EQ(dispatch_stub.Get(), V_DISPATCH(var.ptr())); ExpectRefCount(2U, dispatch_stub.Get()); } ExpectRefCount(1U, dispatch_stub.Get()); } TEST(ScopedVariant, ScopedComIDispatchMove) { Microsoft::WRL::ComPtr<IDispatch> dispatch_stub = Microsoft::WRL::Make<DispatchStub>(); { ScopedVariant var1(dispatch_stub.Get()); ExpectRefCount(2U, dispatch_stub.Get()); ScopedVariant var2(std::move(var1)); ExpectRefCount(2U, dispatch_stub.Get()); ScopedVariant var3; var3 = std::move(var2); ExpectRefCount(2U, dispatch_stub.Get()); } ExpectRefCount(1U, dispatch_stub.Get()); } TEST(ScopedVariant, ScopedComIDispatchCopy) { Microsoft::WRL::ComPtr<IDispatch> dispatch_stub = Microsoft::WRL::Make<DispatchStub>(); { ScopedVariant var1(dispatch_stub.Get()); ExpectRefCount(2U, dispatch_stub.Get()); ScopedVariant var2(static_cast<const VARIANT&>(var1)); ExpectRefCount(3U, dispatch_stub.Get()); ScopedVariant var3; var3 = static_cast<const VARIANT&>(var2); ExpectRefCount(4U, dispatch_stub.Get()); } ExpectRefCount(1U, dispatch_stub.Get()); } TEST(ScopedVariant, ScopedComIUnknownConstructor) { Microsoft::WRL::ComPtr<IUnknown> unknown_stub = Microsoft::WRL::Make<DispatchStub>(); { ScopedVariant unk_var(unknown_stub.Get()); ExpectVariantType(VT_UNKNOWN, unk_var); EXPECT_EQ(unknown_stub.Get(), V_UNKNOWN(unk_var.ptr())); ExpectRefCount(2U, unknown_stub.Get()); } ExpectRefCount(1U, unknown_stub.Get()); } TEST(ScopedVariant, ScopedComIUnknownWithRawVariant) { ScopedVariant var; Microsoft::WRL::ComPtr<IUnknown> unknown_stub = Microsoft::WRL::Make<DispatchStub>(); VARIANT raw; raw.vt = VT_UNKNOWN; raw.punkVal = unknown_stub.Get(); ExpectRefCount(1U, unknown_stub.Get()); var.Set(raw); ExpectRefCount(2U, unknown_stub.Get()); var.Reset(); ExpectRefCount(1U, unknown_stub.Get()); } TEST(ScopedVariant, SetSafeArray) { SAFEARRAY* sa = ::SafeArrayCreateVector(VT_UI1, 0, 100); ASSERT_TRUE(sa); ScopedVariant var; var.Set(sa); EXPECT_TRUE(ScopedVariant::IsLeakableVarType(var.type())); ExpectVariantType(static_cast<VARENUM>(VT_ARRAY | VT_UI1), var); EXPECT_EQ(sa, V_ARRAY(var.ptr())); // The array is destroyed in the destructor of var. sa = nullptr; } TEST(ScopedVariant, SetNullSafeArray) { ScopedVariant var; var.Set(static_cast<SAFEARRAY*>(nullptr)); ExpectVariantType(VT_EMPTY, var); } } // namespace win } // namespace base
engine/third_party/accessibility/base/win/scoped_variant_unittest.cc/0
{ "file_path": "engine/third_party/accessibility/base/win/scoped_variant_unittest.cc", "repo_id": "engine", "token_count": 4068 }
471
// Copyright (c) 2012 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. #include "point_f.h" #include "base/string_utils.h" namespace gfx { void PointF::SetToMin(const PointF& other) { x_ = x_ <= other.x_ ? x_ : other.x_; y_ = y_ <= other.y_ ? y_ : other.y_; } void PointF::SetToMax(const PointF& other) { x_ = x_ >= other.x_ ? x_ : other.x_; y_ = y_ >= other.y_ ? y_ : other.y_; } std::string PointF::ToString() const { return base::StringPrintf("%f,%f", x(), y()); } PointF ScalePoint(const PointF& p, float x_scale, float y_scale) { PointF scaled_p(p); scaled_p.Scale(x_scale, y_scale); return scaled_p; } } // namespace gfx
engine/third_party/accessibility/gfx/geometry/point_f.cc/0
{ "file_path": "engine/third_party/accessibility/gfx/geometry/point_f.cc", "repo_id": "engine", "token_count": 298 }
472
// Copyright (c) 2012 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. #include "size.h" #include "gtest/gtest.h" #include "size_conversions.h" #include "size_f.h" namespace gfx { namespace { static constexpr float kTrivial = 8.f * std::numeric_limits<float>::epsilon(); int TestSizeF(const SizeF& s) { return s.width(); } } // namespace TEST(SizeTest, ToSizeF) { // Check that explicit conversion from integer to float compiles. Size a(10, 20); float width = TestSizeF(gfx::SizeF(a)); EXPECT_EQ(width, a.width()); SizeF b(10, 20); EXPECT_EQ(b, gfx::SizeF(a)); } TEST(SizeTest, ToFlooredSize) { EXPECT_EQ(Size(0, 0), ToFlooredSize(SizeF(0, 0))); EXPECT_EQ(Size(0, 0), ToFlooredSize(SizeF(0.0001f, 0.0001f))); EXPECT_EQ(Size(0, 0), ToFlooredSize(SizeF(0.4999f, 0.4999f))); EXPECT_EQ(Size(0, 0), ToFlooredSize(SizeF(0.5f, 0.5f))); EXPECT_EQ(Size(0, 0), ToFlooredSize(SizeF(0.9999f, 0.9999f))); EXPECT_EQ(Size(10, 10), ToFlooredSize(SizeF(10, 10))); EXPECT_EQ(Size(10, 10), ToFlooredSize(SizeF(10.0001f, 10.0001f))); EXPECT_EQ(Size(10, 10), ToFlooredSize(SizeF(10.4999f, 10.4999f))); EXPECT_EQ(Size(10, 10), ToFlooredSize(SizeF(10.5f, 10.5f))); EXPECT_EQ(Size(10, 10), ToFlooredSize(SizeF(10.9999f, 10.9999f))); } TEST(SizeTest, ToCeiledSize) { EXPECT_EQ(Size(0, 0), ToCeiledSize(SizeF(0, 0))); EXPECT_EQ(Size(1, 1), ToCeiledSize(SizeF(0.0001f, 0.0001f))); EXPECT_EQ(Size(1, 1), ToCeiledSize(SizeF(0.4999f, 0.4999f))); EXPECT_EQ(Size(1, 1), ToCeiledSize(SizeF(0.5f, 0.5f))); EXPECT_EQ(Size(1, 1), ToCeiledSize(SizeF(0.9999f, 0.9999f))); EXPECT_EQ(Size(10, 10), ToCeiledSize(SizeF(10, 10))); EXPECT_EQ(Size(11, 11), ToCeiledSize(SizeF(10.0001f, 10.0001f))); EXPECT_EQ(Size(11, 11), ToCeiledSize(SizeF(10.4999f, 10.4999f))); EXPECT_EQ(Size(11, 11), ToCeiledSize(SizeF(10.5f, 10.5f))); EXPECT_EQ(Size(11, 11), ToCeiledSize(SizeF(10.9999f, 10.9999f))); } TEST(SizeTest, ToRoundedSize) { EXPECT_EQ(Size(0, 0), ToRoundedSize(SizeF(0, 0))); EXPECT_EQ(Size(0, 0), ToRoundedSize(SizeF(0.0001f, 0.0001f))); EXPECT_EQ(Size(0, 0), ToRoundedSize(SizeF(0.4999f, 0.4999f))); EXPECT_EQ(Size(1, 1), ToRoundedSize(SizeF(0.5f, 0.5f))); EXPECT_EQ(Size(1, 1), ToRoundedSize(SizeF(0.9999f, 0.9999f))); EXPECT_EQ(Size(10, 10), ToRoundedSize(SizeF(10, 10))); EXPECT_EQ(Size(10, 10), ToRoundedSize(SizeF(10.0001f, 10.0001f))); EXPECT_EQ(Size(10, 10), ToRoundedSize(SizeF(10.4999f, 10.4999f))); EXPECT_EQ(Size(11, 11), ToRoundedSize(SizeF(10.5f, 10.5f))); EXPECT_EQ(Size(11, 11), ToRoundedSize(SizeF(10.9999f, 10.9999f))); } TEST(SizeTest, ClampSize) { Size a; a = Size(3, 5); EXPECT_EQ(Size(3, 5).ToString(), a.ToString()); a.SetToMax(Size(2, 4)); EXPECT_EQ(Size(3, 5).ToString(), a.ToString()); a.SetToMax(Size(3, 5)); EXPECT_EQ(Size(3, 5).ToString(), a.ToString()); a.SetToMax(Size(4, 2)); EXPECT_EQ(Size(4, 5).ToString(), a.ToString()); a.SetToMax(Size(8, 10)); EXPECT_EQ(Size(8, 10).ToString(), a.ToString()); a.SetToMin(Size(9, 11)); EXPECT_EQ(Size(8, 10).ToString(), a.ToString()); a.SetToMin(Size(8, 10)); EXPECT_EQ(Size(8, 10).ToString(), a.ToString()); a.SetToMin(Size(11, 9)); EXPECT_EQ(Size(8, 9).ToString(), a.ToString()); a.SetToMin(Size(7, 11)); EXPECT_EQ(Size(7, 9).ToString(), a.ToString()); a.SetToMin(Size(3, 5)); EXPECT_EQ(Size(3, 5).ToString(), a.ToString()); } TEST(SizeTest, ClampSizeF) { SizeF a; a = SizeF(3.5f, 5.5f); EXPECT_EQ(SizeF(3.5f, 5.5f).ToString(), a.ToString()); a.SetToMax(SizeF(2.5f, 4.5f)); EXPECT_EQ(SizeF(3.5f, 5.5f).ToString(), a.ToString()); a.SetToMax(SizeF(3.5f, 5.5f)); EXPECT_EQ(SizeF(3.5f, 5.5f).ToString(), a.ToString()); a.SetToMax(SizeF(4.5f, 2.5f)); EXPECT_EQ(SizeF(4.5f, 5.5f).ToString(), a.ToString()); a.SetToMax(SizeF(8.5f, 10.5f)); EXPECT_EQ(SizeF(8.5f, 10.5f).ToString(), a.ToString()); a.SetToMin(SizeF(9.5f, 11.5f)); EXPECT_EQ(SizeF(8.5f, 10.5f).ToString(), a.ToString()); a.SetToMin(SizeF(8.5f, 10.5f)); EXPECT_EQ(SizeF(8.5f, 10.5f).ToString(), a.ToString()); a.SetToMin(SizeF(11.5f, 9.5f)); EXPECT_EQ(SizeF(8.5f, 9.5f).ToString(), a.ToString()); a.SetToMin(SizeF(7.5f, 11.5f)); EXPECT_EQ(SizeF(7.5f, 9.5f).ToString(), a.ToString()); a.SetToMin(SizeF(3.5f, 5.5f)); EXPECT_EQ(SizeF(3.5f, 5.5f).ToString(), a.ToString()); } TEST(SizeTest, Enlarge) { Size test(3, 4); test.Enlarge(5, -8); EXPECT_EQ(test, Size(8, -4)); } TEST(SizeTest, IntegerOverflow) { int int_max = std::numeric_limits<int>::max(); int int_min = std::numeric_limits<int>::min(); Size max_size(int_max, int_max); Size min_size(int_min, int_min); Size test; test = Size(); test.Enlarge(int_max, int_max); EXPECT_EQ(test, max_size); test = Size(); test.Enlarge(int_min, int_min); EXPECT_EQ(test, min_size); test = Size(10, 20); test.Enlarge(int_max, int_max); EXPECT_EQ(test, max_size); test = Size(-10, -20); test.Enlarge(int_min, int_min); EXPECT_EQ(test, min_size); } // This checks that we set IsEmpty appropriately. TEST(SizeTest, TrivialDimensionTests) { const float clearly_trivial = kTrivial / 2.f; const float massize_dimension = 4e13f; // First, using the constructor. EXPECT_TRUE(SizeF(clearly_trivial, 1.f).IsEmpty()); EXPECT_TRUE(SizeF(.01f, clearly_trivial).IsEmpty()); EXPECT_TRUE(SizeF(0.f, 0.f).IsEmpty()); EXPECT_FALSE(SizeF(.01f, .01f).IsEmpty()); // Then use the setter. SizeF test(2.f, 1.f); EXPECT_FALSE(test.IsEmpty()); test.SetSize(clearly_trivial, 1.f); EXPECT_TRUE(test.IsEmpty()); test.SetSize(.01f, clearly_trivial); EXPECT_TRUE(test.IsEmpty()); test.SetSize(0.f, 0.f); EXPECT_TRUE(test.IsEmpty()); test.SetSize(.01f, .01f); EXPECT_FALSE(test.IsEmpty()); // Now just one dimension at a time. test.set_width(clearly_trivial); EXPECT_TRUE(test.IsEmpty()); test.set_width(massize_dimension); test.set_height(clearly_trivial); EXPECT_TRUE(test.IsEmpty()); test.set_width(clearly_trivial); test.set_height(massize_dimension); EXPECT_TRUE(test.IsEmpty()); test.set_width(2.f); EXPECT_FALSE(test.IsEmpty()); } // These are the ramifications of the decision to keep the recorded size // at zero for trivial sizes. TEST(SizeTest, ClampsToZero) { const float clearly_trivial = kTrivial / 2.f; const float nearly_trivial = kTrivial * 1.5f; SizeF test(clearly_trivial, 1.f); EXPECT_FLOAT_EQ(0.f, test.width()); EXPECT_FLOAT_EQ(1.f, test.height()); test.SetSize(.01f, clearly_trivial); EXPECT_FLOAT_EQ(.01f, test.width()); EXPECT_FLOAT_EQ(0.f, test.height()); test.SetSize(nearly_trivial, nearly_trivial); EXPECT_FLOAT_EQ(nearly_trivial, test.width()); EXPECT_FLOAT_EQ(nearly_trivial, test.height()); test.Scale(0.5f); EXPECT_FLOAT_EQ(0.f, test.width()); EXPECT_FLOAT_EQ(0.f, test.height()); test.SetSize(0.f, 0.f); test.Enlarge(clearly_trivial, clearly_trivial); test.Enlarge(clearly_trivial, clearly_trivial); test.Enlarge(clearly_trivial, clearly_trivial); EXPECT_EQ(SizeF(0.f, 0.f), test); } // These make sure the constructor and setter have the same effect on the // boundary case. This claims to know the boundary, but not which way it goes. TEST(SizeTest, ConsistentClamping) { SizeF resized; resized.SetSize(kTrivial, 0.f); EXPECT_EQ(SizeF(kTrivial, 0.f), resized); resized.SetSize(0.f, kTrivial); EXPECT_EQ(SizeF(0.f, kTrivial), resized); } // Let's make sure we don't unexpectedly grow the struct by adding constants. // Also, if some platform packs floats inefficiently, it would be worth noting. TEST(SizeTest, StaysSmall) { EXPECT_EQ(2 * sizeof(float), sizeof(SizeF)); } TEST(SizeTest, OperatorAddSub) { Size lhs(100, 20); Size rhs(50, 10); lhs += rhs; EXPECT_EQ(Size(150, 30), lhs); lhs = Size(100, 20); EXPECT_EQ(Size(150, 30), lhs + rhs); lhs = Size(100, 20); lhs -= rhs; EXPECT_EQ(Size(50, 10), lhs); lhs = Size(100, 20); EXPECT_EQ(Size(50, 10), lhs - rhs); } TEST(SizeTest, OperatorAddOverflow) { int int_max = std::numeric_limits<int>::max(); Size lhs(int_max, int_max); Size rhs(int_max, int_max); EXPECT_EQ(Size(int_max, int_max), lhs + rhs); } TEST(SizeTest, OperatorSubClampAtZero) { Size lhs(10, 10); Size rhs(100, 100); EXPECT_EQ(Size(0, 0), lhs - rhs); lhs = Size(10, 10); rhs = Size(100, 100); lhs -= rhs; EXPECT_EQ(Size(0, 0), lhs); } TEST(SizeTest, OperatorCompare) { Size lhs(100, 20); Size rhs(50, 10); EXPECT_TRUE(lhs != rhs); EXPECT_FALSE(lhs == rhs); rhs = Size(100, 20); EXPECT_TRUE(lhs == rhs); EXPECT_FALSE(lhs != rhs); } } // namespace gfx
engine/third_party/accessibility/gfx/geometry/size_unittest.cc/0
{ "file_path": "engine/third_party/accessibility/gfx/geometry/size_unittest.cc", "repo_id": "engine", "token_count": 3987 }
473
// 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. #include "gfx/test/gfx_util.h" #include <iomanip> #include <sstream> #include <string> #include "gfx/geometry/point.h" #include "gfx/geometry/point_f.h" #include "gfx/geometry/rect.h" #include "gfx/geometry/rect_f.h" #include "gfx/geometry/size.h" #include "gfx/geometry/size_f.h" #include "gfx/geometry/vector2d.h" #include "gfx/geometry/vector2d_f.h" #include "gfx/transform.h" namespace gfx { namespace { bool FloatAlmostEqual(float a, float b) { // FloatLE is the gtest predicate for less than or almost equal to. return ::testing::FloatLE("a", "b", a, b) && ::testing::FloatLE("b", "a", b, a); } } // namespace ::testing::AssertionResult AssertPointFloatEqual(const char* lhs_expr, const char* rhs_expr, const PointF& lhs, const PointF& rhs) { if (FloatAlmostEqual(lhs.x(), rhs.x()) && FloatAlmostEqual(lhs.y(), rhs.y())) { return ::testing::AssertionSuccess(); } return ::testing::AssertionFailure() << "Value of: " << rhs_expr << "\n Actual: " << rhs.ToString() << "\nExpected: " << lhs_expr << "\nWhich is: " << lhs.ToString(); } ::testing::AssertionResult AssertRectFloatEqual(const char* lhs_expr, const char* rhs_expr, const RectF& lhs, const RectF& rhs) { if (FloatAlmostEqual(lhs.x(), rhs.x()) && FloatAlmostEqual(lhs.y(), rhs.y()) && FloatAlmostEqual(lhs.width(), rhs.width()) && FloatAlmostEqual(lhs.height(), rhs.height())) { return ::testing::AssertionSuccess(); } return ::testing::AssertionFailure() << "Value of: " << rhs_expr << "\n Actual: " << rhs.ToString() << "\nExpected: " << lhs_expr << "\nWhich is: " << lhs.ToString(); } ::testing::AssertionResult AssertSizeFFloatEqual(const char* lhs_expr, const char* rhs_expr, const SizeF& lhs, const SizeF& rhs) { if (FloatAlmostEqual(lhs.width(), rhs.width()) && FloatAlmostEqual(lhs.height(), rhs.height())) { return ::testing::AssertionSuccess(); } return ::testing::AssertionFailure() << "Value of: " << rhs_expr << "\n Actual: " << rhs.ToString() << "\nExpected: " << lhs_expr << "\nWhich is: " << lhs.ToString(); } void PrintTo(const Point& point, ::std::ostream* os) { *os << point.ToString(); } void PrintTo(const PointF& point, ::std::ostream* os) { *os << point.ToString(); } void PrintTo(const Rect& rect, ::std::ostream* os) { *os << rect.ToString(); } void PrintTo(const RectF& rect, ::std::ostream* os) { *os << rect.ToString(); } void PrintTo(const Size& size, ::std::ostream* os) { *os << size.ToString(); } void PrintTo(const SizeF& size, ::std::ostream* os) { *os << size.ToString(); } void PrintTo(const Transform& transform, ::std::ostream* os) { *os << transform.ToString(); } void PrintTo(const Vector2d& vector, ::std::ostream* os) { *os << vector.ToString(); } void PrintTo(const Vector2dF& vector, ::std::ostream* os) { *os << vector.ToString(); } } // namespace gfx
engine/third_party/accessibility/gfx/test/gfx_util.cc/0
{ "file_path": "engine/third_party/accessibility/gfx/test/gfx_util.cc", "repo_id": "engine", "token_count": 1664 }
474
// 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 "tonic/dart_class_provider.h" #include "tonic/converter/dart_converter.h" #include "tonic/dart_state.h" #include "tonic/logging/dart_error.h" namespace tonic { DartClassProvider::DartClassProvider(DartState* dart_state, const char* class_name) { library_.Set(dart_state, Dart_LookupLibrary(ToDart(class_name))); } DartClassProvider::~DartClassProvider() {} Dart_Handle DartClassProvider::GetClassByName(const char* class_name) { Dart_Handle name_handle = ToDart(class_name); Dart_Handle class_handle = Dart_GetNonNullableType(library_.value(), name_handle, 0, nullptr); TONIC_DCHECK(!Dart_IsError(class_handle)); return class_handle; } } // namespace tonic
engine/third_party/tonic/dart_class_provider.cc/0
{ "file_path": "engine/third_party/tonic/dart_class_provider.cc", "repo_id": "engine", "token_count": 338 }
475
// 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 "tonic/dart_wrappable.h" #include "tonic/dart_class_library.h" #include "tonic/dart_state.h" #include "tonic/dart_wrapper_info.h" #include "tonic/logging/dart_error.h" namespace tonic { DartWrappable::~DartWrappable() { // Calls the destructor of dart_wrapper_ to delete WeakPersistentHandle. } // TODO(dnfield): Delete this. https://github.com/flutter/flutter/issues/50997 Dart_Handle DartWrappable::CreateDartWrapper(DartState* dart_state) { if (!dart_wrapper_.is_empty()) { // Any previously given out wrapper must have been GCed. TONIC_DCHECK(Dart_IsNull(dart_wrapper_.Get())); dart_wrapper_.Clear(); } const DartWrapperInfo& info = GetDartWrapperInfo(); Dart_PersistentHandle type = dart_state->class_library().GetClass(info); TONIC_DCHECK(!CheckAndHandleError(type)); Dart_Handle wrapper = Dart_New(type, dart_state->private_constructor_name(), 0, nullptr); TONIC_DCHECK(!CheckAndHandleError(wrapper)); Dart_Handle res = Dart_SetNativeInstanceField( wrapper, kPeerIndex, reinterpret_cast<intptr_t>(this)); TONIC_DCHECK(!CheckAndHandleError(res)); this->RetainDartWrappableReference(); // Balanced in FinalizeDartWrapper. dart_wrapper_.Set(dart_state, wrapper, this, sizeof(*this), &FinalizeDartWrapper); return wrapper; } void DartWrappable::AssociateWithDartWrapper(Dart_Handle wrapper) { if (!dart_wrapper_.is_empty()) { // Any previously given out wrapper must have been GCed. TONIC_DCHECK(Dart_IsNull(dart_wrapper_.Get())); dart_wrapper_.Clear(); } TONIC_CHECK(!CheckAndHandleError(wrapper)); TONIC_CHECK(!CheckAndHandleError(Dart_SetNativeInstanceField( wrapper, kPeerIndex, reinterpret_cast<intptr_t>(this)))); this->RetainDartWrappableReference(); // Balanced in FinalizeDartWrapper. DartState* dart_state = DartState::Current(); dart_wrapper_.Set(dart_state, wrapper, this, sizeof(*this), &FinalizeDartWrapper); } void DartWrappable::ClearDartWrapper() { TONIC_DCHECK(!dart_wrapper_.is_empty()); Dart_Handle wrapper = dart_wrapper_.Get(); TONIC_CHECK(!CheckAndHandleError( Dart_SetNativeInstanceField(wrapper, kPeerIndex, 0))); dart_wrapper_.Clear(); this->ReleaseDartWrappableReference(); } void DartWrappable::FinalizeDartWrapper(void* isolate_callback_data, void* peer) { DartWrappable* wrappable = reinterpret_cast<DartWrappable*>(peer); wrappable->ReleaseDartWrappableReference(); // Balanced in CreateDartWrapper. } Dart_PersistentHandle DartWrappable::GetTypeForWrapper( tonic::DartState* dart_state, const tonic::DartWrapperInfo& wrapper_info) { return dart_state->class_library().GetClass(wrapper_info); } DartWrappable* DartConverterWrappable::FromDart(Dart_Handle handle) { if (Dart_IsNull(handle)) { return nullptr; } intptr_t peer = 0; Dart_Handle result = Dart_GetNativeInstanceField(handle, DartWrappable::kPeerIndex, &peer); if (Dart_IsError(result)) return nullptr; return reinterpret_cast<DartWrappable*>(peer); } DartWrappable* DartConverterWrappable::FromArguments(Dart_NativeArguments args, int index, Dart_Handle& exception) { intptr_t native_fields[DartWrappable::kNumberOfNativeFields]; Dart_Handle result = Dart_GetNativeFieldsOfArgument( args, index, DartWrappable::kNumberOfNativeFields, native_fields); if (Dart_IsError(result)) { exception = Dart_NewStringFromCString(DartError::kInvalidArgument); return nullptr; } if (!native_fields[DartWrappable::kPeerIndex]) return nullptr; return reinterpret_cast<DartWrappable*>( native_fields[DartWrappable::kPeerIndex]); } } // namespace tonic
engine/third_party/tonic/dart_wrappable.cc/0
{ "file_path": "engine/third_party/tonic/dart_wrappable.cc", "repo_id": "engine", "token_count": 1538 }
476
// 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 "tonic/filesystem/filesystem/path.h" #include <windows.h> #include <direct.h> #include <shellapi.h> #include <sys/stat.h> #include <sys/types.h> #include <algorithm> #include <cerrno> #include <cstring> #include <functional> #include <list> #include <memory> namespace filesystem { namespace { size_t RootLength(const std::string& path) { if (path.empty()) return 0; if (path[0] == '/') return 1; if (path[0] == '\\') { if (path.size() < 2 || path[1] != '\\') return 1; // The path is a network share. Search for up to two '\'s, as they are // the server and share - and part of the root part. size_t index = path.find('\\', 2); if (index > 0) { index = path.find('\\', index + 1); if (index > 0) return index; } return path.size(); } // If the path is of the form 'C:/' or 'C:\', with C being any letter, it's // a root part. if (path.length() >= 2 && path[1] == ':' && (path[2] == '/' || path[2] == '\\') && ((path[0] >= 'A' && path[0] <= 'Z') || (path[0] >= 'a' && path[0] <= 'z'))) { return 3; } return 0; } size_t IsSeparator(const char sep) { return sep == '/' || sep == '\\'; } size_t LastSeparator(const std::string& path) { return path.find_last_of("/\\"); } size_t LastSeparator(const std::string& path, size_t pos) { return path.find_last_of("/\\", pos); } size_t FirstSeparator(const std::string& path, size_t pos) { return path.find_first_of("/\\", pos); } size_t ResolveParentDirectoryTraversal(const std::string& path, size_t put, size_t root_length) { if (put <= root_length) { return root_length; } size_t previous_separator = LastSeparator(path, put - 2); if (previous_separator != std::string::npos) return previous_separator + 1; return 0; } } // namespace std::string SimplifyPath(std::string path) { if (path.empty()) return "."; size_t put = 0; size_t get = 0; size_t traversal_root = 0; size_t component_start = 0; size_t rootLength = RootLength(path); if (rootLength > 0) { put = rootLength; get = rootLength; component_start = rootLength; } while (get < path.size()) { char c = path[get]; if (c == '.' && (get == component_start || get == component_start + 1)) { // We've seen "." or ".." so far in this component. We need to continue // searching. ++get; continue; } if (IsSeparator(c)) { if (get == component_start || get == component_start + 1) { // We've found a "/" or a "./", which we can elide. ++get; component_start = get; continue; } if (get == component_start + 2) { // We've found a "../", which means we need to remove the previous // component. if (put == traversal_root) { path[put++] = '.'; path[put++] = '.'; path[put++] = '\\'; traversal_root = put; } else { put = ResolveParentDirectoryTraversal(path, put, rootLength); } ++get; component_start = get; continue; } } size_t next_separator = FirstSeparator(path, get); if (next_separator == std::string::npos) { // We've reached the last component. break; } size_t next_component_start = next_separator + 1; ++next_separator; size_t component_size = next_component_start - component_start; if (put != component_start && component_size > 0) { path.replace(put, component_size, path.substr(component_start, component_size)); } put += component_size; get = next_component_start; component_start = next_component_start; } size_t last_component_size = path.size() - component_start; if (last_component_size == 1 && path[component_start] == '.') { // The last component is ".", which we can elide. } else if (last_component_size == 2 && path[component_start] == '.' && path[component_start + 1] == '.') { // The last component is "..", which means we need to remove the previous // component. if (put == traversal_root) { path[put++] = '.'; path[put++] = '.'; path[put++] = '\\'; traversal_root = put; } else { put = ResolveParentDirectoryTraversal(path, put, rootLength); } } else { // Otherwise, we need to copy over the last component. if (put != component_start && last_component_size > 0) { path.replace(put, last_component_size, path.substr(component_start, last_component_size)); } put += last_component_size; } if (put >= 2 && IsSeparator(path[put - 1])) --put; // Trim trailing / else if (put == 0) return "."; // Use . for otherwise empty paths to treat them as relative. path.resize(put); std::replace(path.begin(), path.end(), '/', '\\'); return path; } std::string AbsolutePath(const std::string& path) { char absPath[MAX_PATH]; _fullpath(absPath, path.c_str(), MAX_PATH); return std::string(absPath); } std::string GetDirectoryName(const std::string& path) { size_t rootLength = RootLength(path); size_t separator = LastSeparator(path); if (separator < rootLength) separator = rootLength; if (separator == std::string::npos) return std::string(); return path.substr(0, separator); } std::string GetBaseName(const std::string& path) { size_t separator = LastSeparator(path); if (separator == std::string::npos) return path; return path.substr(separator + 1); } std::string GetAbsoluteFilePath(const std::string& path) { HANDLE file = CreateFileA(path.c_str(), FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL); if (file == INVALID_HANDLE_VALUE) { return std::string(); } char buffer[MAX_PATH]; DWORD ret = GetFinalPathNameByHandleA(file, buffer, MAX_PATH, FILE_NAME_NORMALIZED); if (ret == 0 || ret > MAX_PATH) { std::string result; if (GetLastError() == ERROR_ACCESS_DENIED) { // In sandboxed apps, GetFinalPathNameByHandle requires the app to // declare appropriate capabilities in the app's package manifest. Some // of these capabilities are not permitted in shipping apps on the app // store, but may be fine for development/debugging scenarios. If we // can't resolve the full path due to insufficient access, but have // verified the handle is valid, return AbsolutePath of the original // path. // // https://github.com/flutter/flutter/issues/79609 result = AbsolutePath(path); } CloseHandle(file); return result; } std::string result(buffer); result.erase(0, strlen("\\\\?\\")); CloseHandle(file); return result; } } // namespace filesystem
engine/third_party/tonic/filesystem/filesystem/path_win.cc/0
{ "file_path": "engine/third_party/tonic/filesystem/filesystem/path_win.cc", "repo_id": "engine", "token_count": 2847 }
477
// 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 "tonic/scopes/dart_isolate_scope.h" namespace tonic { DartIsolateScope::DartIsolateScope(Dart_Isolate isolate) { isolate_ = isolate; previous_ = Dart_CurrentIsolate(); if (previous_ == isolate_) return; if (previous_) Dart_ExitIsolate(); Dart_EnterIsolate(isolate_); } DartIsolateScope::~DartIsolateScope() { Dart_Isolate current = Dart_CurrentIsolate(); TONIC_DCHECK(!current || current == isolate_); if (previous_ == isolate_) return; if (current) Dart_ExitIsolate(); if (previous_) Dart_EnterIsolate(previous_); } } // namespace tonic
engine/third_party/tonic/scopes/dart_isolate_scope.cc/0
{ "file_path": "engine/third_party/tonic/scopes/dart_isolate_scope.cc", "repo_id": "engine", "token_count": 270 }
478
// 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 LIB_TONIC_TYPED_DATA_UINT8_LIST_H_ #define LIB_TONIC_TYPED_DATA_UINT8_LIST_H_ #warning uint8_list.h is deprecated; use typed_list.h instead. #include "tonic/typed_data/typed_list.h" #endif // LIB_TONIC_TYPED_DATA_UINT8_LIST_H_
engine/third_party/tonic/typed_data/uint8_list.h/0
{ "file_path": "engine/third_party/tonic/typed_data/uint8_list.h", "repo_id": "engine", "token_count": 154 }
479
/* * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef LIB_TXT_SRC_FONT_COLLECTION_H_ #define LIB_TXT_SRC_FONT_COLLECTION_H_ #include <memory> #include <set> #include <string> #include <unordered_map> #include "flutter/fml/macros.h" #include "third_party/googletest/googletest/include/gtest/gtest_prod.h" // nogncheck #include "third_party/skia/include/core/SkFontMgr.h" #include "third_party/skia/include/core/SkRefCnt.h" #include "third_party/skia/modules/skparagraph/include/FontCollection.h" // nogncheck #include "txt/asset_font_manager.h" #include "txt/text_style.h" namespace txt { class FontCollection : public std::enable_shared_from_this<FontCollection> { public: FontCollection(); ~FontCollection(); size_t GetFontManagersCount() const; void SetupDefaultFontManager(uint32_t font_initialization_data); void SetDefaultFontManager(sk_sp<SkFontMgr> font_manager); void SetAssetFontManager(sk_sp<SkFontMgr> font_manager); void SetDynamicFontManager(sk_sp<SkFontMgr> font_manager); void SetTestFontManager(sk_sp<SkFontMgr> font_manager); // Do not provide alternative fonts that can match characters which are // missing from the requested font family. void DisableFontFallback(); // Remove all entries in the font family cache. void ClearFontFamilyCache(); // Construct a Skia text layout FontCollection based on this collection. sk_sp<skia::textlayout::FontCollection> CreateSktFontCollection(); private: sk_sp<SkFontMgr> default_font_manager_; sk_sp<SkFontMgr> asset_font_manager_; sk_sp<SkFontMgr> dynamic_font_manager_; sk_sp<SkFontMgr> test_font_manager_; bool enable_font_fallback_; // An equivalent font collection usable by the Skia text shaper library. sk_sp<skia::textlayout::FontCollection> skt_collection_; std::vector<sk_sp<SkFontMgr>> GetFontManagerOrder() const; FML_DISALLOW_COPY_AND_ASSIGN(FontCollection); }; } // namespace txt #endif // LIB_TXT_SRC_FONT_COLLECTION_H_
engine/third_party/txt/src/txt/font_collection.h/0
{ "file_path": "engine/third_party/txt/src/txt/font_collection.h", "repo_id": "engine", "token_count": 821 }
480
// 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 <lib/zx/channel.h> #include "third_party/skia/include/ports/SkFontMgr_fuchsia.h" #include "txt/platform.h" #if defined(SK_FONTMGR_FREETYPE_EMPTY_AVAILABLE) #include "third_party/skia/include/ports/SkFontMgr_empty.h" #endif namespace txt { std::vector<std::string> GetDefaultFontFamilies() { return {"Roboto"}; } sk_sp<SkFontMgr> GetDefaultFontManager(uint32_t font_initialization_data) { if (font_initialization_data) { fuchsia::fonts::ProviderSyncPtr sync_font_provider; sync_font_provider.Bind(zx::channel(font_initialization_data)); return SkFontMgr_New_Fuchsia(std::move(sync_font_provider)); } else { #if defined(SK_FONTMGR_FREETYPE_EMPTY_AVAILABLE) static sk_sp<SkFontMgr> mgr = SkFontMgr_New_Custom_Empty(); #else static sk_sp<SkFontMgr> mgr = SkFontMgr::RefEmpty(); #endif return mgr; } } } // namespace txt
engine/third_party/txt/src/txt/platform_fuchsia.cc/0
{ "file_path": "engine/third_party/txt/src/txt/platform_fuchsia.cc", "repo_id": "engine", "token_count": 403 }
481
/* * Copyright 2018 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef TXT_TYPEFACE_FONT_ASSET_PROVIDER_H_ #define TXT_TYPEFACE_FONT_ASSET_PROVIDER_H_ #include <string> #include <unordered_map> #include <vector> #include "flutter/fml/macros.h" #include "third_party/skia/include/core/SkFontMgr.h" #include "txt/font_asset_provider.h" namespace txt { class TypefaceFontStyleSet : public SkFontStyleSet { public: TypefaceFontStyleSet(); ~TypefaceFontStyleSet() override; void registerTypeface(sk_sp<SkTypeface> typeface); // |SkFontStyleSet| int count() override; // |SkFontStyleSet| void getStyle(int index, SkFontStyle* style, SkString* name) override; // |SkFontStyleSet| sk_sp<SkTypeface> createTypeface(int index) override; // |SkFontStyleSet| sk_sp<SkTypeface> matchStyle(const SkFontStyle& pattern) override; private: std::vector<sk_sp<SkTypeface>> typefaces_; FML_DISALLOW_COPY_AND_ASSIGN(TypefaceFontStyleSet); }; class TypefaceFontAssetProvider : public FontAssetProvider { public: TypefaceFontAssetProvider(); ~TypefaceFontAssetProvider() override; void RegisterTypeface(sk_sp<SkTypeface> typeface); void RegisterTypeface(sk_sp<SkTypeface> typeface, std::string family_name_alias); // |FontAssetProvider| size_t GetFamilyCount() const override; // |FontAssetProvider| std::string GetFamilyName(int index) const override; // |FontAssetProvider| sk_sp<SkFontStyleSet> MatchFamily(const std::string& family_name) override; private: std::unordered_map<std::string, sk_sp<TypefaceFontStyleSet>> registered_families_; std::vector<std::string> family_names_; FML_DISALLOW_COPY_AND_ASSIGN(TypefaceFontAssetProvider); }; } // namespace txt #endif // TXT_TYPEFACE_FONT_ASSET_PROVIDER_H_
engine/third_party/txt/src/txt/typeface_font_asset_provider.h/0
{ "file_path": "engine/third_party/txt/src/txt/typeface_font_asset_provider.h", "repo_id": "engine", "token_count": 776 }
482
[ { "url": "https://maven.google.com/androidx/lifecycle/lifecycle-common/2.2.0/lifecycle-common-2.2.0.jar", "out_file_name": "androidx_lifecycle_common.jar", "maven_dependency": "androidx.lifecycle:lifecycle-common:2.2.0", "provides": [ "androidx.lifecycle.Lifecycle", "androidx.lifecycle.LifecycleObserver", "androidx.lifecycle.LifecycleOwner" ] }, { "url": "https://maven.google.com/androidx/lifecycle/lifecycle-common-java8/2.2.0/lifecycle-common-java8-2.2.0.jar", "out_file_name": "androidx_lifecycle_common_java8.jar", "maven_dependency": "androidx.lifecycle:lifecycle-common-java8:2.2.0", "provides": [ "androidx.lifecycle.DefaultLifecycleObserver" ] }, { "url": "https://maven.google.com/androidx/lifecycle/lifecycle-runtime/2.2.0/lifecycle-runtime-2.2.0.aar", "out_file_name": "androidx_lifecycle_runtime.aar", "maven_dependency": "androidx.lifecycle:lifecycle-runtime:2.2.0", "provides": [ "androidx.lifecycle.LifecycleRegistry" ] }, { "url": "https://maven.google.com/androidx/fragment/fragment/1.1.0/fragment-1.1.0.aar", "out_file_name": "androidx_fragment.aar", "maven_dependency": "androidx.fragment:fragment:1.1.0", "provides": [ "androidx.fragment.app.Fragment", "androidx.fragment.app.FragmentActivity" ] }, { "url": "https://maven.google.com/androidx/annotation/annotation/1.1.0/annotation-1.1.0.jar", "out_file_name": "androidx_annotation.jar", "maven_dependency": "androidx.annotation:annotation:1.1.0", "provides": [ "androidx.annotation.CallSuper", "androidx.annotation.FloatRange", "androidx.annotation.IntDef", "androidx.annotation.Keep", "androidx.annotation.NonNull", "androidx.annotation.Nullable", "androidx.annotation.RequiresApi", "androidx.annotation.UiThread", "androidx.annotation.VisibleForTesting" ] }, { "url": "https://maven.google.com/androidx/tracing/tracing/1.0.0/tracing-1.0.0.aar", "out_file_name": "androidx_tracing.aar", "maven_dependency": "androidx.tracing:tracing:1.0.0", "provides": [ "androidx.tracing.Trace" ] }, { "url": "https://dl.google.com/android/maven2/androidx/core/core/1.6.0/core-1.6.0.aar", "out_file_name": "androidx_core.aar", "maven_dependency": "androidx.core:core:1.6.0", "provides": [ "androidx.core.view.WindowInsetsControllerCompat" ] }, { "url": "https://maven.google.com/androidx/window/window-java/1.0.0-beta04/window-java-1.0.0-beta04.aar", "out_file_name": "androidx_window_java.aar", "maven_dependency": "androidx.window:window-java:1.0.0-beta04", "provides": [ "androidx.window.java.layout.WindowInfoRepositoryCallbackAdapter", "androidx.window.layout.DisplayFeature", "androidx.window.layout.FoldingFeature", "androidx.window.layout.FoldingFeature.OcclusionType", "androidx.window.layout.FoldingFeature.State", "androidx.window.layout.WindowLayoutInfo", "androidx.window.layout.WindowInfoRepository" ] }, { "url": "https://dl.google.com/android/maven2/com/google/android/play/core/1.8.0/core-1.8.0.aar", "out_file_name": "core-1.8.0.aar", "maven_dependency": "com.google.android.play:core:1.8.0", "provides": [] } ]
engine/tools/androidx/files.json/0
{ "file_path": "engine/tools/androidx/files.json", "repo_id": "engine", "token_count": 1514 }
483
# Updating malioc Flutter uses `malioc` from the Arm Mobile Studio to statically analyze Impeller's shaders. See `impeller/tools/malioc_diff.py` for more information about that. The files in this directory are instructions for updating the `flutter_internal` CIPD package that CI uses to obtain `malioc`. ## Steps 1. Download the Arm Mobile Studio from [Arm](https://developer.arm.com/Tools%20and%20Software/Arm%20Mobile%20Studio) 2. Extract the `.zip` archive into a directory called `arm-tools` sibling to this file. 3. Check that the `arm-tools` directory contains a child directory `mali_offline_compiler`. If it instead contains a child directory which is something like `Arm_Mobile_Studio_2022.4`, then copy the contents of that directory to `arm-tools` instead. 4. Run the `generate.sh` script in this directory. 5. Verify that the file appears [here](https://chrome-infra-packages.appspot.com/p/flutter_internal/tools). 6. Update `.ci.yaml` to refer to the new version tag echoed by `generate.sh`. 7. Delete the `arm-tools` directory
engine/tools/cipd/malioc/README.md/0
{ "file_path": "engine/tools/cipd/malioc/README.md", "repo_id": "engine", "token_count": 318 }
484
name: compare_goldens environment: sdk: '>=3.2.0-0 <4.0.0'
engine/tools/compare_goldens/pubspec.yaml/0
{ "file_path": "engine/tools/compare_goldens/pubspec.yaml", "repo_id": "engine", "token_count": 32 }
485
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // ignore_for_file: prefer_const_constructors, depend_on_referenced_packages import 'package:const_finder_fixtures/target.dart'; void createTargetInPackage() { const Target target = Target('package', -1, null); target.hit(); } void createNonConstTargetInPackage() { final Target target = Target('package_non', -2, null); target.hit(); }
engine/tools/const_finder/test/fixtures/pkg/package.dart/0
{ "file_path": "engine/tools/const_finder/test/fixtures/pkg/package.dart", "repo_id": "engine", "token_count": 151 }
486
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async' show Timer, runZoned; import 'dart:io' as io show IOSink, stderr, stdout; import 'package:logging/logging.dart' as log; import 'package:meta/meta.dart'; // This is where a flutter_tool style progress spinner, color output, // ascii art, terminal control for clearing lines or the whole screen, etc. // can go. We can just add more methods to Logger using the flutter_tool's // Logger as a guide: // // https://github.com/flutter/flutter/blob/c530276f7806c77da2541c518a0e103c9bb44f10/packages/flutter_tools/lib/src/base/logger.dart#L422 /// A simplified wrapper around the [Logger] from package:logging. /// /// The default log level is [Logger.status]. A --quiet flag might change it to /// [Logger.warning] or [Logger.error]. A --verbose flag might change it to /// [Logger.info]. /// /// Log messages at [Logger.warning] and higher will be written to stderr, and /// to stdout otherwise. [Logger.test] records all log messages to a buffer, /// which can be inspected by unit tetss. class Logger { /// Constructs a logger for use in the tool. Logger() : _logger = log.Logger.detached('et'), _test = false { _logger.level = statusLevel; _logger.onRecord.listen(_handler); _setupIoSink(io.stderr); _setupIoSink(io.stdout); } /// A logger for tests. @visibleForTesting Logger.test() : _logger = log.Logger.detached('et'), _test = true { _logger.level = statusLevel; _logger.onRecord.listen((log.LogRecord r) => _testLogs.add(r)); } /// The logging level for error messages. These go to stderr. static const log.Level errorLevel = log.Level('ERROR', 100); /// The logging level for warning messages. These go to stderr. static const log.Level warningLevel = log.Level('WARNING', 75); /// The logging level for normal status messages. These go to stdout. static const log.Level statusLevel = log.Level('STATUS', 25); /// The logging level for verbose informational messages. These go to stdout. static const log.Level infoLevel = log.Level('INFO', 10); static void _handler(log.LogRecord r) { final io.IOSink sink = r.level >= warningLevel ? io.stderr : io.stdout; final String prefix = r.level >= warningLevel ? '[${r.time}] ${r.level}: ' : ''; _ioSinkWrite(sink, '$prefix${r.message}'); } // Status of the global io.stderr and io.stdout is shared across all // Logger instances. static bool _stdioDone = false; // stdout and stderr might already be closed, and when not already closed, // writing can still fail by throwing either a sync or async exception. // This function handles all three cases. static void _ioSinkWrite(io.IOSink sink, String message) { if (_stdioDone) { return; } runZoned<void>(() { try { sink.write(message); } catch (_) { _stdioDone = true; } }, onError: (Object e, StackTrace s) { _stdioDone = true; }); } static void _setupIoSink(io.IOSink sink) { sink.done.then( (void _) { _stdioDone = true; }, onError: (Object err, StackTrace st) { _stdioDone = true; }, ); } final log.Logger _logger; final List<log.LogRecord> _testLogs = <log.LogRecord>[]; final bool _test; Spinner? _status; /// Get the current logging level. log.Level get level => _logger.level; /// Set the current logging level. set level(log.Level l) { _logger.level = l; } /// Record a log message level [Logger.error] and throw a FatalError. /// This should only be called when the program has entered an impossible /// to recover from state or when something isn't implemented yet. void fatal( Object? message, { int indent = 0, bool newline = true, bool fit = false, }) { _emitLog(errorLevel, message, indent, newline, fit); throw FatalError(_formatMessage(message, indent, newline, fit)); } /// Record a log message at level [Logger.error]. void error( Object? message, { int indent = 0, bool newline = true, bool fit = false, }) { _emitLog(errorLevel, message, indent, newline, fit); } /// Record a log message at level [Logger.warning]. void warning( Object? message, { int indent = 0, bool newline = true, bool fit = false, }) { _emitLog(warningLevel, message, indent, newline, fit); } /// Record a log message at level [Logger.warning]. void status( Object? message, { int indent = 0, bool newline = true, bool fit = false, }) { _emitLog(statusLevel, message, indent, newline, fit); } /// Record a log message at level [Logger.info]. void info( Object? message, { int indent = 0, bool newline = true, bool fit = false, }) { _emitLog(infoLevel, message, indent, newline, fit); } /// Writes a number of spaces to stdout equal to the width of the terminal /// and emits a carriage return. void clearLine() { if (!io.stdout.hasTerminal || _test) { return; } _status?.pause(); _emitClearLine(); _status?.resume(); } /// Starts printing a progress spinner. Spinner startSpinner({ void Function()? onFinish, }) { void finishCallback() { onFinish?.call(); _status = null; } _status = io.stdout.hasTerminal && !_test ? FlutterSpinner(onFinish: finishCallback) : Spinner(onFinish: finishCallback); _status!.start(); return _status!; } static void _emitClearLine() { if (io.stdout.supportsAnsiEscapes) { // Go to start of the line and clear the line. _ioSinkWrite(io.stdout, '\r\x1B[K'); return; } final int width = io.stdout.terminalColumns; final String backspaces = '\b' * width; final String spaces = ' ' * width; _ioSinkWrite(io.stdout, '$backspaces$spaces$backspaces'); } String _formatMessage(Object? message, int indent, bool newline, bool fit) { String m = '${' ' * indent}$message${newline ? '\n' : ''}'; if (fit && io.stdout.hasTerminal) { m = fitToWidth(m, io.stdout.terminalColumns); } return m; } void _emitLog( log.Level level, Object? message, int indent, bool newline, bool fit, ) { final String m = _formatMessage(message, indent, newline, fit); _status?.pause(); _logger.log(level, m); _status?.resume(); } /// Shorten a string such that its length will be `w` by replacing /// enough characters in the middle with '...'. Trailing whitespace will not /// be preserved or counted against 'w', but if the input ends with a newline, /// then the output will end with a newline that is not counted against 'w'. /// That is, if the input string ends with a newline, the output string will /// have length up to (w + 1) and end with a newline. /// /// If w <= 0, the result will be the empty string. /// If w <= 3, the result will be a string containing w '.'s. /// If there are a different number of non-'...' characters to the right and /// left of '...' in the result, then the right will have one more than the /// left. @visibleForTesting static String fitToWidth(String s, int w) { // Preserve a trailing newline if needed. final String maybeNewline = s.endsWith('\n') ? '\n' : ''; if (w <= 0) { return maybeNewline; } if (w <= 3) { return '${'.' * w}$maybeNewline'; } // But remove trailing whitespace before removing the middle of the string. s = s.trimRight(); if (s.length <= w) { return '$s$maybeNewline'; } // remove (s.length + 3 - w) characters from the middle of `s` and // replace them with '...'. final int diff = (s.length + 3) - w; final int leftEnd = (s.length - diff) ~/ 2; final int rightStart = (s.length + diff) ~/ 2; s = s.replaceRange(leftEnd, rightStart, '...'); return s + maybeNewline; } /// In a [Logger] constructed by [Logger.test], this list will contain all of /// the [LogRecord]s emitted by the test. @visibleForTesting List<log.LogRecord> get testLogs => _testLogs; } /// A base class for progress spinners, and a no-op implementation that prints /// nothing. class Spinner { /// Creates a progress spinner. If supplied the `onDone` callback will be /// called when `finish()` is called. Spinner({ this.onFinish, }); /// The callback called when `finish()` is called. final void Function()? onFinish; /// Starts the spinner animation. void start() {} /// Pauses the spinner animation. That is, this call causes printing to the /// terminal to stop. void pause() {} /// Resumes the animation at the same from where `pause()` was called. void resume() {} /// Ends an animation, calling the `onFinish` callback if one was provided. void finish() { onFinish?.call(); } } /// A [Spinner] implementation that prints an animated "Flutter" banner. class FlutterSpinner extends Spinner { // ignore: public_member_api_docs FlutterSpinner({ super.onFinish, }); /// The frames of the animation. static const String frames = '⢸⡯⠭⠅⢸⣇⣀⡀⢸⣇⣸⡇⠈⢹⡏⠁⠈⢹⡏⠁⢸⣯⣭⡅⢸⡯⢕⡂⠀⠀'; static final List<String> _flutterAnimation = frames.runes .map<String>((int scalar) => String.fromCharCode(scalar)) .toList(); Timer? _timer; int _ticks = 0; int _lastAnimationFrameLength = 0; @override void start() { _startSpinner(); } void _startSpinner() { _timer = Timer.periodic(const Duration(milliseconds: 100), _callback); _callback(_timer!); } void _callback(Timer timer) { Logger._ioSinkWrite(io.stdout, '\b' * _lastAnimationFrameLength); _ticks += 1; final String newFrame = _currentAnimationFrame; _lastAnimationFrameLength = newFrame.runes.length; Logger._ioSinkWrite(io.stdout, newFrame); } String get _currentAnimationFrame { return _flutterAnimation[_ticks % _flutterAnimation.length]; } @override void pause() { Logger._emitClearLine(); _lastAnimationFrameLength = 0; _timer?.cancel(); } @override void resume() { _startSpinner(); } @override void finish() { _timer?.cancel(); _timer = null; Logger._emitClearLine(); _lastAnimationFrameLength = 0; if (onFinish != null) { onFinish!(); } } } /// FatalErrors are thrown when a fatal error has occurred. class FatalError extends Error { /// Constructs a FatalError with a message. FatalError(this._message); final String _message; @override String toString() => _message; }
engine/tools/engine_tool/lib/src/logger.dart/0
{ "file_path": "engine/tools/engine_tool/lib/src/logger.dart", "repo_id": "engine", "token_count": 3878 }
487
# 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. if (host_os == "win") { host_executable_suffix = ".exe" } else { host_executable_suffix = "" } template("executable_action") { action(target_name) { assert(defined(invoker.tool), "The executable tool must be specified.") assert(defined(invoker.args), "The command line args must be specified.") if (defined(invoker.visibility)) { visibility = invoker.visibility } if (defined(invoker.testonly)) { testonly = invoker.testonly } script = "//build/gn_run_binary.py" host_executable = rebase_path("${invoker.tool}${host_executable_suffix}", root_build_dir) if (defined(invoker.deps)) { deps = invoker.deps } else { deps = [] } if (defined(invoker.inputs)) { inputs = invoker.inputs } else { inputs = [] } outputs = invoker.outputs args = [ host_executable ] + invoker.args } }
engine/tools/executable_action.gni/0
{ "file_path": "engine/tools/executable_action.gni", "repo_id": "engine", "token_count": 407 }
488
#!/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. """ Builds all Fuchsia artifacts vended by Flutter. """ import argparse import errno import os import platform import re import shutil import subprocess import sys import tempfile from gather_flutter_runner_artifacts import CreateMetaPackage, CopyPath from gen_package import CreateFarPackage _script_dir = os.path.abspath(os.path.join(os.path.realpath(__file__), '..')) _src_root_dir = os.path.join(_script_dir, '..', '..', '..') _out_dir = os.path.join(_src_root_dir, 'out') _bucket_directory = os.path.join(_out_dir, 'fuchsia_bucket') def IsLinux(): return platform.system() == 'Linux' def IsMac(): return platform.system() == 'Darwin' def GetFuchsiaSDKPath(): # host_os references the gn host_os # https://gn.googlesource.com/gn/+/main/docs/reference.md#var_host_os host_os = '' if IsLinux(): host_os = 'linux' elif IsMac(): host_os = 'mac' else: host_os = 'windows' return os.path.join(_src_root_dir, 'fuchsia', 'sdk', host_os) def GetHostArchFromPlatform(): host_arch = platform.machine() # platform.machine() returns AMD64 on 64-bit Windows. if host_arch in ['x86_64', 'AMD64']: return 'x64' elif host_arch == 'aarch64': return 'arm64' raise Exception('Unsupported host architecture: %s' % host_arch) def GetPMBinPath(): return os.path.join(GetFuchsiaSDKPath(), 'tools', GetHostArchFromPlatform(), 'pm') def RunExecutable(command): subprocess.check_call(command, cwd=_src_root_dir) def RunGN(variant_dir, flags): print('Running gn for variant "%s" with flags: %s' % (variant_dir, ','.join(flags))) RunExecutable([ os.path.join('flutter', 'tools', 'gn'), ] + flags) assert os.path.exists(os.path.join(_out_dir, variant_dir)) def BuildNinjaTargets(variant_dir, targets): assert os.path.exists(os.path.join(_out_dir, variant_dir)) print('Running autoninja for targets: %s' % targets) RunExecutable(['autoninja', '-C', os.path.join(_out_dir, variant_dir)] + targets) def RemoveDirectoryIfExists(path): if not os.path.exists(path): return if os.path.isfile(path) or os.path.islink(path): os.unlink(path) else: shutil.rmtree(path) def CopyFiles(source, destination): try: shutil.copytree(source, destination) except OSError as error: if error.errno == errno.ENOTDIR: shutil.copy(source, destination) else: raise def FindFile(name, path): for root, dirs, files in os.walk(path): if name in files: return os.path.join(root, name) def FindFileAndCopyTo(file_name, source, dest_parent, dst_name=None): found = FindFile(file_name, source) if not dst_name: dst_name = file_name if found: dst_path = os.path.join(dest_parent, dst_name) CopyPath(found, dst_path) def CopyGenSnapshotIfExists(source, destination): source_root = os.path.join(_out_dir, source) destination_base = os.path.join(destination, 'dart_binaries') FindFileAndCopyTo('gen_snapshot', source_root, destination_base) FindFileAndCopyTo('gen_snapshot_product', source_root, destination_base) FindFileAndCopyTo( 'kernel_compiler.dart.snapshot', source_root, destination_base, 'kernel_compiler.snapshot' ) FindFileAndCopyTo( 'frontend_server.dart.snapshot', source_root, destination_base, 'flutter_frontend_server.snapshot' ) FindFileAndCopyTo( 'list_libraries.dart.snapshot', source_root, destination_base, 'list_libraries.snapshot' ) def CopyFlutterTesterBinIfExists(source, destination): source_root = os.path.join(_out_dir, source) destination_base = os.path.join(destination, 'flutter_binaries') FindFileAndCopyTo('flutter_tester', source_root, destination_base) def CopyZirconFFILibIfExists(source, destination): source_root = os.path.join(_out_dir, source) destination_base = os.path.join(destination, 'flutter_binaries') FindFileAndCopyTo('libzircon_ffi.so', source_root, destination_base) def CopyToBucketWithMode(source, destination, aot, product, runner_type, api_level): mode = 'aot' if aot else 'jit' product_suff = '_product' if product else '' runner_name = '%s_%s%s_runner' % (runner_type, mode, product_suff) far_dir_name = '%s_far' % runner_name source_root = os.path.join(_out_dir, source) far_base = os.path.join(source_root, far_dir_name) CreateMetaPackage(far_base, runner_name) pm_bin = GetPMBinPath() key_path = os.path.join(_script_dir, 'development.key') destination = os.path.join(_bucket_directory, destination, mode) CreateFarPackage(pm_bin, far_base, key_path, destination, api_level) patched_sdk_dirname = '%s_runner_patched_sdk' % runner_type patched_sdk_dir = os.path.join(source_root, patched_sdk_dirname) dest_sdk_path = os.path.join(destination, patched_sdk_dirname) if not os.path.exists(dest_sdk_path): CopyPath(patched_sdk_dir, dest_sdk_path) CopyGenSnapshotIfExists(source_root, destination) CopyFlutterTesterBinIfExists(source_root, destination) CopyZirconFFILibIfExists(source_root, destination) def CopyToBucket(src, dst, product=False): api_level = ReadTargetAPILevel() CopyToBucketWithMode(src, dst, False, product, 'flutter', api_level) CopyToBucketWithMode(src, dst, True, product, 'flutter', api_level) CopyToBucketWithMode(src, dst, False, product, 'dart', api_level) CopyToBucketWithMode(src, dst, True, product, 'dart', api_level) def ReadTargetAPILevel(): filename = os.path.join(os.path.dirname(__file__), '../../build/config/fuchsia/gn_configs.gni') with open(filename) as f: for line in f: if line.startswith('fuchsia_target_api_level'): return line.split('=')[-1].strip() assert False, 'No fuchsia_target_api_level found in //flutter/build/config/fuchsia/gn_configs.gni' def CopyVulkanDepsToBucket(src, dst, arch): sdk_path = GetFuchsiaSDKPath() deps_bucket_path = os.path.join(_bucket_directory, dst) if not os.path.exists(deps_bucket_path): FindFileAndCopyTo('VkLayer_khronos_validation.json', '%s/pkg' % (sdk_path), deps_bucket_path) FindFileAndCopyTo( 'VkLayer_khronos_validation.so', '%s/arch/%s' % (sdk_path, arch), deps_bucket_path ) def CopyIcuDepsToBucket(src, dst): source_root = os.path.join(_out_dir, src) deps_bucket_path = os.path.join(_bucket_directory, dst) FindFileAndCopyTo('icudtl.dat', source_root, deps_bucket_path) def CopyBuildToBucket(runtime_mode, arch, optimized, product): unopt = "_unopt" if not optimized else "" out_dir = 'fuchsia_%s%s_%s/' % (runtime_mode, unopt, arch) bucket_dir = 'flutter/%s/%s%s/' % (arch, runtime_mode, unopt) deps_dir = 'flutter/%s/deps/' % (arch) CopyToBucket(out_dir, bucket_dir, product) CopyVulkanDepsToBucket(out_dir, deps_dir, arch) CopyIcuDepsToBucket(out_dir, deps_dir) # Copy the CIPD YAML template from the source directory to be next to the bucket # we are about to package. cipd_yaml = os.path.join(_script_dir, 'fuchsia.cipd.yaml') CopyFiles(cipd_yaml, os.path.join(_bucket_directory, 'fuchsia.cipd.yaml')) # Copy the license files from the source directory to be next to the bucket we # are about to package. bucket_root = os.path.join(_bucket_directory, 'flutter') licenses_root = os.path.join(_src_root_dir, 'flutter/ci/licenses_golden') license_files = ['licenses_flutter', 'licenses_fuchsia', 'licenses_skia', 'licenses_third_party'] for license in license_files: src_path = os.path.join(licenses_root, license) dst_path = os.path.join(bucket_root, license) CopyPath(src_path, dst_path) def CheckCIPDPackageExists(package_name, tag): '''Check to see if the current package/tag combo has been published''' command = [ 'cipd', 'search', package_name, '-tag', tag, ] stdout = subprocess.check_output(command) # TODO ricardoamador: remove this check when python 2 is deprecated. stdout = stdout if isinstance(stdout, str) else stdout.decode('UTF-8') match = re.search(r'No matching instances\.', stdout) if match: return False else: return True def RunCIPDCommandWithRetries(command): # Retry up to three times. We've seen CIPD fail on verification in some # instances. Normally verification takes slightly more than 1 minute when # it succeeds. num_tries = 3 for tries in range(num_tries): try: subprocess.check_call(command, cwd=_bucket_directory) break except subprocess.CalledProcessError: print('Failed %s times' % tries + 1) if tries == num_tries - 1: raise def ProcessCIPDPackage(upload, engine_version): if not upload or not IsLinux(): RunCIPDCommandWithRetries([ 'cipd', 'pkg-build', '-pkg-def', 'fuchsia.cipd.yaml', '-out', os.path.join(_bucket_directory, 'fuchsia.cipd') ]) return # Everything after this point will only run iff `upload==true` and # `IsLinux() == true` assert (upload) assert (IsLinux()) if engine_version is None: print('--upload requires --engine-version to be specified.') return tag = 'git_revision:%s' % engine_version already_exists = CheckCIPDPackageExists('flutter/fuchsia', tag) if already_exists: print('CIPD package flutter/fuchsia tag %s already exists!' % tag) return RunCIPDCommandWithRetries([ 'cipd', 'create', '-pkg-def', 'fuchsia.cipd.yaml', '-ref', 'latest', '-tag', tag, ]) def BuildTarget( runtime_mode, arch, optimized, enable_lto, enable_legacy, asan, dart_version_git_info, prebuilt_dart_sdk, build_targets ): unopt = "_unopt" if not optimized else "" out_dir = 'fuchsia_%s%s_%s' % (runtime_mode, unopt, arch) flags = [ '--fuchsia', '--fuchsia-cpu', arch, '--runtime-mode', runtime_mode, ] if not optimized: flags.append('--unoptimized') if not enable_lto: flags.append('--no-lto') if not enable_legacy: flags.append('--no-fuchsia-legacy') if asan: flags.append('--asan') if not dart_version_git_info: flags.append('--no-dart-version-git-info') if not prebuilt_dart_sdk: flags.append('--no-prebuilt-dart-sdk') RunGN(out_dir, flags) BuildNinjaTargets(out_dir, build_targets) return def main(): parser = argparse.ArgumentParser() parser.add_argument( '--cipd-dry-run', default=False, action='store_true', help='If set, creates the CIPD package but does not upload it.' ) parser.add_argument( '--upload', default=False, action='store_true', help='If set, uploads the CIPD package and tags it as the latest.' ) parser.add_argument('--engine-version', required=False, help='Specifies the flutter engine SHA.') parser.add_argument( '--unoptimized', action='store_true', default=False, help='If set, disables compiler optimization for the build.' ) parser.add_argument( '--runtime-mode', type=str, choices=['debug', 'profile', 'release', 'all'], default='all' ) parser.add_argument('--archs', type=str, choices=['x64', 'arm64', 'all'], default='all') parser.add_argument( '--asan', action='store_true', default=False, help='If set, enables address sanitization (including leak sanitization) for the build.' ) parser.add_argument( '--no-lto', action='store_true', default=False, help='If set, disables LTO for the build.' ) parser.add_argument( '--no-legacy', action='store_true', default=False, help='If set, disables legacy code for the build.' ) parser.add_argument( '--skip-build', action='store_true', default=False, help='If set, skips building and just creates packages.' ) parser.add_argument( '--targets', default='', help=('Comma-separated list; adds additional targets to build for ' 'Fuchsia.') ) parser.add_argument( '--no-dart-version-git-info', action='store_true', default=False, help='If set, turns off the Dart SDK git hash check.' ) parser.add_argument( '--no-prebuilt-dart-sdk', action='store_true', default=False, help='If set, builds the Dart SDK locally instead of using the prebuilt Dart SDK.' ) parser.add_argument( '--copy-unoptimized-debug-artifacts', action='store_true', default=False, help='If set, unoptimized debug artifacts will be copied into CIPD along ' 'with optimized builds. This is a hack to allow infra to make ' 'and copy two debug builds, one with ASAN and one without.' ) # TODO(http://fxb/110639): Deprecate this in favor of multiple runtime parameters parser.add_argument( '--skip-remove-buckets', action='store_true', default=False, help='This allows for multiple runtimes to exist in the default bucket directory. If ' 'set, will skip over the removal of existing artifacts in the bucket directory ' '(which is the default behavior).' ) args = parser.parse_args() build_mode = args.runtime_mode if (not args.skip_remove_buckets): RemoveDirectoryIfExists(_bucket_directory) archs = ['x64', 'arm64'] if args.archs == 'all' else [args.archs] runtime_modes = ['debug', 'profile', 'release'] product_modes = [False, False, True] optimized = not args.unoptimized enable_lto = not args.no_lto enable_legacy = not args.no_legacy # Build buckets for arch in archs: for i in range(len(runtime_modes)): runtime_mode = runtime_modes[i] product = product_modes[i] if build_mode == 'all' or runtime_mode == build_mode: if not args.skip_build: BuildTarget( runtime_mode, arch, optimized, enable_lto, enable_legacy, args.asan, not args.no_dart_version_git_info, not args.no_prebuilt_dart_sdk, args.targets.split(",") if args.targets else ['flutter'] ) CopyBuildToBucket(runtime_mode, arch, optimized, product) # This is a hack. The recipe for building and uploading Fuchsia to CIPD # builds both a debug build (debug without ASAN) and unoptimized debug # build (debug with ASAN). To copy both builds into CIPD, the recipe # runs build_fuchsia_artifacts.py in optimized mode and tells # build_fuchsia_artifacts.py to also copy_unoptimized_debug_artifacts. # # TODO(akbiggs): Consolidate Fuchsia's building and copying logic to # avoid ugly hacks like this. if args.copy_unoptimized_debug_artifacts and runtime_mode == 'debug' and optimized: CopyBuildToBucket(runtime_mode, arch, not optimized, product) # Set revision to HEAD if empty and remove upload. This is to support # presubmit workflows. should_upload = args.upload engine_version = args.engine_version if not engine_version: engine_version = 'HEAD' should_upload = False # Create and optionally upload CIPD package if args.cipd_dry_run or args.upload: ProcessCIPDPackage(should_upload, engine_version) return 0 if __name__ == '__main__': sys.exit(main())
engine/tools/fuchsia/build_fuchsia_artifacts.py/0
{ "file_path": "engine/tools/fuchsia/build_fuchsia_artifacts.py", "repo_id": "engine", "token_count": 5825 }
489
#!/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. # ### Tests run_unit_tests.sh by running it with various arguments. ### This script doesn't assert the results but just checks that the script runs ### successfully every time. ### ### This script doesn't run on CQ, it's only used for local testing. source "$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)"/../lib/vars.sh || exit $? ensure_engine_dir set -e # Fail on any error. engine-info "Testing run_unit_tests.sh --package-filter flutter_runner_tests-0.far..." "$ENGINE_DIR"/flutter/tools/fuchsia/devshell/run_unit_tests.sh --package-filter "flutter_runner_tests-0.far" engine-info "Testing run_unit_tests.sh --package-filter flutter_runner_tests-0.far --count 2..." "$ENGINE_DIR"/flutter/tools/fuchsia/devshell/run_unit_tests.sh --package-filter "flutter_runner_tests-0.far" --count 2 engine-info "Testing run_unit_tests.sh --package-filter flutter_runner_tests-0.far --gtest-filter *FlatlandConnection*..." "$ENGINE_DIR"/flutter/tools/fuchsia/devshell/run_unit_tests.sh --package-filter "flutter_runner_tests-0.far" --gtest-filter "*FlatlandConnection*" engine-info "Testing run_unit_tests.sh with no args..." "$ENGINE_DIR"/flutter/tools/fuchsia/devshell/run_unit_tests.sh
engine/tools/fuchsia/devshell/test/test_run_unit_tests.sh/0
{ "file_path": "engine/tools/fuchsia/devshell/test/test_run_unit_tests.sh", "repo_id": "engine", "token_count": 470 }
490
#!/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. """ Parses manifest file and dumps it to json. """ import argparse import json import os import sys import hashlib def main(): parser = argparse.ArgumentParser() parser.add_argument('--input', dest='file_path', action='store', required=True) parser.add_argument('--clang-cpu', dest='clang_cpu', action='store', required=True) args = parser.parse_args() with open(args.file_path) as f: data = json.load(f) output = {} target = args.clang_cpu + '-fuchsia' for d in data: if target in d['target']: for runtime in d['runtime']: # key contains the soname and the cflags used to compile it. # this allows us to distinguish between different sanitizers # and experiments key = runtime['soname'] + ''.join(d['cflags']) md5 = hashlib.md5(key.encode()).hexdigest() hash_key = 'md5_%s' % md5 # Uncomment this line to get the hash keys # print runtime['dist'], d['cflags'], hash_key output[hash_key] = os.path.dirname(runtime['dist']) print(json.dumps(output)) return 0 if __name__ == '__main__': sys.exit(main())
engine/tools/fuchsia/parse_manifest.py/0
{ "file_path": "engine/tools/fuchsia/parse_manifest.py", "repo_id": "engine", "token_count": 479 }
491
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // The following segment is not only used in the generating script, but also // copied to the generated package. /*@@@ SHARED SEGMENT START @@@*/ /// Used in the final mapping indicating the logical key should be derived from /// KeyboardEvent.keyCode. /// /// This value is chosen because it's a printable character within EASCII that /// will never be mapped to (checked in the marshalling algorithm). const int kUseKeyCode = 0xFF; /// Used in the final mapping indicating the event key is 'Dead', the dead key. final String _kUseDead = String.fromCharCode(0xFE); /// The KeyboardEvent.key for a dead key. const String _kEventKeyDead = 'Dead'; /// A map of all goals from the scan codes to their mapped value in US layout. const Map<String, String> kLayoutGoals = <String, String>{ 'KeyA': 'a', 'KeyB': 'b', 'KeyC': 'c', 'KeyD': 'd', 'KeyE': 'e', 'KeyF': 'f', 'KeyG': 'g', 'KeyH': 'h', 'KeyI': 'i', 'KeyJ': 'j', 'KeyK': 'k', 'KeyL': 'l', 'KeyM': 'm', 'KeyN': 'n', 'KeyO': 'o', 'KeyP': 'p', 'KeyQ': 'q', 'KeyR': 'r', 'KeyS': 's', 'KeyT': 't', 'KeyU': 'u', 'KeyV': 'v', 'KeyW': 'w', 'KeyX': 'x', 'KeyY': 'y', 'KeyZ': 'z', 'Digit1': '1', 'Digit2': '2', 'Digit3': '3', 'Digit4': '4', 'Digit5': '5', 'Digit6': '6', 'Digit7': '7', 'Digit8': '8', 'Digit9': '9', 'Digit0': '0', 'Minus': '-', 'Equal': '=', 'BracketLeft': '[', 'BracketRight': ']', 'Backslash': r'\', 'Semicolon': ';', 'Quote': "'", 'Backquote': '`', 'Comma': ',', 'Period': '.', 'Slash': '/', }; final int _kLowerA = 'a'.codeUnitAt(0); final int _kUpperA = 'A'.codeUnitAt(0); final int _kLowerZ = 'z'.codeUnitAt(0); final int _kUpperZ = 'Z'.codeUnitAt(0); bool _isAscii(int charCode) { // 0x20 is the first printable character in ASCII. return charCode >= 0x20 && charCode <= 0x7F; } /// Returns whether the `char` is a single character of a letter or a digit. bool isLetter(int charCode) { return (charCode >= _kLowerA && charCode <= _kLowerZ) || (charCode >= _kUpperA && charCode <= _kUpperZ); } /// A set of rules that can derive a large number of logical keys simply from /// the event's code and key. /// /// This greatly reduces the entries needed in the final mapping. int? heuristicMapper(String code, String key) { // Digit code: return the digit by event code. if (code.startsWith('Digit')) { assert(code.length == 6); return code.codeUnitAt(5); // The character immediately after 'Digit' } final int charCode = key.codeUnitAt(0); // Non-ascii: return the goal (i.e. US mapping by event code). if (key.length > 1 || !_isAscii(charCode)) { return kLayoutGoals[code]?.codeUnitAt(0); } // Letter key: return the event key letter. if (isLetter(charCode)) { return key.toLowerCase().codeUnitAt(0); } return null; } // Maps an integer to a printable EASCII character by adding it to this value. // // We could've chosen 0x20, the first printable character, for a slightly bigger // range, but it's prettier this way and sufficient. final int _kMarshallIntBase = '0'.codeUnitAt(0); class _StringStream { _StringStream(this._data) : _offset = 0; final String _data; final Map<int, String> _goalToEventCode = Map<int, String>.fromEntries( kLayoutGoals .entries .map((MapEntry<String, String> beforeEntry) => MapEntry<int, String>(beforeEntry.value.codeUnitAt(0), beforeEntry.key)) ); int get offest => _offset; int _offset; int readIntAsVerbatim() { final int result = _data.codeUnitAt(_offset); _offset += 1; assert(result >= _kMarshallIntBase); return result - _kMarshallIntBase; } int readIntAsChar() { final int result = _data.codeUnitAt(_offset); _offset += 1; return result; } String readEventKey() { final String char = String.fromCharCode(readIntAsChar()); if (char == _kUseDead) { return _kEventKeyDead; } else { return char; } } String readEventCode() { final int charCode = _data.codeUnitAt(_offset); _offset += 1; return _goalToEventCode[charCode]!; } } Map<String, int> _unmarshallCodeMap(_StringStream stream) { final int entryNum = stream.readIntAsVerbatim(); return <String, int>{ for (int i = 0; i < entryNum; i++) stream.readEventKey(): stream.readIntAsChar(), }; } /// Decode a key mapping data out of the string. Map<String, Map<String, int>> unmarshallMappingData(String compressed) { final _StringStream stream = _StringStream(compressed); final int eventCodeNum = stream.readIntAsVerbatim(); return <String, Map<String, int>>{ for (int i = 0; i < eventCodeNum; i++) stream.readEventCode() : _unmarshallCodeMap(stream), }; } /*@@@ SHARED SEGMENT END @@@*/ /// Whether the given charCode is a ASCII letter. bool isLetterChar(int charCode) { return (charCode >= _kLowerA && charCode <= _kLowerZ) || (charCode >= _kUpperA && charCode <= _kUpperZ); } bool _isPrintableEascii(int charCode) { return charCode >= 0x20 && charCode <= 0xFF; } typedef _ForEachAction<V> = void Function(String key, V value); void _sortedForEach<V>(Map<String, V> map, _ForEachAction<V> action) { map .entries .toList() ..sort((MapEntry<String, V> a, MapEntry<String, V> b) => a.key.compareTo(b.key)) ..forEach((MapEntry<String, V> entry) { action(entry.key, entry.value); }); } // Encode a small integer as a character by its value. // // For example, 0x48 is encoded as '0'. This means that values within 0x0 - 0x19 // or greater than 0xFF are forbidden. void _marshallIntAsChar(StringBuffer builder, int value) { assert(_isPrintableEascii(value), '$value'); builder.writeCharCode(value); } const int _kMarshallIntEnd = 0xFF; // The last printable EASCII. // Encode a small integer as a character based on a certain printable codepoint. // // For example, 0x0 is encoded as '0', and 0x1 is encoded as '1'. This function // allows smaller values than _marshallIntAsChar. void _marshallIntAsVerbatim(StringBuffer builder, int value) { final int result = value + _kMarshallIntBase; assert(result <= _kMarshallIntEnd); builder.writeCharCode(result); } void _marshallEventCode(StringBuffer builder, String value) { // Instead of recording the entire eventCode, since the eventCode is mapped // 1-to-1 to a character in kLayoutGoals, we record the goal instead. final String char = kLayoutGoals[value]!; builder.write(char); } void _marshallEventKey(StringBuffer builder, String value) { if (value == _kEventKeyDead) { builder.write(_kUseDead); } else { assert(value.length == 1, value); assert(value != _kUseDead); builder.write(value); } } /// Encode a key mapping data into a list of strings. /// /// The list of strings should be used concatenated, but is returned this way /// for aesthetic purposes (one entry per line). /// /// The algorithm aims at encoding the map directly into a printable string /// (instead of a binary stream converted by base64). Some characters in the /// string can be multi-byte, which means the decoder should parse the string /// using substr instead of as a binary stream. List<String> marshallMappingData(Map<String, Map<String, int>> mappingData) { final StringBuffer builder = StringBuffer(); _marshallIntAsVerbatim(builder, mappingData.length); _sortedForEach(mappingData, (String eventCode, Map<String, int> codeMap) { builder.write('\n'); _marshallEventCode(builder, eventCode); _marshallIntAsVerbatim(builder, codeMap.length); _sortedForEach(codeMap, (String eventKey, int logicalKey) { _marshallEventKey(builder, eventKey); _marshallIntAsChar(builder, logicalKey); }); }); return builder.toString().split('\n'); }
engine/tools/gen_web_locale_keymap/lib/common.dart/0
{ "file_path": "engine/tools/gen_web_locale_keymap/lib/common.dart", "repo_id": "engine", "token_count": 2835 }
492
# Updating gradle version used in engine repo The instructions in this README explain how to create a CIPD package that contains the gradle build-time dependency of the Android embedding of the Engine. The Android embedder is shipped to Flutter end-users, but gradle is not. ## Requirements 1. If you have a flutter/engine checkout, then you should already have [Depot tools](http://commondatastorage.googleapis.com/chrome-infra-docs/flat/depot_tools/docs/html/depot_tools_tutorial.html#_setting_up) on your path. 1. Ensure you have write access for cipd. go/flutter-luci-cipd 1. Download the new version of gradle then verify the checksum, and unzip into a local directory. ## Update CIPD Steps These steps use gradle version 7.5.1 as an example. 1. Unzip gradle into a folder `unzip gradle-7.5.1-all.zip` 1. Authenticate with cipd `cipd auth-login` 1. Run `cipd create -in gradle-7.5.1 -install-mode copy -tag version:7.5.1 -name flutter/gradle` 1. Update `engine/src/flutter/DEPS` gradle entry to contain the tag from the command above. 1. Run `gclient sync` to verify that dependency can be fetched. ## Useful links * CIPD gradle https://chrome-infra-packages.appspot.com/p/flutter/gradle/+/ * Gradle Releases https://gradle.org/releases/
engine/tools/gradle/README.md/0
{ "file_path": "engine/tools/gradle/README.md", "repo_id": "engine", "token_count": 400 }
493
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert'; import 'dart:core' hide RegExp; import 'dart:io' as system; import 'cache.dart'; import 'formatter.dart'; import 'limits.dart'; import 'patterns.dart'; import 'regexp_debug.dart'; class FetchedContentsOf extends Key { FetchedContentsOf(super.value); } enum LicenseType { afl, apache, apacheNotice, apsl, bison, bsd, eclipse, freetype, gpl, icu, defaultTemplate, // metatype: a license that applies to a file without an internal license; only used when searching for a license ietf, ijg, lgpl, libpng, llvm, mit, mpl, openssl, unicode, unknown, vulkan, zlib, } LicenseType convertLicenseNameToType(String? name) { switch (name) { case 'Apache': case 'Apache-2.0.txt': case 'LICENSE-APACHE-2.0.txt': case 'LICENSE.vulkan': case 'APACHE-LICENSE-2.0': return LicenseType.apache; case 'BSD': case 'BSD-3-Clause.txt': case 'BSD.txt': return LicenseType.bsd; case 'COPYING-LGPL-2.1': case 'LICENSE-LGPL-2': case 'LICENSE-LGPL-2.1': return LicenseType.lgpl; case 'COPYING-GPL-3': case 'GPL-3.0-only.txt': case 'GPLv2.TXT': return LicenseType.gpl; case 'FTL.TXT': return LicenseType.freetype; case 'zlib.h': return LicenseType.zlib; case 'png.h': return LicenseType.libpng; case 'ICU': return LicenseType.icu; case 'Apple Public Source License': return LicenseType.apsl; case 'OpenSSL': return LicenseType.openssl; case 'COPYING-MPL-1.1': case 'LICENSE.MPLv2': case 'http://mozilla.org/MPL/2.0/': return LicenseType.mpl; case 'COPYRIGHT.vulkan': return LicenseType.vulkan; case 'LICENSE.MIT': case 'MIT': case 'MIT.txt': return LicenseType.mit; // file names that don't say what the type is case 'COPYING': case 'COPYING.LIB': // lgpl usually case 'COPYING.RUNTIME': // gcc exception usually case 'COPYING.txt': case 'COPYRIGHT.musl': case 'Copyright': case 'LICENSE': case 'LICENSE-APPLE': case 'LICENSE.TXT': case 'LICENSE.cssmin': case 'LICENSE.md': case 'LICENSE.rst': case 'LICENSE.txt': case 'License.txt': case 'NOTICE': case 'NOTICE.txt': case 'copyright': case 'extreme.indiana.edu.license.TXT': case 'extreme.indiana.edu.license.txt': case 'javolution.license.TXT': case 'javolution.license.txt': case 'libyaml-license.txt': case 'license.html': case 'license.patch': case 'license.txt': case 'mh-bsd-gcc': case 'pivotal.labs.license.txt': return LicenseType.unknown; } throw 'unknown license type: $name'; } LicenseType convertBodyToType(String body) { if (body.startsWith(lrApache) && body.contains(lrLLVM)) { return LicenseType.llvm; } if (body.startsWith(lrApache)) { return LicenseType.apache; } if (body.startsWith(lrMPL)) { return LicenseType.mpl; } if (body.startsWith(lrGPL)) { return LicenseType.gpl; } if (body.startsWith(lrAPSL)) { return LicenseType.apsl; } if (body.contains(lrOpenSSL)) { return LicenseType.openssl; } if (body.contains(lrBSD)) { return LicenseType.bsd; } if (body.contains(lrMIT)) { return LicenseType.mit; } if (body.contains(lrZlib)) { return LicenseType.zlib; } if (body.contains(lrPNG)) { return LicenseType.libpng; } if (body.contains(lrBison)) { return LicenseType.bison; } return LicenseType.unknown; } // API exposed by the classes in main.dart abstract class LicenseSource { String get name; String get libraryName; String get officialSourceLocation; List<License>? nearestLicensesFor(String name); License? nearestLicenseOfType(LicenseType type); License? nearestLicenseWithName(String name, { String? authors }); } // Represents a license/file pairing, with metadata saying where the license came from. class Assignment { const Assignment(this.license, this.target, this.source); final License license; final String target; final LicenseSource source; } // Represents a group of files assigned to the same license, so that we can avoid // duplicating licenses in the output. class GroupedLicense { GroupedLicense(this.type, this.body); final LicenseType type; final String body; // The names of files to which this license applies. final Set<String> targets = <String>{}; // The libraries from which those files originate. final Set<String> libraries = <String>{}; // How we determined the license applied to these files. final Set<String> origins = <String>{}; String toStringDebug() { final StringBuffer result = StringBuffer(); result.writeln('=' * 100); (libraries.map((String s) => 'LIBRARY: $s').toList()..sort()).forEach(result.writeln); (origins.map((String s) => 'ORIGIN: $s').toList()..sort()).forEach(result.writeln); result.writeln('TYPE: $type'); (targets.map((String s) => 'FILE: $s').toList()..sort()).forEach(result.writeln); result.writeln('-' * 100); if (body.isEmpty) { result.writeln('<THIS BLOCK INTENTIONALLY LEFT BLANK>'); } else { result.writeln(body); } result.writeln('=' * 100); return result.toString(); } String toStringFormal() { final StringBuffer result = StringBuffer(); (libraries.toList()..sort()).forEach(result.writeln); result.writeln(); assert(body.isNotEmpty); result.write(body); return result.toString(); } } List<GroupedLicense> groupLicenses(Iterable<Assignment> assignments) { final Map<String, GroupedLicense> groups = <String, GroupedLicense>{}; for (final Assignment assignment in assignments) { final String body = assignment.license.toStringBody(assignment.source); final GroupedLicense entry = groups.putIfAbsent(body, () => GroupedLicense(assignment.license.type, body)); entry.targets.add(assignment.target); entry.libraries.add(assignment.source.libraryName); entry.origins.add(assignment.license.origin); } final List<GroupedLicense> results = groups.values.toList(); results.sort((GroupedLicense a, GroupedLicense b) => a.body.compareTo(b.body)); return results; } abstract class License { factory License.unique(String body, LicenseType type, { bool reformatted = false, required String origin, String? authors, bool yesWeKnowWhatItLooksLikeButItIsNot = false }) { if (!reformatted) { body = reformat(body); } final License result = UniqueLicense._(body, type, origin: origin, yesWeKnowWhatItLooksLikeButItIsNot: yesWeKnowWhatItLooksLikeButItIsNot, authors: authors); assert(() { if (result is! UniqueLicense || result.type != type) { throw 'tried to add a UniqueLicense $type, but it was a duplicate of a ${result.runtimeType} ${result.type}'; } return true; }()); return result; } factory License.template(String body, LicenseType type, { bool reformatted = false, required String origin, String? authors, }) { if (!reformatted) { body = reformat(body); } final License result = TemplateLicense._autosplit(body, type, origin: origin, authors: authors); assert(() { if (result is! TemplateLicense || result.type != type) { throw 'tried to add a TemplateLicense $type, but it was a duplicate of a ${result.runtimeType} ${result.type}'; } return true; }()); return result; } factory License.multiLicense(String body, LicenseType type, { bool reformatted = false, String? authors, required String origin }) { if (!reformatted) { body = reformat(body); } final License result = MultiLicense._(body, type, origin: origin, authors: authors); assert(() { if (result is! MultiLicense || result.type != type) { throw 'tried to add a MultiLicense $type, but it was a duplicate of a ${result.runtimeType} ${result.type}'; } return true; }()); return result; } factory License.message(String body, LicenseType type, { bool reformatted = false, required String origin }) { if (!reformatted) { body = reformat(body); } final License result = MessageLicense._(body, type, origin: origin); assert(() { if (result is! MessageLicense || result.type != type) { throw 'tried to add a MessageLicense $type, but it was a duplicate of a ${result.runtimeType} ${result.type}'; } return true; }()); return result; } factory License.blank(String body, LicenseType type, { required String origin }) { final License result = BlankLicense._(reformat(body), type, origin: origin); assert(() { if (result is! BlankLicense || result.type != type) { throw 'tried to add a BlankLicense $type, but it was a duplicate of a ${result.runtimeType} ${result.type}'; } return true; }()); return result; } factory License.mozilla(String body, { required String origin }) { body = reformat(body); final License result = MozillaLicense._(body, LicenseType.mpl, origin: origin); assert(() { if (result is! MozillaLicense) { throw 'tried to add a MozillaLicense, but it was a duplicate of a ${result.runtimeType} ${result.type}'; } return true; }()); return result; } factory License.fromMultipleBlocks(List<String> bodies, LicenseType type, { String? authors, required String origin, bool yesWeKnowWhatItLooksLikeButItIsNot = false, }) { final String body = bodies.map((String s) => reformat(s)).join('\n\n'); return MultiLicense._(body, type, authors: authors, origin: origin, yesWeKnowWhatItLooksLikeButItIsNot: yesWeKnowWhatItLooksLikeButItIsNot); } factory License.fromBodyAndType(String body, LicenseType type, { bool reformatted = false, required String origin }) { if (!reformatted) { body = reformat(body); } final License result; switch (type) { case LicenseType.bsd: case LicenseType.mit: result = TemplateLicense._autosplit(body, type, origin: origin); case LicenseType.apache: case LicenseType.freetype: case LicenseType.ijg: case LicenseType.ietf: case LicenseType.libpng: case LicenseType.llvm: // The LLVM license is an Apache variant case LicenseType.unicode: case LicenseType.unknown: case LicenseType.vulkan: case LicenseType.zlib: result = MessageLicense._(body, type, origin: origin); case LicenseType.apacheNotice: result = UniqueLicense._(body, type, origin: origin); case LicenseType.mpl: result = MozillaLicense._(body, type, origin: origin); // The exception in the license of Bison allows redistributing larger // works "under terms of your choice"; we choose terms that don't require // any notice in the binary distribution. case LicenseType.bison: result = BlankLicense._(body, type, origin: origin); case LicenseType.icu: case LicenseType.openssl: throw 'Use License.fromMultipleBlocks rather than License.fromBodyAndType for the ICU and OpenSSL licenses.'; case LicenseType.afl: case LicenseType.apsl: case LicenseType.eclipse: case LicenseType.gpl: case LicenseType.lgpl: result = DisallowedLicense._(body, type, origin: origin); case LicenseType.defaultTemplate: throw 'should not be creating a LicenseType.defaultTemplate license, it is not a real type'; } assert(result.type == type); return result; } factory License.fromBodyAndName(String body, String name, { required String origin }) { body = reformat(body); LicenseType type = convertLicenseNameToType(name); if (type == LicenseType.unknown) { type = convertBodyToType(body); } return License.fromBodyAndType(body, type, reformatted: true, origin: origin); } factory License.fromBody(String body, { required String origin, bool reformatted = false }) { if (!reformatted) { body = reformat(body); } final LicenseType type = convertBodyToType(body); return License.fromBodyAndType(body, type, reformatted: true, origin: origin); } factory License.fromCopyrightAndLicense(String copyright, String template, LicenseType type, { required String origin }) { copyright = reformat(copyright); template = reformat(template); return TemplateLicense._(copyright, template, type, origin: origin); } factory License.fromIdentifyingReference(String identifyingReference, { required String referencer }) { String body; LicenseType type = LicenseType.unknown; switch (identifyingReference) { case 'Apache-2.0 OR MIT': // SPDX ID case 'Apache-2.0': // SPDX ID case 'Apache:2.0': case 'http://www.apache.org/licenses/LICENSE-2.0': case 'https://www.apache.org/licenses/LICENSE-2.0': // If you're wondering why Abseil has what appears to be a duplicate copy of // the Apache license, it's because of this: // https://github.com/abseil/abseil-cpp/pull/270/files#r793181143 body = system.File('data/apache-license-2.0').readAsStringSync(); type = LicenseType.apache; case 'Apache-2.0 WITH LLVM-exception': // SPDX ID case 'https://llvm.org/LICENSE.txt': body = system.File('data/apache-license-2.0-with-llvm-exception').readAsStringSync(); type = LicenseType.llvm; case 'https://developers.google.com/open-source/licenses/bsd': body = system.File('data/google-bsd').readAsStringSync(); type = LicenseType.bsd; case 'http://polymer.github.io/LICENSE.txt': body = system.File('data/polymer-bsd').readAsStringSync(); type = LicenseType.bsd; case 'http://www.eclipse.org/legal/epl-v10.html': body = system.File('data/eclipse-1.0').readAsStringSync(); type = LicenseType.eclipse; case 'COPYING3:3': body = system.File('data/gpl-3.0').readAsStringSync(); type = LicenseType.gpl; case 'COPYING.LIB:2': case 'COPYING.LIother.m_:2': // blame hyatt body = system.File('data/library-gpl-2.0').readAsStringSync(); type = LicenseType.lgpl; case 'GNU Lesser:2': // there has never been such a license, but the authors said they meant the LGPL2.1 case 'GNU Lesser:2.1': body = system.File('data/lesser-gpl-2.1').readAsStringSync(); type = LicenseType.lgpl; case 'COPYING.RUNTIME:3.1': case 'GCC Runtime Library Exception:3.1': body = system.File('data/gpl-gcc-exception-3.1').readAsStringSync(); case 'Academic Free License:3.0': body = system.File('data/academic-3.0').readAsStringSync(); type = LicenseType.afl; case 'Mozilla Public License:1.1': body = system.File('data/mozilla-1.1').readAsStringSync(); type = LicenseType.mpl; case 'http://mozilla.org/MPL/2.0/:2.0': body = system.File('data/mozilla-2.0').readAsStringSync(); type = LicenseType.mpl; case 'MIT': // SPDX ID case 'http://opensource->org/licenses/MIT': // i don't even case 'http://opensource.org/licenses/MIT': case 'https://opensource.org/licenses/MIT': body = system.File('data/mit').readAsStringSync(); type = LicenseType.mit; case 'Unicode-DFS-2016': // SPDX ID case 'http://unicode.org/copyright.html#Exhibit1': case 'http://www.unicode.org/copyright.html#License': case 'http://www.unicode.org/copyright.html': case 'http://www.unicode.org/terms_of_use.html': // redirects to copyright.html case 'https://www.unicode.org/copyright.html': case 'https://www.unicode.org/terms_of_use.html': // redirects to copyright.html body = system.File('data/unicode').readAsStringSync(); type = LicenseType.unicode; case 'http://www.ietf.org/rfc/rfc3454.txt': body = system.File('data/ietf').readAsStringSync(); type = LicenseType.ietf; default: throw 'unknown identifyingReference $identifyingReference'; } return License.fromBodyAndType(body, type, origin: '$identifyingReference referenced by $referencer'); } License._(String body, this.type, { required this.origin, String? authors, bool yesWeKnowWhatItLooksLikeButItIsNot = false }) : authors = authors ?? _readAuthors(body) { assert(() { try { switch (type) { case LicenseType.afl: case LicenseType.apsl: case LicenseType.eclipse: case LicenseType.gpl: case LicenseType.lgpl: // We do not want this kind of license in our build. assert(this is DisallowedLicense); case LicenseType.apache: case LicenseType.freetype: case LicenseType.ijg: case LicenseType.ietf: case LicenseType.libpng: case LicenseType.llvm: case LicenseType.unicode: case LicenseType.vulkan: case LicenseType.zlib: assert(this is MessageLicense); case LicenseType.apacheNotice: assert(this is UniqueLicense); case LicenseType.bison: assert(this is BlankLicense); case LicenseType.bsd: case LicenseType.mit: assert(this is TemplateLicense); case LicenseType.icu: case LicenseType.openssl: assert(this is MultiLicense); case LicenseType.mpl: assert(this is MozillaLicense); case LicenseType.unknown: assert(this is MessageLicense || this is UniqueLicense); case LicenseType.defaultTemplate: assert(false, 'should not be creating LicenseType.defaultTemplate license'); } } on AssertionError { throw 'incorrectly created a $runtimeType for a $type'; } return true; }()); final LicenseType detectedType = convertBodyToType(body); if (detectedType != LicenseType.unknown && detectedType != type && !yesWeKnowWhatItLooksLikeButItIsNot) { throw 'Created a license of type $type but it looks like $detectedType:\n---------\n$body\n-----------'; } if (type != LicenseType.apache && type != LicenseType.llvm && type != LicenseType.vulkan && type != LicenseType.apacheNotice && body.contains('Apache')) { throw 'Non-Apache license (type=$type, detectedType=$detectedType) contains the word "Apache"; maybe it\'s a notice?:\n---\n$body\n---'; } if (detectedType != LicenseType.unknown && detectedType != type && !yesWeKnowWhatItLooksLikeButItIsNot) { throw 'Created a license of type $type but it looks like $detectedType.'; } if (body.contains(trailingColon)) { throw 'incomplete license detected:\n---\n$body\n---'; } bool isUTF8 = true; late List<int> latin1Encoded; try { latin1Encoded = latin1.encode(body); isUTF8 = false; } on ArgumentError { /* Fall through to next encoding check. */ } if (!isUTF8) { bool isAscii = false; try { ascii.decode(latin1Encoded); isAscii = true; } on FormatException { /* Fall through to next encoding check */ } if (isAscii) { return; } try { utf8.decode(latin1Encoded); isUTF8 = true; } on FormatException { /* We check isUTF8 below and throw if necessary */ } if (isUTF8) { throw 'tried to create a License object with text that appears to have been misdecoded as Latin1 instead of as UTF-8:\n$body'; } } } final String? authors; final String origin; final LicenseType type; Assignment assignLicenses(String target, LicenseSource source) { return Assignment(this, target, source); } // This takes a second license, which has been pre-split into copyright and // licenseBody, and uses this license to expand it into a new license. How // this works depends on this license; for example BSD licenses typically take // their body and put on the given copyright, (and the licenseBody argument // here in those cases is usually a reference to that license); some other // licenses turn into two, one for the original license and one for this // copyright/body pair. Iterable<License> _expandTemplate(String copyright, String licenseBody, { required String origin }); String toStringBody(LicenseSource source); static final RegExp _copyrightForAuthors = RegExp( r'Copyright [-0-9 ,(cC)©]+\b(The .+ Authors)\.', caseSensitive: false ); static String? _readAuthors(String body) { final List<Match> matches = _copyrightForAuthors.allMatches(body).toList(); if (matches.isEmpty) { return null; } if (matches.length > 1) { throw 'found too many authors for this copyright:\n$body\n\n${StackTrace.current}\n\n'; } return matches[0].group(1); } @override String toString() => '$runtimeType ($type) from $origin'; } class _LineRange { _LineRange(this.start, this.end, this._body); final int start; final int end; final String _body; String? _value; String get value { _value ??= _body.substring(start, end); return _value!; } } Iterable<_LineRange> _walkLinesBackwards(String body, int start) sync* { int? end; while (start > 0) { start -= 1; if (body[start] == '\n') { if (end != null) { yield _LineRange(start + 1, end, body); } end = start; } } if (end != null) { yield _LineRange(start, end, body); } } Iterable<_LineRange> _walkLinesForwards(String body, { int start = 0, int? end }) sync* { int? startIndex = start == 0 || body[start-1] == '\n' ? start : null; int endIndex = startIndex ?? start; end ??= body.length; while (endIndex < end) { if (body[endIndex] == '\n') { if (startIndex != null) { yield _LineRange(startIndex, endIndex, body); } startIndex = endIndex + 1; } endIndex += 1; } if (startIndex != null) { yield _LineRange(startIndex, endIndex, body); } } class _SplitLicense { _SplitLicense(this._body, this._split) : assert(_split == 0 || _split == _body.length || _body[_split] == '\n'); final String _body; final int _split; String getCopyright() => _body.substring(0, _split); String getConditions() => _split >= _body.length ? '' : _body.substring(_split == 0 ? 0 : _split + 1); } _SplitLicense _splitLicense(String body, { bool verifyResults = true }) { final Iterator<_LineRange> lines = _walkLinesForwards(body).iterator; if (!lines.moveNext()) { throw 'tried to split empty license'; } int end = 0; String endReason; while (true) { final String line = lines.current.value; if (line == 'Author:' || line == 'This code is derived from software contributed to Berkeley by' || line == 'The Initial Developer of the Original Code is') { if (!lines.moveNext()) { throw 'unexpected end of block instead of author when looking for copyright'; } if (lines.current.value.trim() == '') { throw 'unexpectedly blank line instead of author when looking for copyright'; } end = lines.current.end; if (!lines.moveNext()) { endReason = 'ran out of text after author'; break; } } else if (line.startsWith('Authors:') || line == 'Other contributors:') { if (line != 'Authors:') { // assume this line contained an author as well end = lines.current.end; } if (!lines.moveNext()) { throw 'unexpected end of license when reading list of authors while looking for copyright'; } final String firstAuthor = lines.current.value; int subindex = 0; while (subindex < firstAuthor.length && (firstAuthor[subindex] == ' ')) { subindex += 1; } if (subindex == 0 || subindex > firstAuthor.length) { throw 'unexpected blank line instead of authors found when looking for copyright'; } end = lines.current.end; final String prefix = firstAuthor.substring(0, subindex); bool hadMoreLines; while ((hadMoreLines = lines.moveNext()) && lines.current.value.startsWith(prefix)) { final String nextAuthor = lines.current.value.substring(prefix.length); if (nextAuthor == '' || nextAuthor[0] == ' ') { throw 'unexpectedly ragged author list when looking for copyright'; } end = lines.current.end; } if (!hadMoreLines) { endReason = 'ran out of text while collecting authors'; break; } } else if (line.contains(halfCopyrightPattern)) { do { if (!lines.moveNext()) { throw 'unexpected end of block instead of copyright holder when looking for copyright'; } if (lines.current.value.trim() == '') { throw 'unexpectedly blank line instead of copyright holder when looking for copyright'; } end = lines.current.end; } while (lines.current.value.contains(trailingComma)); if (!lines.moveNext()) { endReason = 'ran out of text after matching halfCopyrightPattern/trailingComma sequence'; break; } } else if (copyrightStatementPatterns.any(line.contains)) { end = lines.current.end; if (!lines.moveNext()) { endReason = 'ran out of text after copyright statement pattern'; break; } } else { endReason = 'line did not match any copyright patterns ("$line")'; break; } } if (verifyResults && 'Copyright ('.allMatches(body, end).isNotEmpty && !body.startsWith('If you modify libpng')) { throw 'the license seems to contain a copyright:\n===copyright===\n${body.substring(0, end)}\n===license===\n${body.substring(end)}\n=========\ntermination reason: $endReason'; } return _SplitLicense(body, end); } class _PartialLicenseMatch { _PartialLicenseMatch(this._body, this.start, this.split, this.end, this._match, { required this.hasCopyrights }) : assert(split >= start), assert(split == start || _body[split] == '\n'); final String _body; final int start; final int split; final int end; final Match _match; String? group(int? index) => _match.group(index!); String? getAuthors() { final Match? match = authorPattern.firstMatch(getCopyrights()); if (match != null) { return match.group(1); } return null; } String getCopyrights() => _body.substring(start, split); String getConditions() => _body.substring(split + 1, end); String getEntireLicense() => _body.substring(start, end); final bool hasCopyrights; } // Look for all matches of `pattern` in `body` and return them along with associated copyrights. Iterable<_PartialLicenseMatch> _findLicenseBlocks(String body, RegExp pattern, int firstPrefixIndex, int indentPrefixIndex, { bool needsCopyright = true }) sync* { // I tried doing this with one big RegExp initially, but that way lay madness. for (final Match match in pattern.allMatches(body)) { assert(match.groupCount >= firstPrefixIndex); assert(match.groupCount >= indentPrefixIndex); int start = match.start; final String fullPrefix = '${match.group(firstPrefixIndex)}${match.group(indentPrefixIndex)}'; // first we walk back to the start of the block that has the same prefix (e.g. // the start of this comment block) int firstLineOffset = 0; bool lastWasBlank = false; bool foundNonBlank = false; for (final _LineRange range in _walkLinesBackwards(body, start)) { String line = range.value; bool isBlockCommentLine; if (line.length > 3 && line.endsWith('*/')) { int index = line.length - 3; while (line[index] == ' ') { index -= 1; } line = line.substring(0, index + 1); isBlockCommentLine = true; } else { isBlockCommentLine = false; } if (line.isEmpty || fullPrefix.startsWith(line)) { // this is a blank line if (lastWasBlank && (foundNonBlank || !needsCopyright)) { break; } lastWasBlank = true; } else if (!isBlockCommentLine && line.startsWith('/*')) { start = range.start; firstLineOffset = 2; break; } else if (line.startsWith('<!--')) { start = range.start; firstLineOffset = 4; break; } else if (fullPrefix.isNotEmpty && !line.startsWith(fullPrefix)) { break; } else if (licenseFragments.any((RegExp pattern) => line.contains(pattern))) { // we're running into another license, abort, abort! break; } else { lastWasBlank = false; foundNonBlank = true; } start = range.start; } // then we walk forward dropping anything until the first line that matches what // we think might be part of a copyright statement bool foundAny = false; RegExp? debugFirstPattern; copyrightSearch: for (final _LineRange range in _walkLinesForwards(body, start: start, end: match.start)) { String line = range.value; if (firstLineOffset > 0) { line = line.substring(firstLineOffset); firstLineOffset = 0; } else if (line.startsWith(fullPrefix)) { line = line.substring(fullPrefix.length); } else { assert(line.isEmpty || fullPrefix.startsWith(line), 'invariant violated: expected this to be a blank line but it was "$line" (prefix is "$fullPrefix").'); continue copyrightSearch; } for (final RegExp pattern in copyrightStatementLeadingPatterns) { if (line.contains(pattern)) { start = range.start; foundAny = true; debugFirstPattern = pattern; break copyrightSearch; } } } // At this point we have figured out what might be copyright text before the license (if anything). int split; if (!foundAny) { if (needsCopyright) { throw 'could not find copyright before license\nlicense body was:\n---\n${body.substring(match.start, match.end)}\n---\nfile was:\n---\n$body\n---'; } start = match.start; split = match.start; } else { final String copyrights = body.substring(start, match.start); final String undecoratedCopyrights = reformat(copyrights); // Let's try splitting the copyright block as if it was a license. // This will tell us if we collected something in the copyright block // that was more license than copyright and that therefore should be // examined closer. final _SplitLicense consistencyCheck = _splitLicense(undecoratedCopyrights, verifyResults: false); final String conditions = consistencyCheck.getConditions(); if (conditions != '') { // Copyright lines long enough to spill to a second line can create // false positives; try to weed those out. final String resplitCopyright = consistencyCheck.getCopyright(); if (resplitCopyright.trim().contains('\n') || conditions.trim().contains('\n') || resplitCopyright.length < 70 || conditions.length > 15) { throw 'potential license text caught in _findLicenseBlocks copyright dragnet:\n---\n$conditions\n---\nundecorated copyrights was:\n---\n$undecoratedCopyrights\n---\ncopyrights was:\n---\n$copyrights\n---\nblock was:\n---\n${body.substring(start, match.end)}\n---\nfirst line matched: $debugFirstPattern\n---\npattern:\n$pattern\n---\n${StackTrace.current}\n============='; } } if (!copyrights.contains(anySlightSignOfCopyrights)) { throw 'could not find copyright before license block:\n---\ncopyrights was:\n---\n$copyrights\n---\nblock was:\n---\n${body.substring(start, match.end)}\n---'; } assert(body[match.start - 1] == '\n', 'match did not start at a newline; match.start = ${match.start}, match.end = ${match.end}, split at: "${body[match.start - 1]}"'); split = match.start - 1; } yield _PartialLicenseMatch(body, start, split, match.end, match, hasCopyrights: foundAny); } } class _LicenseMatch { _LicenseMatch(this.license, this.start, this.end, { this.debug = '', this.ignoreWhenCheckingOverlappingRegions = false, this.missingCopyrights = false }); final License license; final int start; final int end; final String debug; final bool ignoreWhenCheckingOverlappingRegions; final bool missingCopyrights; @override String toString() { return '$start..$end: $license'; } } Iterable<_LicenseMatch> _expand(License template, String copyright, String body, int start, int end, { String debug = '', required String origin }) sync* { final List<License> results = template._expandTemplate(reformat(copyright), body, origin: origin).toList(); if (results.isEmpty) { throw 'license could not be expanded'; } yield _LicenseMatch(results.first, start, end, debug: 'expanding template for $debug'); if (results.length > 1) { yield* results.skip(1).map((License license) => _LicenseMatch(license, start, end, ignoreWhenCheckingOverlappingRegions: true, debug: 'expanding subsequent template for $debug')); } } Iterable<_LicenseMatch> _tryReferenceByFilename(String body, LicenseFileReferencePattern pattern, LicenseSource parentDirectory, { required String origin }) sync* { if (pattern.copyrightIndex != null) { for (final Match match in pattern.pattern.allMatches(body)) { final String copyright = match.group(pattern.copyrightIndex!)!; final String? authors = pattern.authorIndex != null ? match.group(pattern.authorIndex!) : null; final String filename = match.group(pattern.fileIndex)!; final License? template = parentDirectory.nearestLicenseWithName(filename, authors: authors); if (template == null) { throw 'failed to find template $filename in $parentDirectory (authors=$authors)'; } assert(reformat(copyright) != ''); final String entireLicense = body.substring(match.start, match.end); yield* _expand(template, copyright, entireLicense, match.start, match.end, debug: '_tryReferenceByFilename (with explicit copyright) looking for $filename', origin: origin); } } else { for (final _PartialLicenseMatch match in _findLicenseBlocks(body, pattern.pattern, pattern.firstPrefixIndex, pattern.indentPrefixIndex, needsCopyright: pattern.needsCopyright)) { final String? authors = match.getAuthors(); String? filename = match.group(pattern.fileIndex); if (filename == 'modp_b64.c') { filename = 'modp_b64.cc'; // it was renamed but other files reference the old name } // There's also special cases for fuchsia/sdk/linux/dart/zircon/lib/src/fakes/handle_disposition.dart // (which points to "The Flutter Authors" instead of "The Fuchsia Authors" for mysterious reasons) and // third_party/angle/src/common/fuchsia_egl/fuchsia_egl.* (which does something similar), but those // files never reach here because they're marked as binary files in filesystem.dart. final License? template = parentDirectory.nearestLicenseWithName(filename!, authors: authors); if (template == null) { throw 'failed to find accompanying "$filename" in $parentDirectory\n' 'block:\n---\n${match.getEntireLicense()}\n---'; } if (match.getCopyrights() == '') { yield _LicenseMatch(template, match.start, match.end, debug: '_tryReferenceByFilename (with failed copyright search) looking for $filename'); } else { yield* _expand(template, match.getCopyrights(), match.getEntireLicense(), match.start, match.end, debug: '_tryReferenceByFilename (with successful copyright search) looking for $filename', origin: origin); } } } } Iterable<_LicenseMatch> _tryReferenceByType(String body, RegExp pattern, LicenseSource parentDirectory, { required String origin }) sync* { for (final _PartialLicenseMatch match in _findLicenseBlocks(body, pattern, 1, 2, needsCopyright: false)) { final LicenseType type = convertLicenseNameToType(match.group(3)); final License? template = parentDirectory.nearestLicenseOfType(type); if (template == null) { throw 'failed to find accompanying $type license in $parentDirectory'; } if (match.getCopyrights() == '') { yield _LicenseMatch(template, match.start, match.end, debug: '_tryReferenceByType (without copyrights) for type $type'); } else { yield* _expand(template, match.getCopyrights(), match.getEntireLicense(), match.start, match.end, debug: '_tryReferenceByType (with successful copyright search) for type $type', origin: origin); } } } License _dereferenceLicense(int groupIndex, String? Function(int index) group, LicenseReferencePattern pattern, LicenseSource parentDirectory, { required String origin }) { License? result = pattern.checkLocalFirst ? parentDirectory.nearestLicenseWithName(group(groupIndex)!) : null; result ??= License.fromIdentifyingReference(group(groupIndex)!, referencer: origin); return result; } Iterable<_LicenseMatch> _tryReferenceByIdentifyingReference(String body, LicenseReferencePattern pattern, LicenseSource parentDirectory, { required String origin }) sync* { for (final _PartialLicenseMatch match in _findLicenseBlocks(body, pattern.pattern!, 1, 2, needsCopyright: false)) { if (pattern.spdx) { // Per legal advice, we allowlist the use of SPDX headers. Currently, we // recognize SPDX headers in code from Khronos. To identify such code, we // examine the copyright that came with the SPDX header or we look at the // library name. We also accept the headers in some libcxx files that have // their own license and that otherwise would trip up our code checking // for missed licenses and copyrights. To identify those, we use the // library name and the parent directory name or copyright. bool allowSpdx = false; final String copyrights = match.getCopyrights(); if (copyrights.contains('The Khronos Group') || parentDirectory.libraryName == 'spirv-cross' || (parentDirectory.libraryName == 'libcxx' && parentDirectory.name == 'ryu') || (parentDirectory.libraryName == 'libcxx' && copyrights.contains('Microsoft'))) { allowSpdx = true; } if (!allowSpdx) { // Skip this match. continue; } } assert(match.group(3) != null, 'pattern ${pattern.pattern!} did not have three groups when matched against:\n---\n$body\n---\nmatch: $match'); final License template = _dereferenceLicense(3, match.group, pattern, parentDirectory, origin: origin); if (match.getCopyrights() == '') { yield _LicenseMatch(template, match.start, match.end, debug: '_tryReferenceByIdentifyingReference (without copyrights)'); } else { yield* _expand(template, match.getCopyrights(), match.getEntireLicense(), match.start, match.end, debug: '_tryReferenceByIdentifyingReference (with copyright)', origin: origin); } } } Iterable<_LicenseMatch> _tryInline(String body, RegExp pattern, { required bool needsCopyright, required String origin, }) sync* { for (final _PartialLicenseMatch match in _findLicenseBlocks(body, pattern, 1, 2, needsCopyright: needsCopyright)) { yield _LicenseMatch(License.fromBody(match.getEntireLicense(), origin: origin), match.start, match.end, debug: '_tryInline', missingCopyrights: needsCopyright && !match.hasCopyrights); } } Iterable<_LicenseMatch> _tryStray(String body, RegExp pattern, LicenseSource parentDirectory, { required String origin }) sync* { // this one doesn't look for copyrights (that's the point, the patterns _are_ the copyrights) bool gotTemplate = false; License? template; for (final Match match in pattern.allMatches(body)) { if (!gotTemplate) { template = parentDirectory.nearestLicenseOfType(LicenseType.defaultTemplate); gotTemplate = true; } if (template != null) { yield* _expand(template, match.group(0)!, match.group(0)!, match.start, match.end, debug: '_tryStray (with template)', origin: origin); } else { yield _LicenseMatch(License.fromBody(match.group(0)!, origin: origin), match.start, match.end, debug: '_tryStray'); } } } Iterable<_LicenseMatch> _tryForwardReferencePattern(String fileContents, ForwardReferencePattern pattern, License template, LicenseSource source, { required String origin }) sync* { String? body; for (final _PartialLicenseMatch match in _findLicenseBlocks(fileContents, pattern.pattern, pattern.firstPrefixIndex, pattern.indentPrefixIndex)) { body ??= template.toStringBody(source); if (!body.contains(pattern.targetPattern)) { throw 'forward license reference to unexpected license\n' 'license:\n---\n$body\n---\nexpected pattern:\n---\n${pattern.targetPattern}\n---'; } yield* _expand(template, match.getCopyrights(), match.getEntireLicense(), match.start, match.end, debug: '_tryForwardReferencePattern', origin: origin); } } List<License> determineLicensesFor(String fileContents, String filename, LicenseSource? parentDirectory, { required String origin }) { if (parentDirectory == null) { throw 'Fatal error: determineLicensesFor was called with parentDirectory=null!'; } if (fileContents.length > kMaxSize) { fileContents = fileContents.substring(0, kMaxSize); } final List<_LicenseMatch> results = <_LicenseMatch>[]; fileContents = stripAsciiArt(fileContents); results.addAll(csReferencesByFilename.expand((LicenseFileReferencePattern pattern) => _tryReferenceByFilename(fileContents, pattern, parentDirectory, origin: origin))); results.addAll(csReferencesByType.expand((RegExp pattern) => _tryReferenceByType(fileContents, pattern, parentDirectory, origin: origin))); results.addAll(csReferencesByIdentifyingReference.expand((LicenseReferencePattern pattern) => _tryReferenceByIdentifyingReference(fileContents, pattern, parentDirectory, origin: origin))); results.addAll(csTemplateLicenses.expand((RegExp pattern) => _tryInline(fileContents, pattern, needsCopyright: true, origin: origin))); results.addAll(csNoticeLicenses.expand((RegExp pattern) => _tryInline(fileContents, pattern, needsCopyright: false, origin: origin))); _LicenseMatch? usedTemplate; if (results.length == 1) { final _LicenseMatch target = results.single; results.addAll(csForwardReferenceLicenses.expand((ForwardReferencePattern pattern) => _tryForwardReferencePattern(fileContents, pattern, target.license, parentDirectory, origin: origin))); if (results.length > 1) { usedTemplate = target; } } for (final _LicenseMatch match in results.where((_LicenseMatch match) => match.missingCopyrights)) { throw 'found a license for $filename but could not match its copyright:\n----8<----\n${match.license}\n----8<----'; } if (results.isEmpty) { if ((fileContents.contains(copyrightMentionPattern) && fileContents.contains(licenseMentionPattern)) && !fileContents.contains(copyrightMentionOkPattern)) { throw 'failed to find any license but saw unmatched potential copyright and license statements; first twenty lines:\n----8<----\n${fileContents.split("\n").take(20).join("\n")}\n----8<----'; } } // Some files have the odd copyright that isn't explicitly attached to a // license; we treat those as notice licenses. Only such copyrights // allowlisted in csStrayCopyrights are handled this way, though. For each of // these, we have to make sure they don't overlap any of the actual licenses // matched earlier, so we check for overlaps on each one first. strays: for (final _LicenseMatch stray in csStrayCopyrights.expand((RegExp pattern) => _tryStray(fileContents, pattern, parentDirectory, origin: origin))) { for (final _LicenseMatch full in results) { if (stray.start >= full.start && stray.end <= full.end) { continue strays; } } results.add(stray); } final List<_LicenseMatch> verificationList = results.toList(); if (usedTemplate != null && !verificationList.contains(usedTemplate)) { verificationList.add(usedTemplate); } verificationList.sort((_LicenseMatch a, _LicenseMatch b) { final int result = a.start - b.start; if (result != 0) { return result; } return a.end - b.end; }); int position = 0; for (final _LicenseMatch m in verificationList) { if (m.ignoreWhenCheckingOverlappingRegions) { continue; } // some text expanded into multiple licenses, so overlapping is expected if (position > m.start) { system.stderr.writeln('\n\noverlapping licenses:'); for (final _LicenseMatch n in results) { system.stderr.writeln( 'license match: ${n.start}..${n.end}, ${n.license.runtimeType}, ${n.debug}\n' ' first line: ${n.license.toStringBody(parentDirectory).split("\n").first}\n' ' last line: ${n.license.toStringBody(parentDirectory).split("\n").last}' ); } throw 'overlapping licenses in $filename (one ends at $position, another starts at ${m.start})'; } if (position < m.start) { final String substring = fileContents.substring(position, m.start); if (substring.contains(copyrightMentionPattern) && !substring.contains(copyrightMentionOkPattern)) { throw 'there is another unmatched potential copyright statement in $filename:\n $position..${m.start}: "$substring"\nmatched licenses: $results'; } if (substring.contains(licenseMentionPattern)) { throw 'there is another unmatched potential license in $filename:\n $position..${m.start}: "$substring"\nmatched licenses: $results'; } } position = m.end; } final String substring = fileContents.substring(position); if (substring.contains(copyrightMentionPattern) && !substring.contains(copyrightMentionOkPattern)) { throw 'there is an unmatched potential copyright statement in $filename:\n $position..end: "$substring"\nmatched licenses: $results'; } if (substring.contains(licenseMentionPattern)) { throw 'there is an unmatched potential license in $filename:\n $position..end: "$substring"\nmatched licenses: $results'; } return results.map((_LicenseMatch entry) => entry.license).toSet().toList(); } License? interpretAsRedirectLicense(String fileContents, LicenseSource parentDirectory, { required String origin }) { _SplitLicense split; try { split = _splitLicense(fileContents); } on String { return null; } final String body = split.getConditions().trim(); License? result; for (final LicenseReferencePattern pattern in csReferencesByIdentifyingReference) { if (pattern.spdx) { // We don't support SPDX headers in files that use _RepositoryLicenseRedirectFile. // Before changing this, obtain legal advice. continue; } final Match? match = pattern.pattern!.matchAsPrefix(body); if (match != null && match.start == 0 && match.end == body.length) { final License candidate = _dereferenceLicense(3, match.group as String? Function(int?), pattern, parentDirectory, origin: origin); if (result != null) { throw 'Multiple potential matches in interpretAsRedirectLicense in $parentDirectory; body was:\n------8<------\n$fileContents\n------8<------'; } result = candidate; } } return result; } // the kind of license that just wants to show a message (e.g. the JPEG one) class MessageLicense extends License { MessageLicense._(this.body, LicenseType type, { required String origin }) : super._(body, type, origin: origin); final String body; @override String toStringBody(LicenseSource source) => body; @override Iterable<License> _expandTemplate(String copyright, String licenseBody, { required String origin }) => <License>[this]; } // the kind of license that says to include the copyright and the license text (e.g. BSD) class TemplateLicense extends License { TemplateLicense._(this.defaultCopyright, this.terms, LicenseType type, { String? authors, required String origin }) : assert(!defaultCopyright.endsWith('\n')), assert(!terms.startsWith('\n')), assert(terms.isNotEmpty), super._('$defaultCopyright\n\n$terms', type, origin: origin, authors: authors); factory TemplateLicense._autosplit(String body, LicenseType type, { String? authors, required String origin }) { final _SplitLicense bits = _splitLicense(body); final String copyright = bits.getCopyright(); final String terms = bits.getConditions(); assert((copyright.isEmpty && terms == body) || ('$copyright\n$terms' == body) || (copyright == body && terms.isEmpty), '_splitLicense contract violation.\nCOPYRIGHT:\n===\n$copyright\n===\nTERMS:\n===\n$terms\n===\nBODY:\n===\n$body\n===\n'); int copyrightLength = copyright.length; while (copyrightLength > 0 && copyright[copyrightLength - 1] == '\n') { copyrightLength -= 1; } int termsStart = 0; while (termsStart < terms.length && terms[termsStart] == '\n') { termsStart += 1; } return TemplateLicense._( copyright.substring(0, copyrightLength), terms.substring(termsStart), type, authors: authors, origin: origin, ); } final String defaultCopyright; final String terms; @override String toStringBody(LicenseSource source) { if (defaultCopyright.isEmpty) { return terms; } return '$defaultCopyright\n\n$terms'; } @override Iterable<License> _expandTemplate(String copyright, String licenseBody, { required String origin }) { return <License>[ License.fromCopyrightAndLicense(copyright, terms, type, origin: '$origin + ${this.origin}') ]; } } // The kind of license that expands to two license blocks a main license and the referring block // (e.g. OpenSSL). // // This is a lawyer-suggested workaround for handling BSD-style licenses where instead of there // being a single license block where it's obvious what is meant by "above copyright notice" and // "this list of conditions", we instead have a bunch of similar licenses, each with their own // copyright, plus there's a copyright in the file that (probably) doesn't exactly match any of the // copyrights in the file, plus some text saying that that license applies to the file. class MultiLicense extends License { MultiLicense._(this.body, LicenseType type, { String? authors, required String origin, bool yesWeKnowWhatItLooksLikeButItIsNot = false, }) : super._(body, type, origin: origin, authors: authors, yesWeKnowWhatItLooksLikeButItIsNot: yesWeKnowWhatItLooksLikeButItIsNot); final String body; @override String toStringBody(LicenseSource source) => body; @override Iterable<License> _expandTemplate(String copyright, String licenseBody, { required String origin }) { // Sometimes a license (e.g. the OpenSSL license in the BoringSSL package) is referenced // from a file that has its own copyright header. When that happens we just print the referenced // license and the reference to that license separately because it's not at all clear how we're // supposed to merge them otherwise. licenseBody = reformat(licenseBody); assert(licenseBody.startsWith(copyright), 'copyright:\n---\n$copyright\n---\nlicenseBody:\n---\n$licenseBody\n---'); return <License>[ this, License.fromBody(licenseBody, origin: '$origin (with ${this.origin})', reformatted: true), ]; } } // the kind of license that should not be combined with separate copyright notices class UniqueLicense extends License { UniqueLicense._(this.body, LicenseType type, { required String origin, String? authors, bool yesWeKnowWhatItLooksLikeButItIsNot = false }) : super._(body, type, origin: origin, yesWeKnowWhatItLooksLikeButItIsNot: yesWeKnowWhatItLooksLikeButItIsNot, authors: authors); final String body; @override String toStringBody(LicenseSource source) => body; @override Iterable<License> _expandTemplate(String copyright, String licenseBody, { required String origin }) { throw 'attempted to expand non-template license with "$copyright"\ntemplate was: $this'; } } // the kind of license that doesn't need to be reported anywhere class BlankLicense extends License { BlankLicense._(super.body, super.type, { required super.origin }) : super._(); @override Iterable<License> _expandTemplate(String copyright, String licenseBody, { required String origin }) { // We don't care what copyrights this kind of license has, we don't need // to report them. Just report |this| (which is always blank, see below). return <License>[this]; } @override String toStringBody(LicenseSource source) => ''; } // MPL class MozillaLicense extends License { MozillaLicense._(this.body, LicenseType type, { required String origin }) : assert(type == LicenseType.mpl), super._(body, type, origin: origin); final String body; @override Assignment assignLicenses(String target, LicenseSource source) { if (source.libraryName != 'fallback_root_certificates') { throw 'Only fallack_root_certificates is allowed to use the MPL.'; } return Assignment(this, target, source); } @override Iterable<License> _expandTemplate(String copyright, String licenseBody, { required String origin }) { throw 'attempted to expand non-template license with "$copyright"\ntemplate was: $this'; } @override String toStringBody(LicenseSource source) { final StringBuffer result = StringBuffer(); result.writeln(body); result.writeln(); result.writeln("You may obtain a copy of this library's Source Code Form from: ${source.officialSourceLocation}"); return result.toString(); } } class DisallowedLicense extends License { DisallowedLicense._(this.body, LicenseType type, { required String origin }) : super._(body, type, origin: origin); final String body; @override Assignment assignLicenses(String target, LicenseSource source) { throw '$target (in ${source.libraryName}) attempted to use $origin which is a disallowed license type ($type)'; } @override Iterable<License> _expandTemplate(String copyright, String licenseBody, { required String origin }) { throw 'attempted to use $origin which is a disallowed license type ($type)'; } @override String toStringBody(LicenseSource source) { throw '${source.libraryName} attempted to use $origin which is a disallowed license type ($type)'; } }
engine/tools/licenses/lib/licenses.dart/0
{ "file_path": "engine/tools/licenses/lib/licenses.dart", "repo_id": "engine", "token_count": 19155 }
494
## Overview This package contains libraries and example code for working with the engine_v2 build config json files that live under `flutter/ci/builders`. * `lib/src/build_config.dart`: Contains the Dart object representations of the build config json files. * `lib/src/build_config_loader.dart`: Contains a helper class for loading all of the build configuration json files in a directory tree into the Dart objects. * `lib/src/build_config_runner.dart`: Contains classes that run a loaded build config on the local machine. There is some example code using these APIs under the `bin/` directory. * `bin/check.dart`: Checks the validity of the build config json files. This runs on CI in pre and post submit in `ci/check_build_configs.sh` through `ci/builders/linux_unopt.json`. * `bin/run.dart`: Runs one build from a build configuration on the local machine. It doesn't run generators or tests, and it isn't run on CI. ## Usage ### `run.dart` usage: ``` $ dart bin/run.dart [build config name] [build name] ``` For example: ``` $ dart bin/run.dart mac_unopt host_debug_unopt ``` The build config names are the names of the json files under ci/builders. The build names are the "name" fields of the maps in the list of "builds". ### `check.dart` usage: ``` $ dart bin/check.dart [/path/to/engine/src] ``` The path to the engine source is optional when the current working directory is inside of an engine checkout.
engine/tools/pkg/engine_build_configs/README.md/0
{ "file_path": "engine/tools/pkg/engine_build_configs/README.md", "repo_id": "engine", "token_count": 431 }
495
// 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. /// A minimal library for discovering and probing a local engine repository. /// /// This library is intended to be used by tools that need to interact with a /// local engine repository, such as `clang_tidy` or `githooks`. For example, /// finding the `compile_commands.json` file for the most recently built output: /// /// ```dart /// final Engine engine = Engine.findWithin(); /// final Output? output = engine.latestOutput(); /// if (output == null) { /// print('No output targets found.'); /// } else { /// final io.File? compileCommandsJson = output.compileCommandsJson; /// if (compileCommandsJson == null) { /// print('No compile_commands.json file found.'); /// } else { /// print('Found compile_commands.json file at ${compileCommandsJson.path}'); /// } /// } /// ``` library; import 'dart:io' as io; import 'package:path/path.dart' as p; /// Represents the `$ENGINE` directory (i.e. a checked-out Flutter engine). /// /// If you have a path to the `$ENGINE/src` directory, use [Engine.fromSrcPath]. /// /// If you have a path to a directory within the `$ENGINE/src` directory, or /// want to use the current working directory, use [Engine.findWithin]. final class Engine { const Engine._({ required this.srcDir, required this.flutterDir, required this.outDir, }); /// Creates an [Engine] from a path such as `/Users/.../flutter/engine/src`. /// /// ```dart /// final Engine engine = Engine.findWithin('/Users/.../engine/src'); /// print(engine.srcDir.path); // /Users/.../engine/src /// ``` /// /// Throws a [InvalidEngineException] if the path is not a valid engine root. factory Engine.fromSrcPath(String srcPath) { // If the path does not end in `/src`, fail. if (p.basename(srcPath) != 'src') { throw InvalidEngineException.doesNotEndWithSrc(srcPath); } // If the directory does not exist, or is not a directory, fail. final io.Directory srcDir = io.Directory(srcPath); if (!srcDir.existsSync()) { throw InvalidEngineException.notADirectory(srcPath); } // Check for the existence of a `flutter` directory within `src`. final io.Directory flutterDir = io.Directory(p.join(srcPath, 'flutter')); if (!flutterDir.existsSync()) { throw InvalidEngineException.missingFlutterDirectory(srcPath); } // We do **NOT** check for the existence of a `out` directory within `src`, // it's not required to exist (i.e. a new checkout of the engine), and we // don't want to fail if it doesn't exist. final io.Directory outDir = io.Directory(p.join(srcPath, 'out')); return Engine._( srcDir: srcDir, flutterDir: flutterDir, outDir: outDir, ); } /// Creates an [Engine] by looking for a `src/` directory in the given path. /// /// Similar to [tryFindWithin], but throws a [StateError] if the path is not /// within a valid engine. This is useful for tools that require an engine /// and do not have a reasonable fallback or recovery path. factory Engine.findWithin([String? path]) { final Engine? engine = tryFindWithin(path); if (engine == null) { throw StateError('The path "$path" is not within a valid engine.'); } return engine; } /// Creates an [Engine] by looking for a `src/` directory in the given [path]. /// /// ```dart /// // Use the current working directory. /// final Engine engine = Engine.findWithin(); /// print(engine.srcDir.path); // /Users/.../engine/src /// /// // Use a specific directory. /// final Engine engine = Engine.findWithin('/Users/.../engine/src/foo/bar'); /// print(engine.srcDir.path); // /Users/.../engine/src /// ``` /// /// If a [path] is not provided, the current working directory is used. /// /// If path does not exist, or is not a directory, an error is thrown. /// /// Returns `null` if the path is not within a valid engine. static Engine? tryFindWithin([String? path]) { path ??= p.current; // Search parent directories for a `src` directory. io.Directory maybeSrcDir = io.Directory(path); if (!maybeSrcDir.existsSync()) { throw StateError( 'The path "$path" does not exist or is not a directory.' ); } do { try { return Engine.fromSrcPath(maybeSrcDir.path); } on InvalidEngineException { // Ignore, we'll keep searching. } maybeSrcDir = maybeSrcDir.parent; } while (maybeSrcDir.parent.path != maybeSrcDir.path /* at root */); return null; } /// The path to the `$ENGINE/src` directory. final io.Directory srcDir; /// The path to the `$ENGINE/src/flutter` directory. final io.Directory flutterDir; /// The path to the `$ENGINE/src/out` directory. /// /// **NOTE**: This directory may not exist. final io.Directory outDir; /// Returns a list of all output targets in [outDir]. List<Output> outputs() { return outDir .listSync() .whereType<io.Directory>() .map<Output>(Output._) .toList(); } /// Returns the most recently modified output target in [outDir]. /// /// If there are no output targets, returns `null`. Output? latestOutput() { final List<Output> outputs = this.outputs(); if (outputs.isEmpty) { return null; } outputs.sort((Output a, Output b) { return b.path.statSync().modified.compareTo(a.path.statSync().modified); }); return outputs.first; } } /// An implementation of [Engine] that has pre-defined outputs for testing. final class TestEngine extends Engine { /// Creates a [TestEngine] with pre-defined paths. /// /// The [srcDir] and [flutterDir] must exist, but the [outDir] is optional. /// /// Optionally, provide a list of [outputs] to use, otherwise it is empty. TestEngine.withPaths({ required super.srcDir, required super.flutterDir, required super.outDir, List<TestOutput> outputs = const <TestOutput>[], }) : _outputs = outputs, super._() { if (!srcDir.existsSync()) { throw ArgumentError.value(srcDir, 'srcDir', 'does not exist'); } if (!flutterDir.existsSync()) { throw ArgumentError.value(flutterDir, 'flutterDir', 'does not exist'); } } /// Creates a [TestEngine] within a temporary directory. /// /// The [rootDir] is the temporary directory that will contain the engine. /// /// Optionally, provide a list of [outputs] to use, otherwise it is empty. factory TestEngine.createTemp({ required io.Directory rootDir, List<TestOutput> outputs = const <TestOutput>[], }) { final io.Directory srcDir = io.Directory(p.join(rootDir.path, 'src')); final io.Directory flutterDir = io.Directory(p.join(srcDir.path, 'flutter')); final io.Directory outDir = io.Directory(p.join(srcDir.path, 'out')); srcDir.createSync(recursive: true); flutterDir.createSync(recursive: true); outDir.createSync(recursive: true); return TestEngine.withPaths( srcDir: srcDir, flutterDir: flutterDir, outDir: outDir, outputs: outputs, ); } final List<TestOutput> _outputs; @override List<Output> outputs() => List<Output>.unmodifiable(_outputs); @override Output? latestOutput() { if (_outputs.isEmpty) { return null; } _outputs.sort((TestOutput a, TestOutput b) { return b.lastModified.compareTo(a.lastModified); }); return _outputs.first; } } /// An implementation of [Output] that has a pre-defined path for testing. final class TestOutput extends Output { /// Creates a [TestOutput] with a pre-defined path. /// /// Optionally, provide a [lastModified] date. TestOutput(super.path, {DateTime? lastModified}) : lastModified = lastModified ?? _defaultLastModified, super._(); static final DateTime _defaultLastModified = DateTime.now(); /// The last modified date of the output target. final DateTime lastModified; } /// Thrown when an [Engine] could not be created from a path. sealed class InvalidEngineException implements Exception { /// Thrown when an [Engine] was created from a path not ending in `src`. factory InvalidEngineException.doesNotEndWithSrc(String path) { return InvalidEngineSrcPathException._(path); } /// Thrown when an [Engine] was created from a directory that does not exist. factory InvalidEngineException.notADirectory(String path) { return InvalidEngineNotADirectoryException._(path); } /// Thrown when an [Engine] was created from a path not containing `flutter/`. factory InvalidEngineException.missingFlutterDirectory(String path) { return InvalidEngineMissingFlutterDirectoryException._(path); } } /// Thrown when an [Engine] was created from a path not ending in `src`. final class InvalidEngineSrcPathException implements InvalidEngineException { InvalidEngineSrcPathException._(this.path); /// The path that was used to create the [Engine]. final String path; @override String toString() { return 'The path $path does not end in `${p.separator}src`.'; } } /// Thrown when an [Engine] was created from a path that is not a directory. final class InvalidEngineNotADirectoryException implements InvalidEngineException { InvalidEngineNotADirectoryException._(this.path); /// The path that was used to create the [Engine]. final String path; @override String toString() { return 'The path "$path" does not exist or is not a directory.'; } } /// Thrown when an [Engine] was created from a path not containing `flutter/`. final class InvalidEngineMissingFlutterDirectoryException implements InvalidEngineException { InvalidEngineMissingFlutterDirectoryException._(this.path); /// The path that was used to create the [Engine]. final String path; @override String toString() { return 'The path "$path" does not contain a "flutter" directory.'; } } /// Represents a single output target in the `$ENGINE/src/out` directory. final class Output { const Output._(this.path); /// The directory containing the output target. final io.Directory path; /// The `compile_commands.json` file that should exist for this output target. /// /// The file may not exist. io.File get compileCommandsJson { return io.File(p.join(path.path, 'compile_commands.json')); } }
engine/tools/pkg/engine_repo_tools/lib/engine_repo_tools.dart/0
{ "file_path": "engine/tools/pkg/engine_repo_tools/lib/engine_repo_tools.dart", "repo_id": "engine", "token_count": 3393 }
496
# 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. if (is_fuchsia) { import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni") } source_set("vulkan") { sources = [ "vulkan_application.cc", "vulkan_application.h", "vulkan_backbuffer.cc", "vulkan_backbuffer.h", "vulkan_command_buffer.cc", "vulkan_command_buffer.h", "vulkan_debug_report.cc", "vulkan_debug_report.h", "vulkan_device.cc", "vulkan_device.h", "vulkan_image.cc", "vulkan_image.h", "vulkan_native_surface.cc", "vulkan_native_surface.h", "vulkan_skia_proc_table.cc", "vulkan_skia_proc_table.h", "vulkan_surface.cc", "vulkan_surface.h", "vulkan_swapchain.h", "vulkan_utilities.cc", "vulkan_utilities.h", "vulkan_window.cc", "vulkan_window.h", ] if (is_android) { sources += [ "vulkan_native_surface_android.cc", "vulkan_native_surface_android.h", "vulkan_swapchain.cc", ] } else { sources += [ "vulkan_swapchain_stub.cc" ] } deps = [ "procs", "//flutter/flutter_vma:flutter_skia_vma", "//flutter/fml", "//flutter/skia", ] public_configs = [ "//flutter:config" ] public_deps = [ "//flutter/third_party/vulkan-deps/vulkan-headers/src:vulkan_headers" ] }
engine/vulkan/BUILD.gn/0
{ "file_path": "engine/vulkan/BUILD.gn", "repo_id": "engine", "token_count": 631 }
497
// 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 "vulkan_debug_report.h" #include <algorithm> #include <iomanip> #include <vector> #include "flutter/fml/compiler_specific.h" #include "vulkan_utilities.h" namespace vulkan { static const VkDebugReportFlagsEXT kVulkanErrorFlags FML_ALLOW_UNUSED_TYPE = VK_DEBUG_REPORT_WARNING_BIT_EXT | VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT | VK_DEBUG_REPORT_ERROR_BIT_EXT; static const VkDebugReportFlagsEXT kVulkanInfoFlags FML_ALLOW_UNUSED_TYPE = VK_DEBUG_REPORT_INFORMATION_BIT_EXT | VK_DEBUG_REPORT_DEBUG_BIT_EXT; std::string VulkanDebugReport::DebugExtensionName() { return VK_EXT_DEBUG_REPORT_EXTENSION_NAME; } static const char* VkDebugReportFlagsEXTToString(VkDebugReportFlagsEXT flags) { if (flags & VK_DEBUG_REPORT_INFORMATION_BIT_EXT) { return "Information"; } else if (flags & VK_DEBUG_REPORT_WARNING_BIT_EXT) { return "Warning"; } else if (flags & VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT) { return "Performance Warning"; } else if (flags & VK_DEBUG_REPORT_ERROR_BIT_EXT) { return "Error"; } else if (flags & VK_DEBUG_REPORT_DEBUG_BIT_EXT) { return "Debug"; } return "UNKNOWN"; } static const char* VkDebugReportObjectTypeEXTToString( VkDebugReportObjectTypeEXT type) { switch (type) { case VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT: return "Unknown"; case VK_DEBUG_REPORT_OBJECT_TYPE_INSTANCE_EXT: return "Instance"; case VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT: return "Physical Device"; case VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT: return "Device"; case VK_DEBUG_REPORT_OBJECT_TYPE_QUEUE_EXT: return "Queue"; case VK_DEBUG_REPORT_OBJECT_TYPE_SEMAPHORE_EXT: return "Semaphore"; case VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT: return "Command Buffer"; case VK_DEBUG_REPORT_OBJECT_TYPE_FENCE_EXT: return "Fence"; case VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT: return "Device Memory"; case VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT: return "Buffer"; case VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT: return "Image"; case VK_DEBUG_REPORT_OBJECT_TYPE_EVENT_EXT: return "Event"; case VK_DEBUG_REPORT_OBJECT_TYPE_QUERY_POOL_EXT: return "Query Pool"; case VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_VIEW_EXT: return "Buffer View"; case VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_VIEW_EXT: return "Image_view"; case VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT: return "Shader Module"; case VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_CACHE_EXT: return "Pipeline Cache"; case VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_LAYOUT_EXT: return "Pipeline Layout"; case VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT: return "Render Pass"; case VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT: return "Pipeline"; case VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT_EXT: return "Descriptor Set Layout"; case VK_DEBUG_REPORT_OBJECT_TYPE_SAMPLER_EXT: return "Sampler"; case VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_POOL_EXT: return "Descriptor Pool"; case VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT: return "Descriptor Set"; case VK_DEBUG_REPORT_OBJECT_TYPE_FRAMEBUFFER_EXT: return "Framebuffer"; case VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_POOL_EXT: return "Command Pool"; case VK_DEBUG_REPORT_OBJECT_TYPE_SURFACE_KHR_EXT: return "Surface"; case VK_DEBUG_REPORT_OBJECT_TYPE_SWAPCHAIN_KHR_EXT: return "Swapchain"; case VK_DEBUG_REPORT_OBJECT_TYPE_DEBUG_REPORT_EXT: return "Debug"; default: break; } return "Unknown"; } static VKAPI_ATTR VkBool32 #ifdef WIN32 __stdcall #endif OnVulkanDebugReportCallback(VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT object_type, uint64_t object, size_t location, int32_t message_code, const char* layer_prefix, const char* message, void* user_data) { std::vector<std::pair<std::string, std::string>> items; items.emplace_back("Severity", VkDebugReportFlagsEXTToString(flags)); items.emplace_back("Object Type", VkDebugReportObjectTypeEXTToString(object_type)); items.emplace_back("Object Handle", std::to_string(object)); if (location != 0) { items.emplace_back("Location", std::to_string(location)); } if (message_code != 0) { items.emplace_back("Message Code", std::to_string(message_code)); } if (layer_prefix != nullptr) { items.emplace_back("Layer", layer_prefix); } if (message != nullptr) { items.emplace_back("Message", message); } size_t padding = 0; for (const auto& item : items) { padding = std::max(padding, item.first.size()); } padding += 1; std::stringstream stream; stream << std::endl; stream << "--- Vulkan Debug Report ----------------------------------------"; stream << std::endl; for (const auto& item : items) { stream << "| " << std::setw(static_cast<int>(padding)) << item.first << std::setw(0) << ": " << item.second << std::endl; } stream << "-----------------------------------------------------------------"; if (flags & kVulkanErrorFlags) { if (ValidationErrorsFatal()) { FML_DCHECK(false) << stream.str(); } else { FML_LOG(ERROR) << stream.str(); } } else { FML_LOG(INFO) << stream.str(); } // Returning false tells the layer not to stop when the event occurs, so // they see the same behavior with and without validation layers enabled. return VK_FALSE; } VulkanDebugReport::VulkanDebugReport( const VulkanProcTable& p_vk, const VulkanHandle<VkInstance>& application) : vk_(p_vk), application_(application), valid_(false) { if (!vk_.CreateDebugReportCallbackEXT || !vk_.DestroyDebugReportCallbackEXT) { return; } if (!application_) { return; } VkDebugReportFlagsEXT flags = kVulkanErrorFlags; if (ValidationLayerInfoMessagesEnabled()) { flags |= kVulkanInfoFlags; } const VkDebugReportCallbackCreateInfoEXT create_info = { .sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT, .pNext = nullptr, .flags = flags, .pfnCallback = &vulkan::OnVulkanDebugReportCallback, .pUserData = nullptr, }; VkDebugReportCallbackEXT handle = VK_NULL_HANDLE; if (VK_CALL_LOG_ERROR(vk_.CreateDebugReportCallbackEXT( application_, &create_info, nullptr, &handle)) != VK_SUCCESS) { return; } handle_ = VulkanHandle<VkDebugReportCallbackEXT>{ handle, [this](VkDebugReportCallbackEXT handle) { vk_.DestroyDebugReportCallbackEXT(application_, handle, nullptr); }}; valid_ = true; } VulkanDebugReport::~VulkanDebugReport() = default; bool VulkanDebugReport::IsValid() const { return valid_; } } // namespace vulkan
engine/vulkan/vulkan_debug_report.cc/0
{ "file_path": "engine/vulkan/vulkan_debug_report.cc", "repo_id": "engine", "token_count": 2917 }
498
// 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 "vulkan_swapchain.h" #include "flutter/vulkan/procs/vulkan_proc_table.h" #include "third_party/skia/include/core/SkColorSpace.h" #include "third_party/skia/include/core/SkSurface.h" #include "third_party/skia/include/gpu/GrBackendSurface.h" #include "third_party/skia/include/gpu/GrDirectContext.h" #include "third_party/skia/include/gpu/ganesh/SkSurfaceGanesh.h" #include "third_party/skia/include/gpu/ganesh/vk/GrVkBackendSurface.h" #include "third_party/skia/include/gpu/vk/GrVkTypes.h" #include "vulkan_backbuffer.h" #include "vulkan_device.h" #include "vulkan_image.h" #include "vulkan_surface.h" namespace vulkan { namespace { struct FormatInfo { VkFormat format_; SkColorType color_type_; sk_sp<SkColorSpace> color_space_; }; } // namespace static std::vector<FormatInfo> DesiredFormatInfos() { return {{VK_FORMAT_R8G8B8A8_SRGB, kRGBA_8888_SkColorType, SkColorSpace::MakeSRGB()}, {VK_FORMAT_B8G8R8A8_SRGB, kRGBA_8888_SkColorType, SkColorSpace::MakeSRGB()}, {VK_FORMAT_R16G16B16A16_SFLOAT, kRGBA_F16_SkColorType, SkColorSpace::MakeSRGBLinear()}, {VK_FORMAT_R8G8B8A8_UNORM, kRGBA_8888_SkColorType, SkColorSpace::MakeSRGB()}, {VK_FORMAT_B8G8R8A8_UNORM, kRGBA_8888_SkColorType, SkColorSpace::MakeSRGB()}}; } VulkanSwapchain::VulkanSwapchain(const VulkanProcTable& p_vk, const VulkanDevice& device, const VulkanSurface& surface, GrDirectContext* skia_context, std::unique_ptr<VulkanSwapchain> old_swapchain, uint32_t queue_family_index) : vk(p_vk), device_(device), capabilities_(), surface_format_(), current_pipeline_stage_(VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT), current_backbuffer_index_(0), current_image_index_(0), valid_(false) { if (!device_.IsValid() || !surface.IsValid() || skia_context == nullptr) { FML_DLOG(INFO) << "Device or surface is invalid."; return; } if (!device_.GetSurfaceCapabilities(surface, &capabilities_)) { FML_DLOG(INFO) << "Could not find surface capabilities."; return; } const auto format_infos = DesiredFormatInfos(); std::vector<VkFormat> desired_formats(format_infos.size()); for (size_t i = 0; i < format_infos.size(); ++i) { if (skia_context->colorTypeSupportedAsSurface( format_infos[i].color_type_)) { desired_formats[i] = format_infos[i].format_; } else { desired_formats[i] = VK_FORMAT_UNDEFINED; } } int format_index = device_.ChooseSurfaceFormat(surface, desired_formats, &surface_format_); if (format_index < 0) { FML_DLOG(INFO) << "Could not choose surface format."; return; } VkPresentModeKHR present_mode = VK_PRESENT_MODE_FIFO_KHR; if (!device_.ChoosePresentMode(surface, &present_mode)) { FML_DLOG(INFO) << "Could not choose present mode."; return; } // Check if the surface can present. VkBool32 supported = VK_FALSE; if (VK_CALL_LOG_ERROR(vk.GetPhysicalDeviceSurfaceSupportKHR( device_.GetPhysicalDeviceHandle(), // physical device queue_family_index, // queue family surface.Handle(), // surface to test &supported)) != VK_SUCCESS) { FML_DLOG(INFO) << "Could not get physical device surface support."; return; } if (supported != VK_TRUE) { FML_DLOG(INFO) << "Surface was not supported by the physical device."; return; } // Construct the Swapchain VkSwapchainKHR old_swapchain_handle = VK_NULL_HANDLE; if (old_swapchain != nullptr && old_swapchain->IsValid()) { old_swapchain_handle = old_swapchain->swapchain_; // The unique pointer to the swapchain will go out of scope here // and its handle collected after the appropriate device wait. } VkSurfaceKHR surface_handle = surface.Handle(); VkImageUsageFlags usage_flags = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; const VkSwapchainCreateInfoKHR create_info = { .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR, .pNext = nullptr, .flags = 0, .surface = surface_handle, .minImageCount = capabilities_.minImageCount, .imageFormat = surface_format_.format, .imageColorSpace = surface_format_.colorSpace, .imageExtent = capabilities_.currentExtent, .imageArrayLayers = 1, .imageUsage = usage_flags, .imageSharingMode = VK_SHARING_MODE_EXCLUSIVE, .queueFamilyIndexCount = 0, // Because of the exclusive sharing mode. .pQueueFamilyIndices = nullptr, .preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR, .compositeAlpha = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR, .presentMode = present_mode, .clipped = VK_FALSE, .oldSwapchain = old_swapchain_handle, }; VkSwapchainKHR swapchain = VK_NULL_HANDLE; if (VK_CALL_LOG_ERROR(vk.CreateSwapchainKHR(device_.GetHandle(), &create_info, nullptr, &swapchain)) != VK_SUCCESS) { FML_DLOG(INFO) << "Could not create the swapchain."; return; } swapchain_ = VulkanHandle<VkSwapchainKHR>{ swapchain, [this](VkSwapchainKHR swapchain) { FML_ALLOW_UNUSED_LOCAL(device_.WaitIdle()); vk.DestroySwapchainKHR(device_.GetHandle(), swapchain, nullptr); }}; if (!CreateSwapchainImages( skia_context, format_infos[format_index].color_type_, format_infos[format_index].color_space_, usage_flags)) { FML_DLOG(INFO) << "Could not create swapchain images."; return; } valid_ = true; } VulkanSwapchain::~VulkanSwapchain() = default; bool VulkanSwapchain::IsValid() const { return valid_; } std::vector<VkImage> VulkanSwapchain::GetImages() const { uint32_t count = 0; if (VK_CALL_LOG_ERROR(vk.GetSwapchainImagesKHR( device_.GetHandle(), swapchain_, &count, nullptr)) != VK_SUCCESS) { return {}; } if (count == 0) { return {}; } std::vector<VkImage> images; images.resize(count); if (VK_CALL_LOG_ERROR(vk.GetSwapchainImagesKHR( device_.GetHandle(), swapchain_, &count, images.data())) != VK_SUCCESS) { return {}; } return images; } SkISize VulkanSwapchain::GetSize() const { VkExtent2D extents = capabilities_.currentExtent; if (extents.width < capabilities_.minImageExtent.width) { extents.width = capabilities_.minImageExtent.width; } else if (extents.width > capabilities_.maxImageExtent.width) { extents.width = capabilities_.maxImageExtent.width; } if (extents.height < capabilities_.minImageExtent.height) { extents.height = capabilities_.minImageExtent.height; } else if (extents.height > capabilities_.maxImageExtent.height) { extents.height = capabilities_.maxImageExtent.height; } return SkISize::Make(extents.width, extents.height); } sk_sp<SkSurface> VulkanSwapchain::CreateSkiaSurface( GrDirectContext* gr_context, VkImage image, VkImageUsageFlags usage_flags, const SkISize& size, SkColorType color_type, sk_sp<SkColorSpace> color_space) const { if (gr_context == nullptr) { return nullptr; } if (color_type == kUnknown_SkColorType) { // Unexpected Vulkan format. return nullptr; } GrVkImageInfo image_info; image_info.fImage = image; image_info.fImageTiling = VK_IMAGE_TILING_OPTIMAL; image_info.fImageLayout = VK_IMAGE_LAYOUT_UNDEFINED; image_info.fFormat = surface_format_.format; image_info.fImageUsageFlags = usage_flags; image_info.fSampleCount = 1; image_info.fLevelCount = 1; // TODO(chinmaygarde): Setup the stencil buffer and the sampleCnt. auto backend_render_target = GrBackendRenderTargets::MakeVk(size.fWidth, size.fHeight, image_info); SkSurfaceProps props(0, kUnknown_SkPixelGeometry); return SkSurfaces::WrapBackendRenderTarget( gr_context, // context backend_render_target, // backend render target kTopLeft_GrSurfaceOrigin, // origin color_type, // color type std::move(color_space), // color space &props // surface properties ); } bool VulkanSwapchain::CreateSwapchainImages( GrDirectContext* skia_context, SkColorType color_type, const sk_sp<SkColorSpace>& color_space, VkImageUsageFlags usage_flags) { std::vector<VkImage> images = GetImages(); if (images.empty()) { return false; } const SkISize surface_size = GetSize(); for (const VkImage& image : images) { // Populate the backbuffer. auto backbuffer = std::make_unique<VulkanBackbuffer>( vk, device_.GetHandle(), device_.GetCommandPool()); if (!backbuffer->IsValid()) { return false; } backbuffers_.emplace_back(std::move(backbuffer)); // Populate the image. VulkanHandle<VkImage> image_handle = VulkanHandle<VkImage>{ image, [this](VkImage image) { vk.DestroyImage(device_.GetHandle(), image, nullptr); }}; auto vulkan_image = std::make_unique<VulkanImage>(std::move(image_handle)); if (!vulkan_image->IsValid()) { return false; } images_.emplace_back(std::move(vulkan_image)); // Populate the surface. auto surface = CreateSkiaSurface(skia_context, image, usage_flags, surface_size, color_type, color_space); if (surface == nullptr) { return false; } surfaces_.emplace_back(std::move(surface)); } FML_DCHECK(backbuffers_.size() == images_.size()); FML_DCHECK(images_.size() == surfaces_.size()); return true; } VulkanBackbuffer* VulkanSwapchain::GetNextBackbuffer() { auto available_backbuffers = backbuffers_.size(); if (available_backbuffers == 0) { return nullptr; } auto next_backbuffer_index = (current_backbuffer_index_ + 1) % backbuffers_.size(); auto& backbuffer = backbuffers_[next_backbuffer_index]; if (!backbuffer->IsValid()) { return nullptr; } current_backbuffer_index_ = next_backbuffer_index; return backbuffer.get(); } VulkanSwapchain::AcquireResult VulkanSwapchain::AcquireSurface() { AcquireResult error = {AcquireStatus::ErrorSurfaceLost, nullptr}; if (!IsValid()) { FML_DLOG(INFO) << "Swapchain was invalid."; return error; } // --------------------------------------------------------------------------- // Step 0: // Acquire the next available backbuffer. // --------------------------------------------------------------------------- auto backbuffer = GetNextBackbuffer(); if (backbuffer == nullptr) { FML_DLOG(INFO) << "Could not get the next backbuffer."; return error; } // --------------------------------------------------------------------------- // Step 1: // Wait for use readiness. // --------------------------------------------------------------------------- if (!backbuffer->WaitFences()) { FML_DLOG(INFO) << "Failed waiting on fences."; return error; } // --------------------------------------------------------------------------- // Step 2: // Put fences in an unsignaled state. // --------------------------------------------------------------------------- if (!backbuffer->ResetFences()) { FML_DLOG(INFO) << "Could not reset fences."; return error; } // --------------------------------------------------------------------------- // Step 3: // Acquire the next image index. // --------------------------------------------------------------------------- uint32_t next_image_index = 0; VkResult acquire_result = VK_CALL_LOG_ERROR( vk.AcquireNextImageKHR(device_.GetHandle(), // swapchain_, // std::numeric_limits<uint64_t>::max(), // backbuffer->GetUsageSemaphore(), // VK_NULL_HANDLE, // &next_image_index)); switch (acquire_result) { case VK_SUCCESS: break; case VK_ERROR_OUT_OF_DATE_KHR: return {AcquireStatus::ErrorSurfaceOutOfDate, nullptr}; case VK_ERROR_SURFACE_LOST_KHR: return {AcquireStatus::ErrorSurfaceLost, nullptr}; default: FML_LOG(INFO) << "Unexpected result from AcquireNextImageKHR: " << acquire_result; return {AcquireStatus::ErrorSurfaceLost, nullptr}; } // Simple sanity checking of image index. if (next_image_index >= images_.size()) { FML_DLOG(INFO) << "Image index returned was out-of-bounds."; return error; } auto& image = images_[next_image_index]; if (!image->IsValid()) { FML_DLOG(INFO) << "Image at index was invalid."; return error; } // --------------------------------------------------------------------------- // Step 4: // Start recording to the command buffer. // --------------------------------------------------------------------------- if (!backbuffer->GetUsageCommandBuffer().Begin()) { FML_DLOG(INFO) << "Could not begin recording to the command buffer."; return error; } // --------------------------------------------------------------------------- // Step 5: // Set image layout to color attachment mode. // --------------------------------------------------------------------------- VkPipelineStageFlagBits destination_pipeline_stage = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; VkImageLayout destination_image_layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; if (!image->InsertImageMemoryBarrier( backbuffer->GetUsageCommandBuffer(), // command buffer current_pipeline_stage_, // src_pipeline_bits destination_pipeline_stage, // dest_pipeline_bits VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, // dest_access_flags destination_image_layout // dest_layout )) { FML_DLOG(INFO) << "Could not insert image memory barrier."; return error; } else { current_pipeline_stage_ = destination_pipeline_stage; } // --------------------------------------------------------------------------- // Step 6: // End recording to the command buffer. // --------------------------------------------------------------------------- if (!backbuffer->GetUsageCommandBuffer().End()) { FML_DLOG(INFO) << "Could not end recording to the command buffer."; return error; } // --------------------------------------------------------------------------- // Step 7: // Submit the command buffer to the device queue. // --------------------------------------------------------------------------- std::vector<VkSemaphore> wait_semaphores = {backbuffer->GetUsageSemaphore()}; std::vector<VkSemaphore> signal_semaphores = {}; std::vector<VkCommandBuffer> command_buffers = { backbuffer->GetUsageCommandBuffer().Handle()}; if (!device_.QueueSubmit( {destination_pipeline_stage}, // wait_dest_pipeline_stages wait_semaphores, // wait_semaphores signal_semaphores, // signal_semaphores command_buffers, // command_buffers backbuffer->GetUsageFence() // fence )) { FML_DLOG(INFO) << "Could not submit to the device queue."; return error; } // --------------------------------------------------------------------------- // Step 8: // Tell Skia about the updated image layout. // --------------------------------------------------------------------------- sk_sp<SkSurface> surface = surfaces_[next_image_index]; if (surface == nullptr) { FML_DLOG(INFO) << "Could not access surface at the image index."; return error; } GrBackendRenderTarget backendRT = SkSurfaces::GetBackendRenderTarget( surface.get(), SkSurfaces::BackendHandleAccess::kFlushRead); if (!backendRT.isValid()) { FML_DLOG(INFO) << "Could not get backend render target."; return error; } GrBackendRenderTargets::SetVkImageLayout(&backendRT, destination_image_layout); current_image_index_ = next_image_index; return {AcquireStatus::Success, surface}; } bool VulkanSwapchain::Submit() { if (!IsValid()) { FML_DLOG(INFO) << "Swapchain was invalid."; return false; } sk_sp<SkSurface> surface = surfaces_[current_image_index_]; const std::unique_ptr<VulkanImage>& image = images_[current_image_index_]; auto backbuffer = backbuffers_[current_backbuffer_index_].get(); // --------------------------------------------------------------------------- // Step 0: // Make sure Skia has flushed all work for the surface to the gpu. // --------------------------------------------------------------------------- skgpu::ganesh::FlushAndSubmit(surface); // --------------------------------------------------------------------------- // Step 1: // Start recording to the command buffer. // --------------------------------------------------------------------------- if (!backbuffer->GetRenderCommandBuffer().Begin()) { FML_DLOG(INFO) << "Could not start recording to the command buffer."; return false; } // --------------------------------------------------------------------------- // Step 2: // Set image layout to present mode. // --------------------------------------------------------------------------- VkPipelineStageFlagBits destination_pipeline_stage = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; VkImageLayout destination_image_layout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; if (!image->InsertImageMemoryBarrier( backbuffer->GetRenderCommandBuffer(), // command buffer current_pipeline_stage_, // src_pipeline_bits destination_pipeline_stage, // dest_pipeline_bits VK_ACCESS_MEMORY_READ_BIT, // dest_access_flags destination_image_layout // dest_layout )) { FML_DLOG(INFO) << "Could not insert memory barrier."; return false; } else { current_pipeline_stage_ = destination_pipeline_stage; } // --------------------------------------------------------------------------- // Step 3: // End recording to the command buffer. // --------------------------------------------------------------------------- if (!backbuffer->GetRenderCommandBuffer().End()) { FML_DLOG(INFO) << "Could not end recording to the command buffer."; return false; } // --------------------------------------------------------------------------- // Step 4: // Submit the command buffer to the device queue. Tell it to signal the render // semaphore. // --------------------------------------------------------------------------- std::vector<VkSemaphore> wait_semaphores = {}; std::vector<VkSemaphore> queue_signal_semaphores = { backbuffer->GetRenderSemaphore()}; std::vector<VkCommandBuffer> command_buffers = { backbuffer->GetRenderCommandBuffer().Handle()}; if (!device_.QueueSubmit( {/* Empty. No wait semaphores. */}, // wait_dest_pipeline_stages wait_semaphores, // wait_semaphores queue_signal_semaphores, // signal_semaphores command_buffers, // command_buffers backbuffer->GetRenderFence() // fence )) { FML_DLOG(INFO) << "Could not submit to the device queue."; return false; } // --------------------------------------------------------------------------- // Step 5: // Submit the present operation and wait on the render semaphore. // --------------------------------------------------------------------------- VkSwapchainKHR swapchain = swapchain_; uint32_t present_image_index = static_cast<uint32_t>(current_image_index_); const VkPresentInfoKHR present_info = { .sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR, .pNext = nullptr, .waitSemaphoreCount = static_cast<uint32_t>(queue_signal_semaphores.size()), .pWaitSemaphores = queue_signal_semaphores.data(), .swapchainCount = 1, .pSwapchains = &swapchain, .pImageIndices = &present_image_index, .pResults = nullptr, }; if (VK_CALL_LOG_ERROR(vk.QueuePresentKHR(device_.GetQueueHandle(), &present_info)) != VK_SUCCESS) { FML_DLOG(INFO) << "Could not submit the present operation."; return false; } return true; } } // namespace vulkan
engine/vulkan/vulkan_swapchain.cc/0
{ "file_path": "engine/vulkan/vulkan_swapchain.cc", "repo_id": "engine", "token_count": 7857 }
499
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:convert'; import 'dart:js_interop'; import 'package:test/test.dart'; // ignore: implementation_imports import 'package:ui/src/engine.dart' show renderer; // ignore: implementation_imports import 'package:ui/src/engine/dom.dart'; import 'package:ui/ui.dart'; Future<dynamic> _callScreenshotServer(dynamic requestData) async { // This is test code, but because the file name doesn't end with "_test.dart" // the analyzer doesn't know it, so have to ignore the lint explicitly. // ignore: invalid_use_of_visible_for_testing_member final HttpFetchResponse response = await testOnlyHttpPost( 'screenshot', json.encode(requestData), ); return json.decode(await response.text()); } /// How to compare pixels within the image. /// /// Keep this enum in sync with the one defined in `goldens.dart`. enum PixelComparison { /// Allows minor blur and anti-aliasing differences by comparing a 3x3 grid /// surrounding the pixel rather than direct 1:1 comparison. fuzzy, /// Compares one pixel at a time. /// /// Anti-aliasing or blur will result in higher diff rate. precise, } /// Attempts to match the current browser state with the screenshot [filename]. /// /// If [region] is not null, the golden will only include the part contained by /// the rectangle. /// /// [maxDiffRate] specifies the tolerance to the number of non-matching pixels /// before the test is considered as failing. If [maxDiffRate] is null, applies /// a default value defined in `test_platform.dart`. /// /// [pixelComparison] determines the algorithm used to compare pixels. Uses /// fuzzy comparison by default. Future<void> matchGoldenFile(String filename, {Rect? region}) async { // It is difficult to deterministically tell when rendered content is actually // visible to the user, so we pump 15 frames to make sure that the content is // has reached the screen. This is at the recommendation of the Chrome team, // and they use this same thing in their screenshot unit tests. for (int i = 0; i < 15; i++) { await awaitNextFrame(); } if (!filename.endsWith('.png')) { throw ArgumentError('Filename must end in .png or SkiaGold will ignore it.'); } final Map<String, dynamic> serverParams = <String, dynamic>{ 'filename': filename, 'region': region == null ? null : <String, dynamic>{ 'x': region.left, 'y': region.top, 'width': region.width, 'height': region.height }, // We use the renderer tag here rather than `renderer is CanvasKitRenderer` // because these unit tests operate on the post-transformed (sdk_rewriter) // sdk where the internal classes like `CanvasKitRenderer` are no longer // visible. 'isCanvaskitTest': renderer.rendererTag == 'canvaskit', }; final String response = await _callScreenshotServer(serverParams) as String; if (response == 'OK') { // Pass return; } fail(response); } /// Waits for one frame to complete rendering Future<void> awaitNextFrame() { final Completer<void> completer = Completer<void>(); domWindow.requestAnimationFrame((JSNumber time) => completer.complete()); return completer.future; }
engine/web_sdk/web_engine_tester/lib/golden_tester.dart/0
{ "file_path": "engine/web_sdk/web_engine_tester/lib/golden_tester.dart", "repo_id": "engine", "token_count": 1048 }
500
<component name="CopyrightManager"> <copyright> <option name="myName" value="chromium" /> <option name="notice" value="Copyright &amp;#36;today.year The Chromium Authors. All rights reserved.&#10;Use of this source code is governed by a BSD-style license that can be&#10;found in the LICENSE file." /> </copyright> </component>
flutter-intellij/.idea/copyright/chromium.xml/0
{ "file_path": "flutter-intellij/.idea/copyright/chromium.xml", "repo_id": "flutter-intellij", "token_count": 104 }
501
<?xml version="1.0" encoding="UTF-8"?> <project version="4"> <component name="VcsDirectoryMappings"> <mapping directory="" vcs="Git" /> <mapping directory="$PROJECT_DIR$" vcs="Git" /> </component> </project>
flutter-intellij/.idea/vcs.xml/0
{ "file_path": "flutter-intellij/.idea/vcs.xml", "repo_id": "flutter-intellij", "token_count": 82 }
502
plugins { id "org.jetbrains.intellij" version "0.4.9" id 'org.jetbrains.kotlin.jvm' version '1.3.21' } group 'io.flutter.tests.gui' version '1.0-SNAPSHOT' repositories { mavenLocal() mavenCentral() jcenter() // this repo contains the test target plugin produced by the plugin tool, io.flutter:SNAPSHOT flatDir dirs: ['../releases/release_master/test_target'] } dependencies { compile "org.jetbrains.kotlin:kotlin-reflect" testCompile group: 'junit', name: 'junit', version: '4.12' } sourceSets { main { java.srcDir 'src' kotlin.srcDir 'src' resources.srcDir 'res' } test { java.srcDir 'testSrc' kotlin.srcDir 'testSrc' resources.srcDir 'testData' } } intellij { // Check versions at https://plugins.jetbrains.com/plugin/11114-test-gui-framework/ plugins 'com.intellij.testGuiFramework:0.10.1@nightly', 'Dart:192.5728.12', 'io.flutter:SNAPSHOT' if (System.getProperty("idea.gui.test.alternativeIdePath") != null) { alternativeIdePath System.getProperty("idea.gui.test.alternativeIdePath") } updateSinceUntilBuild false // version 'LATEST-TRUNK-SNAPSHOT' } kotlin { experimental { coroutines "enable" } } compileKotlin { kotlinOptions.jvmTarget = "1.8" } compileTestKotlin { kotlinOptions.jvmTarget = "1.8" } task testsJar(type: Jar, dependsOn: classes) { classifier = 'tests' from sourceSets.test.output exclude 'testData/*' } prepareSandbox { from(testsJar) { into "$pluginName/lib" } } prepareTestingSandbox { from(testsJar) { into "$pluginName/lib" } } runIde { if (System.getProperty("idea.gui.tests.gradle.runner").equals("true")) { systemProperties System.properties.findAll { (it.key as String).startsWith("idea") || (it.key as String).startsWith("jb") }.findAll { (it.key as String) != "idea.home.path" && (it.key as String) != "jb.vmOptionsFile" } /* Need to split the space-delimited value in the exec.args */ print systemProperties args System.getProperty("exec.args", "").split(",") print args } } test { def sysProps = System.properties.findAll { (it.key as String).startsWith("idea") || (it.key as String).startsWith("jb") && (it.key as String) != "idea.home.path" && (it.key as String) != "jb.vmOptionsFile" } sysProps.put("idea.gui.tests.gradle.runner", true) //Use Gradle Launcher to run GUI tests //sysProps.put("idea.debug.mode", true) // Add to enable debugging with breakpoints systemProperties sysProps }
flutter-intellij/flutter-gui-tests/build.gradle/0
{ "file_path": "flutter-intellij/flutter-gui-tests/build.gradle", "repo_id": "flutter-intellij", "token_count": 1248 }
503
NEEDS TO BE UPDATED a/o 9 NOV 21 # Gradle Module Structure This module is a mirror of flutter-intellij (the non-Gradle version) that has sources structured in a way that the IntelliJ plugin for Gradle expects. A new module was required because the flutter-studio module has dependencies on a number of classes defined in this module and there was a circular dependency when those definitions were rooted in flutter-intellij. The original flutter-intellij structure has been preserved as a courtesy to the engineers that already have it checked out. The original metadata files are checked in to the repository and will be used when the project is opened. To use the Gradle structure, import flutter-intellij/build.gradle instead of opening the project. That will rebuild the metadata files according to the Gradle structure. ## Building the plugin Make sure the proper IDE is unpacked in the artifacts directory. Open a terminal and do `./gradlew clean buildPlugin` The plugin will be found in build/distributions/flutter-intellij-NN.zip. ## Working with Android Studio sources If this project is to be used in a full-source configuration with Android Studio (as described in the flutter-studio module), then some adjustments need to be made after importing the Gradle modules. Select the flutter-intellij module and select the Paths tab. For each of these projects change `Compiler output` to `Inherit project compile output path`: - `flutter-intellij.main` - `flutter-intellij.test` - `flutter-intellij.flutter-idea.main` - `flutter-intellij.flutter-idea.test` - `flutter-intellij.flutter-studio.main` - `flutter-intellij.flutter-studio.test` This needs to be done every time the Gradle module is imported or re-imported. There doesn't seem to be any config setting in the IntelliJ plugin for Gradle to configure this.
flutter-intellij/flutter-idea/README.md/0
{ "file_path": "flutter-intellij/flutter-idea/README.md", "repo_id": "flutter-intellij", "token_count": 493 }
504
/* * Copyright 2016 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. */ package io.flutter.actions; import com.intellij.ide.ActivityTracker; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.actionSystem.ex.ComboBoxAction; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.project.ProjectManagerListener; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.SystemInfo; import com.intellij.util.ModalityUiUtil; import icons.FlutterIcons; import io.flutter.FlutterBundle; import io.flutter.run.FlutterDevice; import io.flutter.run.daemon.DeviceService; import io.flutter.sdk.AndroidEmulatorManager; import io.flutter.utils.FlutterModuleUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.*; public class DeviceSelectorAction extends ComboBoxAction implements DumbAware { private final List<AnAction> actions = new ArrayList<>(); private final List<Project> knownProjects = Collections.synchronizedList(new ArrayList<>()); private SelectDeviceAction selectedDeviceAction; DeviceSelectorAction() { setSmallVariant(true); } public @NotNull ActionUpdateThread getActionUpdateThread() { return ActionUpdateThread.BGT; } @NotNull @Override protected DefaultActionGroup createPopupActionGroup(JComponent button) { final DefaultActionGroup group = new DefaultActionGroup(); group.addAll(actions); return group; } @Override protected boolean shouldShowDisabledActions() { return true; } @Override public void update(@NotNull AnActionEvent e) { // Only show device menu when the device daemon process is running. final Project project = e.getProject(); if (!isSelectorVisible(project)) { e.getPresentation().setVisible(false); return; } super.update(e); final Presentation presentation = e.getPresentation(); if (!knownProjects.contains(project)) { knownProjects.add(project); final Application application = ApplicationManager.getApplication(); application.getMessageBus().connect().subscribe(ProjectManager.TOPIC, new ProjectManagerListener() { @Override public void projectClosed(@NotNull Project closedProject) { knownProjects.remove(closedProject); } }); Runnable deviceListener = () -> queueUpdate(project, e.getPresentation()); DeviceService.getInstance(project).addListener(deviceListener); // Listen for android device changes, and rebuild the menu if necessary. Runnable emulatorListener = () -> queueUpdate(project, e.getPresentation()); AndroidEmulatorManager.getInstance(project).addListener(emulatorListener); ProjectManager.getInstance().addProjectManagerListener(project, new ProjectManagerListener() { public void projectClosing(@NotNull Project project) { DeviceService.getInstance(project).removeListener(deviceListener); AndroidEmulatorManager.getInstance(project).removeListener(emulatorListener); } }); update(project, presentation); } final DeviceService deviceService = DeviceService.getInstance(project); final FlutterDevice selectedDevice = deviceService.getSelectedDevice(); final Collection<FlutterDevice> devices = deviceService.getConnectedDevices(); if (devices.isEmpty()) { final boolean isLoading = deviceService.getStatus() == DeviceService.State.LOADING; if (isLoading) { presentation.setText(FlutterBundle.message("devicelist.loading")); } else { presentation.setText("<no devices>"); } } else if (selectedDevice == null) { presentation.setText("<no device selected>"); } else if (selectedDeviceAction != null) { final Presentation template = selectedDeviceAction.getTemplatePresentation(); presentation.setIcon(template.getIcon()); presentation.setText(selectedDevice.presentationName()); presentation.setEnabled(true); } } private void queueUpdate(@NotNull Project project, @NotNull Presentation presentation) { ModalityUiUtil.invokeLaterIfNeeded( ModalityState.defaultModalityState(), () -> update(project, presentation)); } private void update(@NotNull Project project, @NotNull Presentation presentation) { if (project.isDisposed()) { return; // This check is probably unnecessary, but safe. } updateActions(project, presentation); updateVisibility(project, presentation); } private static void updateVisibility(final Project project, final Presentation presentation) { final boolean visible = isSelectorVisible(project); final JComponent component = (JComponent)presentation.getClientProperty("customComponent"); if (component != null) { component.setVisible(visible); if (component.getParent() != null) { component.getParent().doLayout(); component.getParent().repaint(); } } } private static boolean isSelectorVisible(@Nullable Project project) { if (project == null || !FlutterModuleUtils.hasFlutterModule(project)) { return false; } final DeviceService deviceService = DeviceService.getInstance(project); return deviceService.isRefreshInProgress() || deviceService.getStatus() != DeviceService.State.INACTIVE; } private void updateActions(@NotNull Project project, Presentation presentation) { actions.clear(); final DeviceService deviceService = DeviceService.getInstance(project); final FlutterDevice selectedDevice = deviceService.getSelectedDevice(); final Collection<FlutterDevice> devices = deviceService.getConnectedDevices(); selectedDeviceAction = null; for (FlutterDevice device : devices) { final SelectDeviceAction deviceAction = new SelectDeviceAction(device, devices); actions.add(deviceAction); if (Objects.equals(device, selectedDevice)) { selectedDeviceAction = deviceAction; final Presentation template = deviceAction.getTemplatePresentation(); presentation.setIcon(template.getIcon()); //presentation.setText(deviceAction.presentationName()); presentation.setEnabled(true); } } // Show the 'Open iOS Simulator' action. if (SystemInfo.isMac) { boolean simulatorOpen = false; for (AnAction action : actions) { if (action instanceof SelectDeviceAction) { final SelectDeviceAction deviceAction = (SelectDeviceAction)action; final FlutterDevice device = deviceAction.device; if (device.isIOS() && device.emulator()) { simulatorOpen = true; } } } actions.add(new Separator()); actions.add(new OpenSimulatorAction(!simulatorOpen)); } // Add Open Android emulators actions. final List<OpenEmulatorAction> emulatorActions = OpenEmulatorAction.getEmulatorActions(project); if (!emulatorActions.isEmpty()) { actions.add(new Separator()); actions.addAll(emulatorActions); } if (!FlutterModuleUtils.hasInternalDartSdkPath(project)) { actions.add(new Separator()); actions.add(new RestartFlutterDaemonAction()); } ActivityTracker.getInstance().inc(); } // Show the current device as selected when the combo box menu opens. @Override protected Condition<AnAction> getPreselectCondition() { return action -> action == selectedDeviceAction; } private static class SelectDeviceAction extends AnAction { @NotNull private final FlutterDevice device; SelectDeviceAction(@NotNull FlutterDevice device, @NotNull Collection<FlutterDevice> devices) { super(device.getUniqueName(devices), null, FlutterIcons.Phone); this.device = device; } public String presentationName() { return device.presentationName(); } @Override public void actionPerformed(AnActionEvent e) { final Project project = e.getProject(); final DeviceService service = project == null ? null : DeviceService.getInstance(project); if (service != null) { service.setSelectedDevice(device); } } } }
flutter-intellij/flutter-idea/src/io/flutter/actions/DeviceSelectorAction.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/actions/DeviceSelectorAction.java", "repo_id": "flutter-intellij", "token_count": 2769 }
505
/* * Copyright 2016 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. */ package io.flutter.actions; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.DefaultActionGroup; import com.intellij.openapi.actionSystem.Presentation; import com.intellij.openapi.project.Project; import io.flutter.utils.FlutterModuleUtils; import org.jetbrains.annotations.Nullable; public class FlutterToolsActionGroup extends DefaultActionGroup { @Override public void update(@Nullable AnActionEvent e) { final Project project = e == null ? null : e.getProject(); final Presentation presentation = e == null ? null : e.getPresentation(); if (presentation != null) { final boolean visible = project != null && FlutterModuleUtils.declaresFlutter(project); presentation.setEnabled(visible); presentation.setVisible(visible); } } }
flutter-intellij/flutter-idea/src/io/flutter/actions/FlutterToolsActionGroup.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/actions/FlutterToolsActionGroup.java", "repo_id": "flutter-intellij", "token_count": 301 }
506
/* * Copyright 2017 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. */ package io.flutter.actions; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.project.Project; import io.flutter.FlutterInitializer; import io.flutter.run.daemon.DeviceService; public class RestartFlutterDaemonAction extends AnAction { public RestartFlutterDaemonAction() { super("Refresh"); } @Override public void actionPerformed(AnActionEvent event) { FlutterInitializer.sendAnalyticsAction(this); final Project project = event.getProject(); if (project == null) { return; } DeviceService.getInstance(project).restart(); } }
flutter-intellij/flutter-idea/src/io/flutter/actions/RestartFlutterDaemonAction.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/actions/RestartFlutterDaemonAction.java", "repo_id": "flutter-intellij", "token_count": 262 }
507
/* * Copyright 2017 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. */ package io.flutter.bazel; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Objects; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import com.google.gson.annotations.SerializedName; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Computable; import com.intellij.openapi.vfs.VirtualFile; import io.flutter.FlutterUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.regex.PatternSyntaxException; /** * An in-memory snapshot of the flutter.json file from a Bazel workspace. */ public class PluginConfig { private final @NotNull Fields fields; private PluginConfig(@NotNull Fields fields) { this.fields = fields; } @Nullable String getDaemonScript() { return fields.daemonScript; } @Nullable String getDevToolsScript() { return fields.devToolsScript; } @Nullable String getDoctorScript() { return fields.doctorScript; } @Nullable String getTestScript() { return fields.testScript; } @Nullable String getRunScript() { return fields.runScript; } @Nullable String getSyncScript() { return fields.syncScript; } @Nullable String getToolsScript() { return fields.toolsScript; } @Nullable String getSdkHome() { return fields.sdkHome; } @Nullable String getRequiredIJPluginID() { return fields.requiredIJPluginID; } @Nullable String getRequiredIJPluginMessage() { return fields.requiredIJPluginMessage; } @Nullable String getConfigWarningPrefix() { return fields.configWarningPrefix; } @Nullable String getUpdatedIosRunMessage() { return fields.updatedIosRunMessage; } @Override public boolean equals(Object obj) { if (!(obj instanceof PluginConfig)) return false; final PluginConfig other = (PluginConfig)obj; return Objects.equal(fields, other.fields); } @Override public int hashCode() { return Objects.hashCode(fields); } /** * Reads plugin configuration from a file, if possible. */ @Nullable public static PluginConfig load(@NotNull VirtualFile file) { final Computable<PluginConfig> readAction = () -> { try ( // Create the input stream in a try-with-resources statement. This will automatically close the stream // in an implicit finally section; this addresses a file handle leak issue we had on MacOS. final InputStreamReader input = new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8) ) { final Fields fields = GSON.fromJson(input, Fields.class); return new PluginConfig(fields); } catch (FileNotFoundException e) { LOG.info("Flutter plugin didn't find flutter.json at " + file.getPath()); return null; } catch (IOException e) { FlutterUtils.warn(LOG, "Flutter plugin failed to load config file at " + file.getPath(), e); return null; } catch (JsonSyntaxException e) { FlutterUtils.warn(LOG, "Flutter plugin failed to parse JSON in config file at " + file.getPath()); return null; } catch (PatternSyntaxException e) { FlutterUtils .warn(LOG, "Flutter plugin failed to parse directory pattern (" + e.getPattern() + ") in config file at " + file.getPath()); return null; } }; return ApplicationManager.getApplication().runReadAction(readAction); } @VisibleForTesting public static PluginConfig forTest( @Nullable String daemonScript, @Nullable String devToolsScript, @Nullable String doctorScript, @Nullable String testScript, @Nullable String runScript, @Nullable String syncScript, @Nullable String toolsScript, @Nullable String sdkHome, @Nullable String requiredIJPluginID, @Nullable String requiredIJPluginMessage, @Nullable String configWarningPrefix, @Nullable String updatedIosRunMessage ) { final Fields fields = new Fields( daemonScript, devToolsScript, doctorScript, testScript, runScript, syncScript, toolsScript, sdkHome, requiredIJPluginID, requiredIJPluginMessage, configWarningPrefix, updatedIosRunMessage ); return new PluginConfig(fields); } /** * The JSON fields in a PluginConfig, as loaded from disk. */ private static class Fields { /** * The script to run to start 'flutter daemon'. */ @SerializedName("daemonScript") private String daemonScript; @SerializedName("devToolsScript") private String devToolsScript; /** * The script to run to start 'flutter doctor'. */ @SerializedName("doctorScript") private String doctorScript; /** * The script to run to start 'flutter test' */ @SerializedName("testScript") private String testScript; /** * The script to run to start 'flutter run' */ @SerializedName("runScript") private String runScript; /** * The script to run to start 'flutter sync' */ @SerializedName("syncScript") private String syncScript; @SerializedName("toolsScript") private String toolsScript; /** * The directory containing the SDK tools. */ @SerializedName("sdkHome") private String sdkHome; /** * The file containing the Flutter version. */ @SerializedName("requiredIJPluginID") private String requiredIJPluginID; /** * The file containing the message to install the required IJ Plugin. */ @SerializedName("requiredIJPluginMessage") private String requiredIJPluginMessage; /** * The prefix that indicates a configuration warning message. */ @SerializedName("configWarningPrefix") private String configWarningPrefix; /** * The prefix that indicates a message about iOS run being updated. */ @SerializedName("updatedIosRunMessage") private String updatedIosRunMessage; Fields() { } /** * Convenience constructor that takes all parameters. */ Fields(String daemonScript, String devToolsScript, String doctorScript, String testScript, String runScript, String syncScript, String toolsScript, String sdkHome, String requiredIJPluginID, String requiredIJPluginMessage, String configWarningPrefix, String updatedIosRunMessage) { this.daemonScript = daemonScript; this.devToolsScript = devToolsScript; this.doctorScript = doctorScript; this.testScript = testScript; this.runScript = runScript; this.syncScript = syncScript; this.toolsScript = toolsScript; this.sdkHome = sdkHome; this.requiredIJPluginID = requiredIJPluginID; this.requiredIJPluginMessage = requiredIJPluginMessage; this.configWarningPrefix = configWarningPrefix; this.updatedIosRunMessage = updatedIosRunMessage; } @Override public boolean equals(Object obj) { if (!(obj instanceof Fields)) return false; final Fields other = (Fields)obj; return Objects.equal(daemonScript, other.daemonScript) && Objects.equal(devToolsScript, other.devToolsScript) && Objects.equal(doctorScript, other.doctorScript) && Objects.equal(testScript, other.testScript) && Objects.equal(runScript, other.runScript) && Objects.equal(syncScript, other.syncScript) && Objects.equal(sdkHome, other.sdkHome) && Objects.equal(requiredIJPluginID, other.requiredIJPluginID) && Objects.equal(requiredIJPluginMessage, other.requiredIJPluginMessage) && Objects.equal(configWarningPrefix, other.configWarningPrefix) && Objects.equal(updatedIosRunMessage, other.updatedIosRunMessage); } @Override public int hashCode() { return Objects.hashCode(daemonScript, devToolsScript, doctorScript, testScript, runScript, syncScript, sdkHome, requiredIJPluginID, requiredIJPluginMessage, configWarningPrefix, updatedIosRunMessage); } } private static final Gson GSON = new Gson(); private static final Logger LOG = Logger.getInstance(PluginConfig.class); }
flutter-intellij/flutter-idea/src/io/flutter/bazel/PluginConfig.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/bazel/PluginConfig.java", "repo_id": "flutter-intellij", "token_count": 3134 }
508
/* * 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. */ package io.flutter.devtools; public class DevToolsUtils { public static String findWidgetId(String url) { final String searchFor = "inspectorRef="; final String[] split = url.split("&"); for (String part : split) { if (part.startsWith(searchFor)) { return part.substring(searchFor.length()); } } return null; } }
flutter-intellij/flutter-idea/src/io/flutter/devtools/DevToolsUtils.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/devtools/DevToolsUtils.java", "repo_id": "flutter-intellij", "token_count": 181 }
509
/* * Copyright 2016 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. */ package io.flutter.editor; import com.intellij.openapi.editor.markup.GutterIconRenderer; import com.intellij.openapi.project.DumbAware; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.util.Objects; public class FlutterIconRenderer extends GutterIconRenderer implements DumbAware { private final Icon myIcon; private final String myId; public FlutterIconRenderer(Icon icon, PsiElement element) { myIcon = icon; myId = element.getText(); } public String getTooltipText() { return myId; } @NotNull @Override public Icon getIcon() { return myIcon; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final FlutterIconRenderer renderer = (FlutterIconRenderer)o; return Objects.equals(myId, renderer.myId); } @Override public int hashCode() { return myId.hashCode(); } }
flutter-intellij/flutter-idea/src/io/flutter/editor/FlutterIconRenderer.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/editor/FlutterIconRenderer.java", "repo_id": "flutter-intellij", "token_count": 397 }
510
/* * 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. */ package io.flutter.editor; import com.intellij.openapi.project.Project; import io.flutter.dart.FlutterDartAnalysisServer; import io.flutter.inspector.InspectorGroupManagerService; /** * Context with references to data useful for widget editing code. */ public class WidgetEditingContext { public final Project project; public final FlutterDartAnalysisServer flutterDartAnalysisService; public final InspectorGroupManagerService inspectorGroupManagerService; public final EditorPositionService editorPositionService; public WidgetEditingContext( Project project, FlutterDartAnalysisServer flutterDartAnalysisService, InspectorGroupManagerService inspectorGroupManagerService, EditorPositionService editorPositionService ) { this.project = project; this.flutterDartAnalysisService = flutterDartAnalysisService; this.inspectorGroupManagerService = inspectorGroupManagerService; this.editorPositionService = editorPositionService; } }
flutter-intellij/flutter-idea/src/io/flutter/editor/WidgetEditingContext.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/editor/WidgetEditingContext.java", "repo_id": "flutter-intellij", "token_count": 307 }
511
/* * Copyright 2017 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. */ package io.flutter.inspector; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonNull; import com.google.gson.JsonObject; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.xdebugger.XSourcePosition; import com.jetbrains.lang.dart.analyzer.DartAnalysisServerService; import io.flutter.run.daemon.FlutterApp; import io.flutter.utils.CustomIconMaker; import io.flutter.utils.JsonUtils; import io.flutter.vmService.frame.DartVmServiceValue; import org.apache.commons.lang3.StringUtils; import org.dartlang.analysis.server.protocol.HoverInformation; import org.dartlang.vm.service.element.InstanceRef; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.function.BiConsumer; /** * Defines diagnostics data for a [value]. * <p> * [DiagnosticsNode] provides a high quality multi-line string dump via * [toStringDeep]. The core members are the [name], [toDescription], * [getProperties], [value], and [getChildren]. All other members exist * typically to provide hints for how [toStringDeep] and debugging tools should * format output. * <p> * See also: * <p> * * DiagnosticsNode class defined at https://github.com/flutter/flutter/blob/master/packages/flutter/lib/src/foundation/diagnostics.dart * The difference is the class hierarchy is collapsed on the Java side as * the class hierarchy on the Dart side exists more to simplify creation * of Diagnostics than because the class hierarchy of Diagnostics is * important. If you need to determine the exact Diagnostic class on the * Dart side you can use the value of type. The raw Dart object value is * also available via the getValue() method. */ public class DiagnosticsNode { private static final Logger LOG = Logger.getInstance(DiagnosticsNode.class); private static final CustomIconMaker iconMaker = new CustomIconMaker(); private final FlutterApp app; private InspectorSourceLocation location; private DiagnosticsNode parent; private CompletableFuture<String> propertyDocFuture; private ArrayList<DiagnosticsNode> cachedProperties; public DiagnosticsNode(JsonObject json, InspectorService.ObjectGroup inspectorService, boolean isProperty, DiagnosticsNode parent) { this.json = json; this.inspectorService = CompletableFuture.completedFuture(inspectorService); this.isProperty = isProperty; this.app = inspectorService.getApp(); } public DiagnosticsNode(JsonObject json, @NotNull CompletableFuture<InspectorService.ObjectGroup> inspectorService, FlutterApp app, boolean isProperty, DiagnosticsNode parent) { this.json = json; this.inspectorService = inspectorService; this.isProperty = isProperty; this.app = app; } @Override public boolean equals(Object other) { if (other instanceof DiagnosticsNode) { final DiagnosticsNode otherNode = (DiagnosticsNode)other; return getDartDiagnosticRef().equals(otherNode.getDartDiagnosticRef()); } return false; } @Override public String toString() { final String name = getName(); if (StringUtils.isEmpty(name) || !getShowName()) { return getDescription(); } return name + getSeparator() + ' ' + getDescription(); } public boolean isDisposed() { try { final InspectorService.ObjectGroup service = inspectorService.getNow(null); // If the service isn't created yet it can't have been disposed. return service != null && service.isDisposed(); } catch (Exception e) { // If the service can't be acquired then it is disposed. return false; } } /** * Set this node's parent. */ public void setParent(DiagnosticsNode parent) { this.parent = parent; } /** * This node's parent (if it's been set). */ @Nullable public DiagnosticsNode getParent() { return parent; } /** * Separator text to show between property names and values. */ public String getSeparator() { return getShowSeparator() ? ":" : ""; } /** * Label describing the [DiagnosticsNode], typically shown before a separator * (see [showSeparator]). * <p> * The name should be omitted if the [showName] property is false. */ public String getName() { return getStringMember("name"); } /** * Whether to show a separator between [name] and description. * <p> * If false, name and description should be shown with no separation. * `:` is typically used as a separator when displaying as text. */ public boolean getShowSeparator() { return getBooleanMember("showSeparator", true); } /** * Returns a description with a short summary of the node itself not * including children or properties. * <p> * `parentConfiguration` specifies how the parent is rendered as text art. * For example, if the parent does not line break between properties, the * description of a property should also be a single line if possible. */ public String getDescription() { return getStringMember("description"); } /** * Returns a transformed rect that describes the bounding box for an element * <p> */ public TransformedRect getTransformToRoot() { if (!json.has("transformToRoot")) { return null; } return new TransformedRect(json.getAsJsonObject("transformToRoot")); } /** * Priority level of the diagnostic used to control which diagnostics should * be shown and filtered. * <p> * Typically this only makes sense to set to a different value than * [DiagnosticLevel.info] for diagnostics representing properties. Some * subclasses have a `level` argument to their constructor which influences * the value returned here but other factors also influence it. For example, * whether an exception is thrown computing a property value * [DiagnosticLevel.error] is returned. */ public DiagnosticLevel getLevel() { return getLevelMember("level", DiagnosticLevel.info); } /** * Returns a value associated with the node. This is a URL for DevToolsDeepLinkProperty nodes. */ public String getValue() { return getStringMember("value"); } /** * Whether the name of the property should be shown when showing the default * view of the tree. * <p> * This could be set to false (hiding the name) if the value's description * will make the name self-evident. */ public boolean getShowName() { return getBooleanMember("showName", true); } /** * Description to show if the node has no displayed properties or children. */ public String getEmptyBodyDescription() { return getStringMember("emptyBodyDescription"); } /** * Hint for how the node should be displayed. */ public DiagnosticsTreeStyle getStyle() { return getStyleMember("style", DiagnosticsTreeStyle.sparse); } /** * Whether to wrap text on onto multiple lines or not. */ public boolean getAllowWrap() { return getBooleanMember("allowWrap", true); } /** * Dart class defining the diagnostic node. * <p> * For example, DiagnosticProperty<Color>, IntProperty, StringProperty, etc. * This should rarely be required except for cases where custom rendering is desired * of a specific Dart diagnostic class. */ public String getType() { return getStringMember("type"); } /** * Whether the description is enclosed in double quotes. * <p> * Only relevant for String properties. */ public boolean getIsQuoted() { return getBooleanMember("quoted", false); } public boolean hasIsQuoted() { return json.has("quoted"); } /** * Optional unit the [value] is measured in. * <p> * Unit must be acceptable to display immediately after a number with no * spaces. For example: 'physical pixels per logical pixel' should be a * [tooltip] not a [unit]. * <p> * Only specified for Number properties. */ public String getUnit() { return getStringMember("unit"); } public boolean hasUnit() { return json.has("unit"); } /** * String describing just the numeric [value] without a unit suffix. * <p> * Only specified for Number properties. */ public String getNumberToString() { return getStringMember("numberToString"); } public boolean hasNumberToString() { return json.has("numberToString"); } /** * Description to use if the property [value] is true. * <p> * If not specified and [value] equals true the property's priority [level] * will be [DiagnosticLevel.hidden]. * <p> * Only applies to Flag properties. */ public String getIfTrue() { return getStringMember("ifTrue"); } public boolean hasIfTrue() { return json.has("ifTrue"); } /** * Description to use if the property value is false. * <p> * If not specified and [value] equals false, the property's priority [level] * will be [DiagnosticLevel.hidden]. * <p> * Only applies to Flag properties. */ public String getIfFalse() { return getStringMember("ifFalse"); } public boolean hasIfFalse() { return json.has("ifFalse"); } /** * Value as a List of strings. * <p> * The raw value can always be extracted with the regular observatory protocol. * <p> * Only applies to IterableProperty. */ public ArrayList<String> getValues() { if (!json.has("values")) { return null; } final JsonArray rawValues = json.getAsJsonArray("values"); final ArrayList<String> values = new ArrayList<>(rawValues.size()); for (int i = 0; i < rawValues.size(); ++i) { values.add(rawValues.get(i).getAsString()); } return values; } public boolean hasValues() { return json.has("values"); } /** * Description to use if the property [value] is not null. * <p> * If the property [value] is not null and [ifPresent] is null, the * [level] for the property is [DiagnosticsLevel.hidden] and the description * from superclass is used. * <p> * Only specified for ObjectFlagProperty. */ public String getIfPresent() { return getStringMember("ifPresent"); } public boolean hasIfPresent() { return json.has("ifPresent"); } /** * If the [value] of the property equals [defaultValue] the priority [level] * of the property is downgraded to [DiagnosticLevel.fine] as the property * value is uninteresting. * <p> * This is the default value of the object represented as a String. * The actual Dart object representing the defaultValue can also be accessed via * the observatory protocol. We can add a convenience helper method to access it here * if there is a use case. * <p> * Typically you shouldn't need to worry about the default value as the underlying * machinery will generate appropriate description and priority level based on the * default value. */ public String getDefaultValue() { return getStringMember("defaultValue"); } /** * Whether a property has a default value. */ public boolean hasDefaultValue() { return json.has("defaultValue"); } /** * Description if the property description would otherwise be empty. * <p> * Consider showing the property value in gray in an IDE if the description matches * ifEmpty. */ public String getIfEmpty() { return getStringMember("ifEmpty"); } /** * Description if the property [value] is null. */ public String getIfNull() { return getStringMember("ifNull"); } /** * Optional tooltip typically describing the property. * <p> * Example tooltip: 'physical pixels per logical pixel' * <p> * If present, the tooltip is added in parenthesis after the raw value when * generating the string description. */ public String getTooltip() { return getStringMember("tooltip"); } public boolean hasTooltip() { return json.has("tooltip"); } /** * Whether a [value] of null causes the property to have [level] * [DiagnosticLevel.warning] warning that the property is missing a [value]. */ public boolean getMissingIfNull() { return getBooleanMember("missingIfNull", false); } /** * String representation of exception thrown if accessing the property * [value] threw an exception. */ public String exception() { return getStringMember("exception"); } /** * Whether accessing the property throws an exception. */ boolean hasException() { return json.has("exception"); } public boolean hasCreationLocation() { return location != null || json.has("creationLocation"); } public int getLocationId() { return JsonUtils.getIntMember(json, "locationId"); } public InspectorSourceLocation getCreationLocation() { if (location != null) { return location; } if (!hasCreationLocation()) { return null; } location = new InspectorSourceLocation(json.getAsJsonObject("creationLocation"), null, app.getProject()); return location; } /** * String representation of the type of the property [value]. * <p> * This is determined from the type argument `T` used to instantiate the * [DiagnosticsProperty] class. This means that the type is available even if * [value] is null, but it also means that the [propertyType] is only as * accurate as the type provided when invoking the constructor. * <p> * Generally, this is only useful for diagnostic tools that should display * null values in a manner consistent with the property type. For example, a * tool might display a null [Color] value as an empty rectangle instead of * the word "null". */ public String getPropertyType() { return getStringMember("propertyType"); } /** * If the [value] of the property equals [defaultValue] the priority [level] * of the property is downgraded to [DiagnosticLevel.fine] as the property * value is uninteresting. * <p> * [defaultValue] has type [T] or is [kNoDefaultValue]. */ public DiagnosticLevel getDefaultLevel() { return getLevelMember("defaultLevel", DiagnosticLevel.info); } /** * Whether the value of the property is a Diagnosticable value itself. * Optionally, properties that are themselves Diagnosticable should be * displayed as trees of diagnosticable properties and children. * <p> * TODO(jacobr): add helpers to get the properties and children of * this diagnosticable value even if getChildren and getProperties * would return null. This will allow showing nested data for properties * that don't show children by default in other debugging output but * could. */ public boolean getIsDiagnosticableValue() { return getBooleanMember("isDiagnosticableValue", false); } /** * Service used to retrieve more detailed information about the value of the property and its children and properties. */ @NotNull private final CompletableFuture<InspectorService.ObjectGroup> inspectorService; /** * JSON describing the diagnostic node. */ private final JsonObject json; private CompletableFuture<ArrayList<DiagnosticsNode>> children; private CompletableFuture<Map<String, InstanceRef>> valueProperties; private final boolean isProperty; public boolean isProperty() { return isProperty; } public String getStringMember(@NotNull String memberName) { return JsonUtils.getStringMember(json, memberName); } private boolean getBooleanMember(String memberName, boolean defaultValue) { if (!json.has(memberName)) { return defaultValue; } final JsonElement value = json.get(memberName); if (value instanceof JsonNull) { return defaultValue; } return value.getAsBoolean(); } private DiagnosticLevel getLevelMember(String memberName, DiagnosticLevel defaultValue) { if (!json.has(memberName)) { return defaultValue; } final JsonElement value = json.get(memberName); if (value instanceof JsonNull) { return defaultValue; } try { return DiagnosticLevel.valueOf(value.getAsString()); } catch (IllegalArgumentException ignore) { return defaultValue; } } private DiagnosticsTreeStyle getStyleMember(String memberName, DiagnosticsTreeStyle defaultValue) { if (!json.has(memberName)) { return defaultValue; } final JsonElement value = json.get(memberName); if (value instanceof JsonNull) { return defaultValue; } return DiagnosticsTreeStyle.valueOf(value.getAsString()); } /** * Returns a reference to the value the DiagnosticsNode object is describing. */ public InspectorInstanceRef getValueRef() { final JsonElement valueId = json.get("valueId"); return new InspectorInstanceRef(valueId.isJsonNull() ? null : valueId.getAsString()); } public boolean isEnumProperty() { final String type = getType(); return type != null && type.startsWith("EnumProperty<"); } /** * Returns a list of raw Dart property values of the Dart value of this * property that are useful for custom display of the property value. * For example, get the red, green, and blue components of color. * <p> * Unfortunately we cannot just use the list of fields from the Observatory * Instance object for the Dart value because much of the relevant * information to display good visualizations of Flutter values is stored * in properties not in fields. */ public CompletableFuture<Map<String, InstanceRef>> getValueProperties() { final InspectorInstanceRef valueRef = getValueRef(); if (valueProperties == null) { if (getPropertyType() == null || valueRef == null || valueRef.getId() == null) { valueProperties = CompletableFuture.completedFuture(null); return valueProperties; } if (isEnumProperty()) { // Populate all the enum property values. valueProperties = inspectorService.thenComposeAsync((service) -> { if (service == null) { return null; } return service.getEnumPropertyValues(getValueRef()); }); return valueProperties; } final String[] propertyNames; // Add more cases here as visual displays for additional Dart objects // are added. switch (getPropertyType()) { case "Color": propertyNames = new String[]{"red", "green", "blue", "alpha"}; break; case "IconData": propertyNames = new String[]{"codePoint"}; break; default: valueProperties = CompletableFuture.completedFuture(null); return valueProperties; } valueProperties = inspectorService.thenComposeAsync((service) -> { if (service == null) { return null; } return service.getDartObjectProperties(getValueRef(), propertyNames); }); } return valueProperties; } public JsonObject getValuePropertiesJson() { return json.getAsJsonObject("valueProperties"); } public boolean hasChildren() { return getBooleanMember("hasChildren", false); } public boolean isCreatedByLocalProject() { return getBooleanMember("createdByLocalProject", false); } /** * Whether this node is being displayed as a full tree or a filtered tree. */ public boolean isSummaryTree() { return getBooleanMember("summaryTree", false); } /** * Whether this node is being displayed as a full tree or a filtered tree. */ public boolean isStateful() { return getBooleanMember("stateful", false); } public String getWidgetRuntimeType() { return getStringMember("widgetRuntimeType"); } /** * Check whether children are already available. */ public boolean childrenReady() { return json.has("children") || (children != null && children.isDone()); } public CompletableFuture<ArrayList<DiagnosticsNode>> getChildren() { if (children == null) { if (json.has("children")) { final JsonArray jsonArray = json.get("children").getAsJsonArray(); final ArrayList<DiagnosticsNode> nodes = new ArrayList<>(); for (JsonElement element : jsonArray) { final DiagnosticsNode child = new DiagnosticsNode(element.getAsJsonObject(), inspectorService, app, false, parent); child.setParent(this); nodes.add(child); } children = CompletableFuture.completedFuture(nodes); } else if (hasChildren()) { children = inspectorService.thenComposeAsync((service) -> { if (service == null) { return null; } return service.getChildren(getDartDiagnosticRef(), isSummaryTree(), this); }); } else { // Known to have no children so we can provide the children immediately. children = CompletableFuture.completedFuture(new ArrayList<>()); } } return children; } /** * Reference the actual Dart DiagnosticsNode object this object is referencing. */ public InspectorInstanceRef getDartDiagnosticRef() { final JsonElement objectId = json.get("objectId"); return new InspectorInstanceRef(objectId.isJsonNull() ? null : objectId.getAsString()); } public boolean hasInlineProperties() { if (!json.has("properties")) { return false; } final JsonArray jsonArray = json.get("properties").getAsJsonArray(); return !jsonArray.isEmpty(); } /** * Properties to show inline in the widget tree. */ public ArrayList<DiagnosticsNode> getInlineProperties() { if (cachedProperties == null) { cachedProperties = new ArrayList<>(); if (json.has("properties")) { final JsonArray jsonArray = json.get("properties").getAsJsonArray(); for (JsonElement element : jsonArray) { cachedProperties.add(new DiagnosticsNode(element.getAsJsonObject(), inspectorService, app, true, parent)); } } } return cachedProperties; } public CompletableFuture<ArrayList<DiagnosticsNode>> getProperties(InspectorService.ObjectGroup objectGroup) { return objectGroup.getProperties(getDartDiagnosticRef()); } @NotNull public CompletableFuture<String> getPropertyDoc() { if (propertyDocFuture == null) { propertyDocFuture = createPropertyDocFuture(); } return propertyDocFuture; } private CompletableFuture<String> createPropertyDocFuture() { final DiagnosticsNode parent = getParent(); if (parent != null) { return inspectorService.thenComposeAsync((service) -> service.toDartVmServiceValueForSourceLocation(parent.getValueRef()) .thenComposeAsync((DartVmServiceValue vmValue) -> { if (vmValue == null) { return CompletableFuture.completedFuture(null); } return inspectorService.getNow(null).getPropertyLocation(vmValue.getInstanceRef(), getName()) .thenApplyAsync((XSourcePosition sourcePosition) -> { if (sourcePosition != null) { final VirtualFile file = sourcePosition.getFile(); final int offset = sourcePosition.getOffset(); final Project project = getProject(file); if (project != null) { final List<HoverInformation> hovers = DartAnalysisServerService.getInstance(project).analysis_getHover(file, offset); if (!hovers.isEmpty()) { return hovers.get(0).getDartdoc(); } } } return "Unable to find property source"; }); })).exceptionally(t -> { LOG.info("ignoring exception from toObjectForSourceLocation: " + t.toString()); return null; }); } return CompletableFuture.completedFuture("Unable to find property source"); } @Nullable private Project getProject(@NotNull VirtualFile file) { return app != null ? app.getProject() : ProjectUtil.guessProjectForFile(file); } private void setCreationLocation(InspectorSourceLocation location) { this.location = location; } @NotNull public CompletableFuture<InspectorService.ObjectGroup> getInspectorService() { return inspectorService; } @Nullable public Icon getIcon() { return iconMaker.fromWidgetName(getDescription()); } /** * Returns true if two diagnostic nodes are indistinguishable from * the perspective of a user debugging. * <p> * In practice this means that all fields but the objectId and valueId * properties for the DiagnosticsNode objects are identical. The valueId * field may change even for properties that have not changed because in * some cases such as the 'created' property for an element, the property * value is created dynamically each time 'getProperties' is called. */ public boolean identicalDisplay(DiagnosticsNode node) { if (node == null) { return false; } final Set<Map.Entry<String, JsonElement>> entries = json.entrySet(); if (entries.size() != node.json.entrySet().size()) { return false; } for (Map.Entry<String, JsonElement> entry : entries) { final String key = entry.getKey(); if (key.equals("objectId") || key.equals("valueId")) { continue; } if (!entry.getValue().equals(node.json.get(key))) { return false; } } return true; } /** * Await a Future invoking the callback on completion on the UI thread only if the * InspectorService group is still alive when the Future completes. */ public <T> void safeWhenComplete(CompletableFuture<T> future, BiConsumer<? super T, ? super Throwable> action) { try { final InspectorService.ObjectGroup service = inspectorService.getNow(null); if (service != null) { service.safeWhenComplete(future, action); return; } inspectorService.whenCompleteAsync((group, t) -> { if (group == null || t != null) { return; } group.safeWhenComplete(future, action); }); } catch (Exception ignored) { // Nothing to do if the service can't be acquired. } } public void setSelection(InspectorInstanceRef ref, boolean uiAlreadyUpdated) { inspectorService.thenAcceptAsync((service) -> { if (service == null) { return; } service.setSelection(ref, uiAlreadyUpdated, false); }); } }
flutter-intellij/flutter-idea/src/io/flutter/inspector/DiagnosticsNode.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/inspector/DiagnosticsNode.java", "repo_id": "flutter-intellij", "token_count": 8940 }
512
/* * Copyright 2017 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. */ package io.flutter.inspector; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.project.Project; import com.intellij.ui.AppUIUtil; import com.intellij.xdebugger.XSourcePosition; import com.intellij.xdebugger.frame.XNavigatable; import com.intellij.xdebugger.frame.XValue; import io.flutter.FlutterInitializer; import io.flutter.utils.AsyncUtils; import io.flutter.vmService.frame.DartVmServiceValue; import org.jetbrains.annotations.NotNull; import javax.swing.tree.DefaultMutableTreeNode; import java.util.concurrent.CompletableFuture; public abstract class JumpToSourceActionBase extends InspectorTreeActionBase { /** * A string id intended for tracking usage analytics. */ @NotNull private final String id; JumpToSourceActionBase(@NotNull String id) { this.id = id; } @Override protected void perform(final DefaultMutableTreeNode node, final DiagnosticsNode diagnosticsNode, final AnActionEvent e) { final Project project = e.getProject(); if (project == null) { return; } FlutterInitializer.getAnalytics().sendEvent("inspector", id); final XNavigatable navigatable = sourcePosition -> { if (sourcePosition != null) { //noinspection CodeBlock2Expr AppUIUtil.invokeOnEdt(() -> { sourcePosition.createNavigatable(project).navigate(true); }, project.getDisposed()); } }; final XSourcePosition sourcePosition = getSourcePosition(diagnosticsNode); if (sourcePosition != null) { // Source position is available immediately. navigatable.setSourcePosition(sourcePosition); return; } // We have to get a DartVmServiceValue to compute the source position. final CompletableFuture<InspectorService.ObjectGroup> inspectorService = diagnosticsNode.getInspectorService(); final CompletableFuture<DartVmServiceValue> valueFuture = inspectorService.thenComposeAsync((service) -> service.toDartVmServiceValueForSourceLocation(diagnosticsNode.getValueRef())); AsyncUtils.whenCompleteUiThread(valueFuture, (DartVmServiceValue value, Throwable throwable) -> { if (throwable != null) { return; } startComputingSourcePosition(value, navigatable); }); } /** * Implement if the source position is available directly from the diagnostics node. */ protected abstract XSourcePosition getSourcePosition(DiagnosticsNode node); /** * Implement if the source position is available from the XValue of the diagnostics node. */ protected abstract void startComputingSourcePosition(XValue value, XNavigatable navigatable); }
flutter-intellij/flutter-idea/src/io/flutter/inspector/JumpToSourceActionBase.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/inspector/JumpToSourceActionBase.java", "repo_id": "flutter-intellij", "token_count": 902 }
513
<?xml version="1.0" encoding="UTF-8"?> <form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="io.flutter.module.FlutterGeneratorPeer"> <grid id="27dc6" binding="myMainPanel" layout-manager="GridLayoutManager" row-count="6" column-count="12" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1"> <margin top="0" left="5" bottom="0" right="8"/> <constraints> <xy x="20" y="20" width="565" height="363"/> </constraints> <properties/> <border type="none"/> <children> <component id="4e54c" class="com.intellij.ui.components.JBLabel"> <constraints> <grid row="0" column="0" row-span="1" col-span="2" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/> </constraints> <properties> <labelFor value="b09db"/> <text resource-bundle="io/flutter/FlutterBundle" key="flutter.sdk.path.label"/> </properties> </component> <component id="b09db" class="com.intellij.ui.ComboboxWithBrowseButton" binding="mySdkPathComboWithBrowse" custom-create="true"> <constraints> <grid row="0" column="2" row-span="1" col-span="10" vsize-policy="0" hsize-policy="7" anchor="0" fill="1" indent="0" use-parent-layout="false"/> </constraints> <properties/> </component> <component id="2c07c" class="com.intellij.ui.components.JBLabel" binding="myVersionContent"> <constraints> <grid row="2" column="2" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/> </constraints> <properties> <text value=""/> </properties> </component> <vspacer id="e8033"> <constraints> <grid row="4" column="0" row-span="1" col-span="2" vsize-policy="6" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"/> </constraints> </vspacer> <grid id="91fa8" layout-manager="GridLayoutManager" row-count="1" column-count="3" same-size-horizontally="false" same-size-vertically="false" hgap="0" vgap="-1"> <margin top="0" left="0" bottom="0" right="0"/> <constraints> <grid row="5" column="0" row-span="1" col-span="12" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/> </constraints> <properties/> <border type="none"/> <children> <component id="a1cd0" class="javax.swing.JLabel" binding="errorIcon"> <constraints> <grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/> </constraints> <properties> <text value="icon_placeholder"/> </properties> </component> <hspacer id="b4466"> <constraints> <grid row="0" column="2" row-span="1" col-span="1" vsize-policy="1" hsize-policy="6" anchor="0" fill="1" indent="0" use-parent-layout="false"/> </constraints> </hspacer> <scrollpane id="63dd2" binding="errorPane"> <constraints> <grid row="0" column="1" row-span="1" col-span="1" vsize-policy="7" hsize-policy="7" anchor="0" fill="3" indent="0" use-parent-layout="false"/> </constraints> <properties/> <border type="empty"/> <children> <component id="a87fb" class="javax.swing.JTextPane" binding="errorText"> <constraints/> <properties> <text value="Error text placeholder"/> </properties> </component> </children> </scrollpane> </children> </grid> <nested-form id="df11" form-file="io/flutter/module/settings/SettingsHelpForm.form" binding="myHelpForm"> <constraints> <grid row="1" column="0" row-span="1" col-span="12" vsize-policy="0" hsize-policy="6" anchor="0" fill="1" indent="0" use-parent-layout="false"/> </constraints> </nested-form> </children> </grid> </form>
flutter-intellij/flutter-idea/src/io/flutter/module/FlutterGeneratorPeer.form/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/module/FlutterGeneratorPeer.form", "repo_id": "flutter-intellij", "token_count": 1981 }
514
/* * 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. */ package io.flutter.perf; import com.intellij.codeInsight.hint.HintManager; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.event.EditorMouseEvent; import com.intellij.openapi.editor.event.EditorMouseEventArea; import com.intellij.openapi.editor.event.EditorMouseListener; import com.intellij.openapi.editor.ex.MarkupModelEx; import com.intellij.openapi.editor.ex.RangeHighlighterEx; import com.intellij.openapi.editor.markup.*; import com.intellij.openapi.fileEditor.TextEditor; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.wm.ToolWindow; import com.intellij.openapi.wm.ex.ToolWindowManagerEx; import com.intellij.ui.ColorUtil; import com.intellij.ui.JBColor; import com.intellij.xdebugger.XSourcePosition; import io.flutter.performance.FlutterPerformanceView; import io.flutter.run.daemon.FlutterApp; import io.flutter.utils.AsyncUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * This class is a view model managing display of performance statistics for * a specific TextEditor using RangeHighlighters to show the performance * statistics as animated icons in the gutter of the text editor and by * highlighting the ranges of text corresponding to the performance statistcs. */ class EditorPerfDecorations implements EditorMouseListener, EditorPerfModel { private static final int HIGHLIGHTER_LAYER = HighlighterLayer.SELECTION - 1; /** * Experimental option to animate highlighted widget names. * <p> * Disabled by default as animating contents of the TextEditor results in * higher than desired memory usage. */ public static boolean ANIMATE_WIDGET_NAME_HIGLIGHTS = false; @NotNull private final TextEditor textEditor; @NotNull private final FlutterApp app; @NotNull private FilePerfInfo stats; private boolean hasDecorations = false; private boolean hoveredOverLineMarkerArea = false; private final Map<TextRange, PerfGutterIconRenderer> perfMarkers = new HashMap<>(); private boolean alwaysShowLineMarkersOverride = false; EditorPerfDecorations(@NotNull TextEditor textEditor, @NotNull FlutterApp app) { this.textEditor = textEditor; this.app = app; stats = new FilePerfInfo(); textEditor.getEditor().addEditorMouseListener(this); } @Override public boolean getAlwaysShowLineMarkers() { return hoveredOverLineMarkerArea || alwaysShowLineMarkersOverride; } @Override public void setAlwaysShowLineMarkersOverride(boolean show) { final boolean lastValue = getAlwaysShowLineMarkers(); alwaysShowLineMarkersOverride = show; if (lastValue != getAlwaysShowLineMarkers()) { updateIconUIAnimations(); } } @NotNull @Override public FilePerfInfo getStats() { return stats; } @NotNull @Override public TextEditor getTextEditor() { return textEditor; } @NotNull @Override public FlutterApp getApp() { return app; } void setHasDecorations(boolean value) { if (value != hasDecorations) { hasDecorations = value; } } @Override public void setPerfInfo(@NotNull FilePerfInfo stats) { this.stats = stats; final Editor editor = textEditor.getEditor(); final MarkupModel markupModel = editor.getMarkupModel(); // Remove markers that aren't in the new perf report. final List<TextRange> rangesToRemove = new ArrayList<>(); for (TextRange range : perfMarkers.keySet()) { if (!stats.hasLocation(range)) { rangesToRemove.add(range); } } for (TextRange range : rangesToRemove) { removeMarker(range); } for (TextRange range : stats.getLocations()) { final PerfGutterIconRenderer existing = perfMarkers.get(range); if (existing == null) { addRangeHighlighter(range, markupModel); } else { existing.updateUI(true); } } setHasDecorations(true); } private void removeMarker(TextRange range) { final PerfGutterIconRenderer marker = perfMarkers.remove(range); if (marker != null) { final Editor editor = textEditor.getEditor(); final MarkupModel markupModel = editor.getMarkupModel(); markupModel.removeHighlighter(marker.getHighlighter()); } } @Override public void markAppIdle() { stats.markAppIdle(); updateIconUIAnimations(); } private void addRangeHighlighter(TextRange textRange, MarkupModel markupModel) { final RangeHighlighter rangeHighlighter = markupModel.addRangeHighlighter( textRange.getStartOffset(), textRange.getEndOffset(), HIGHLIGHTER_LAYER, new TextAttributes(), HighlighterTargetArea.EXACT_RANGE); final PerfGutterIconRenderer renderer = new PerfGutterIconRenderer( textRange, this, rangeHighlighter ); rangeHighlighter.setGutterIconRenderer(renderer); assert !perfMarkers.containsKey(textRange); perfMarkers.put(textRange, renderer); } @Override public boolean isAnimationActive() { return getStats().getTotalValue(PerfMetric.peakRecent) > 0; } @Override public void onFrame() { if (app.isReloading() || !hasDecorations || !isAnimationActive()) { return; } updateIconUIAnimations(); } private void updateIconUIAnimations() { if (!textEditor.getComponent().isVisible()) { return; } for (PerfGutterIconRenderer marker : perfMarkers.values()) { marker.updateUI(true); } } private void removeHighlightersFromEditor() { final List<RangeHighlighter> highlighters = new ArrayList<>(); final MarkupModel markupModel = textEditor.getEditor().getMarkupModel(); for (PerfGutterIconRenderer marker : perfMarkers.values()) { markupModel.removeHighlighter(marker.getHighlighter()); } perfMarkers.clear(); setHasDecorations(false); } public void flushDecorations() { if (hasDecorations && textEditor.isValid()) { setHasDecorations(false); ApplicationManager.getApplication().invokeLater(this::removeHighlightersFromEditor); } } @Override public void dispose() { textEditor.getEditor().removeEditorMouseListener(this); flushDecorations(); } @Override public void mousePressed(@NotNull EditorMouseEvent e) { } @Override public void mouseClicked(@NotNull EditorMouseEvent e) { } @Override public void mouseReleased(@NotNull EditorMouseEvent e) { } @Override public void mouseEntered(EditorMouseEvent e) { final EditorMouseEventArea area = e.getArea(); if (!hoveredOverLineMarkerArea && area == EditorMouseEventArea.LINE_MARKERS_AREA || area == EditorMouseEventArea.FOLDING_OUTLINE_AREA || area == EditorMouseEventArea.LINE_NUMBERS_AREA) { // Hover is over the gutter area. setHoverState(true); } } @Override public void mouseExited(EditorMouseEvent e) { final EditorMouseEventArea area = e.getArea(); setHoverState(false); // TODO(jacobr): hovers over a tooltip triggered by a gutter icon should // be considered a hover of the gutter but this logic does not handle that // case correctly. } private void setHoverState(boolean value) { if (value != hoveredOverLineMarkerArea) { hoveredOverLineMarkerArea = value; updateIconUIAnimations(); } } @Override public void clear() { stats.clear(); removeHighlightersFromEditor(); } } /** * This class renders the animated gutter icons used to visualize how much * widget repaint or rebuild work is happening. * <p> * This is a somewhat strange GutterIconRender in that we use it to orchestrate * animating the color of the associated RangeHighlighter and changing the icon * of the GutterIconRenderer when performance changes without requiring the * GutterIconRenderer to be discarded. markupModel.fireAttributesChanged is * used to notify the MarkupModel when state has changed and a rerender is * required. */ class PerfGutterIconRenderer extends GutterIconRenderer { // Speed of the animation in radians per second. private static final double ANIMATION_SPEED = 4.0; private final RangeHighlighter highlighter; private final TextRange range; private final EditorPerfModel perfModelForFile; // Tracked so we know when to notify that our icon has changed. private Icon lastIcon; PerfGutterIconRenderer(TextRange range, EditorPerfModel perfModelForFile, RangeHighlighter highlighter) { this.highlighter = highlighter; this.range = range; this.perfModelForFile = perfModelForFile; final TextAttributes textAttributes = highlighter.getTextAttributes(null); assert textAttributes != null; textAttributes.setEffectType(EffectType.LINE_UNDERSCORE); updateUI(false); } public boolean isNavigateAction() { return isActive(); } private FlutterApp getApp() { return perfModelForFile.getApp(); } private int getCurrentValue() { return perfModelForFile.getStats().getCurrentValue(range); } private int getDisplayValue() { final int value = getCurrentValue(); if (value == 0 && perfModelForFile.getAlwaysShowLineMarkers()) { // This is the case where the value was previously non-zero but the app // is idle so the value was reset. For all ui rendering logic we treat // the value as 1 so that consistent coloring is used throughout the // ui. Alternately we could use the original non-zero value but that // could be more confusing to users. return 1; } return value; } private boolean isActive() { return getDisplayValue() > 0; } RangeHighlighter getHighlighter() { return highlighter; } /** * Returns the action executed when the icon is left-clicked. * * @return the action instance, or null if no action is required. */ @Nullable public AnAction getClickAction() { return new AnAction() { @Override public void actionPerformed(@NotNull AnActionEvent event) { if (isActive()) { final ToolWindowManagerEx toolWindowManager = ToolWindowManagerEx.getInstanceEx(getApp().getProject()); final ToolWindow flutterPerfToolWindow = toolWindowManager.getToolWindow(FlutterPerformanceView.TOOL_WINDOW_ID); if (flutterPerfToolWindow == null) { return; } if (flutterPerfToolWindow.isVisible()) { showPerfViewMessage(); return; } flutterPerfToolWindow.show(() -> showPerfViewMessage()); } } }; } private void showPerfViewMessage() { final FlutterPerformanceView flutterPerfView = getApp().getProject().getService(FlutterPerformanceView.class); flutterPerfView.showForAppRebuildCounts(getApp()); final String message = "<html><body>" + getTooltipHtmlFragment() + "</body></html>"; final Iterable<SummaryStats> current = perfModelForFile.getStats().getRangeStats(range); if (current.iterator().hasNext()) { final SummaryStats first = current.iterator().next(); final XSourcePosition position = first.getLocation().getXSourcePosition(); if (position != null) { AsyncUtils.invokeLater(() -> { position.createNavigatable(getApp().getProject()).navigate(true); HintManager.getInstance().showInformationHint(perfModelForFile.getTextEditor().getEditor(), message); }); } } } @NotNull @Override public Alignment getAlignment() { return Alignment.LEFT; } @NotNull @Override public Icon getIcon() { lastIcon = getIconInternal(); return lastIcon; } public Icon getIconInternal() { return Icons.getIconForCount(getCurrentValue(), perfModelForFile.getAlwaysShowLineMarkers()); } Color getErrorStripeMarkColor() { // TODO(jacobr): tween from green or blue to red depending on the count. final int count = getDisplayValue(); if (count == 0) { return null; } if (count >= Icons.HIGH_LOAD_THRESHOLD) { return JBColor.YELLOW; } return JBColor.GRAY; } public void updateUI(boolean repaint) { final int count = getDisplayValue(); final TextAttributes textAttributes = highlighter.getTextAttributes(null); assert textAttributes != null; boolean changed = false; if (count > 0) { Color targetColor = getErrorStripeMarkColor(); if (EditorPerfDecorations.ANIMATE_WIDGET_NAME_HIGLIGHTS) { final double animateTime = (double)(System.currentTimeMillis()) * 0.001; // TODO(jacobr): consider tracking a start time for the individual // animation instead of having all animations running in sync. // 1.0 - Math.cos is used so that balance is 0.0 at the start of the animation // and the value will vary from 0 to 1.0 final double balance = (1.0 - Math.cos(animateTime * ANIMATION_SPEED)) * 0.5; targetColor = ColorUtil.mix(JBColor.WHITE, targetColor, balance); } if (!targetColor.equals(textAttributes.getEffectColor())) { textAttributes.setEffectColor(targetColor); changed = true; } } else { textAttributes.setEffectColor(null); } final Color errorStripeColor = getErrorStripeMarkColor(); highlighter.setErrorStripeMarkColor(errorStripeColor); if (repaint && lastIcon != getIconInternal()) { changed = true; } if (changed && repaint) { final MarkupModel markupModel = perfModelForFile.getTextEditor().getEditor().getMarkupModel(); ((MarkupModelEx)markupModel).fireAttributesChanged((RangeHighlighterEx)highlighter, true, false); } } @SuppressWarnings("StringConcatenationInsideStringBufferAppend") String getTooltipHtmlFragment() { final StringBuilder sb = new StringBuilder(); boolean first = true; for (SummaryStats stats : perfModelForFile.getStats().getRangeStats(range)) { final String style = first ? "" : "margin-top: 8px"; first = false; sb.append("<p style='" + style + "'>"); if (stats.getKind() == PerfReportKind.rebuild) { sb.append("Rebuild"); } else if (stats.getKind() == PerfReportKind.repaint) { sb.append("Repaint"); } sb.append(" counts for: <strong>" + stats.getDescription()); sb.append("</strong></p>"); sb.append("<p style='padding-left: 8px'>"); sb.append("For last frame: " + stats.getValue(PerfMetric.lastFrame) + "<br>"); sb.append("In past second: " + stats.getValue(PerfMetric.pastSecond) + "<br>"); sb.append("Since entering the current screen: " + stats.getValue(PerfMetric.totalSinceEnteringCurrentScreen) + "<br>"); sb.append("Since last hot reload/restart: " + stats.getValue(PerfMetric.total)); sb.append("</p>"); } if (sb.isEmpty()) { sb.append("<p><b>No widget rebuilds detected for line.</b></p>"); } return sb.toString(); } @Override public String getTooltipText() { return "<html><body>" + getTooltipHtmlFragment() + "</body></html>"; } @Override public boolean equals(Object obj) { if (!(obj instanceof PerfGutterIconRenderer)) { return false; } final PerfGutterIconRenderer other = (PerfGutterIconRenderer)obj; return other.getCurrentValue() == getCurrentValue(); } @Override public int hashCode() { return getCurrentValue(); } }
flutter-intellij/flutter-idea/src/io/flutter/perf/EditorPerfDecorations.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/perf/EditorPerfDecorations.java", "repo_id": "flutter-intellij", "token_count": 5584 }
515
/* * 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. */ package io.flutter.perf; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.Ref; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.util.concurrency.Semaphore; import org.dartlang.vm.service.VmService; import org.dartlang.vm.service.consumer.GetIsolateConsumer; import org.dartlang.vm.service.consumer.GetLibraryConsumer; import org.dartlang.vm.service.consumer.GetObjectConsumer; import org.dartlang.vm.service.element.*; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /// XXX probably not needed. class ScriptManager { private static final long RESPONSE_WAIT_TIMEOUT = 3000; @NotNull private final VmService vmService; private final VirtualFileManager virtualFileManager = VirtualFileManager.getInstance(); private IsolateRef isolateRef; private final Map<String, Script> scriptMap = new HashMap<>(); private final Map<String, Map<Integer, Pair<Integer, Integer>>> linesAndColumnsMap = new HashMap<>(); public ScriptManager(@NotNull VmService vmService) { this.vmService = vmService; } public void reset() { scriptMap.clear(); } public void setCurrentIsolate(IsolateRef isolateRef) { this.isolateRef = isolateRef; } @Nullable private Isolate getCurrentIsolate() { final Ref<Isolate> resultRef = Ref.create(); final Semaphore semaphore = new Semaphore(); semaphore.down(); vmService.getIsolate(isolateRef.getId(), new GetIsolateConsumer() { @Override public void received(Isolate isolate) { resultRef.set(isolate); semaphore.up(); } @Override public void received(Sentinel sentinel) { semaphore.up(); } @Override public void onError(RPCError error) { semaphore.up(); } }); semaphore.waitFor(RESPONSE_WAIT_TIMEOUT); return resultRef.get(); } @Nullable public ScriptRef getScriptRefFor(@NotNull VirtualFile file) { final Isolate isolate = getCurrentIsolate(); if (isolate == null) { return null; } for (LibraryRef libraryRef : isolate.getLibraries()) { final String uri = libraryRef.getUri(); if (uri.startsWith("file:")) { final VirtualFile libraryFile = virtualFileManager.findFileByUrl(uri); if (file.equals(libraryFile)) { final Library library = getLibrary(libraryRef); if (library != null) { if (!library.getScripts().isEmpty()) { // TODO(devoncarew): If more than one, should we return the newest script? return library.getScripts().get(0); } } } } } return null; } @Nullable private Library getLibrary(LibraryRef libraryRef) { // TODO(devoncarew): Consider changing the signature to `CompletableFuture getLibrary(LibraryRef instance)` // (see also the EvalOnDartLibrary implementation). final Ref<Library> resultRef = Ref.create(); final Semaphore semaphore = new Semaphore(); semaphore.down(); vmService.getLibrary(isolateRef.getId(), libraryRef.getId(), new GetLibraryConsumer() { @Override public void received(Library library) { resultRef.set(library); semaphore.up(); } @Override public void onError(RPCError error) { semaphore.up(); } }); semaphore.waitFor(RESPONSE_WAIT_TIMEOUT); return resultRef.get(); } public void populateFor(ScriptRef scriptRef) { if (!scriptMap.containsKey(scriptRef.getId())) { scriptMap.put(scriptRef.getId(), getScriptSync(scriptRef)); linesAndColumnsMap.put(scriptRef.getId(), createTokenPosToLineAndColumnMap(scriptMap.get(scriptRef.getId()))); } } public Pair<Integer, Integer> getLineColumnPosForTokenPos(@NotNull ScriptRef scriptRef, int tokenPos) { final Map<Integer, Pair<Integer, Integer>> map = linesAndColumnsMap.get(scriptRef.getId()); return map == null ? null : map.get(tokenPos); } private Script getScriptSync(@NotNull final ScriptRef scriptRef) { final Ref<Script> resultRef = Ref.create(); final Semaphore semaphore = new Semaphore(); semaphore.down(); vmService.getObject(isolateRef.getId(), scriptRef.getId(), new GetObjectConsumer() { @Override public void received(Obj script) { resultRef.set((Script)script); semaphore.up(); } @Override public void received(Sentinel response) { semaphore.up(); } @Override public void onError(RPCError error) { semaphore.up(); } }); semaphore.waitFor(RESPONSE_WAIT_TIMEOUT); return resultRef.get(); } private static Map<Integer, Pair<Integer, Integer>> createTokenPosToLineAndColumnMap(@Nullable final Script script) { if (script == null) { return null; } // Each subarray consists of a line number followed by (tokenPos, columnNumber) pairs; // see https://github.com/dart-lang/vm_service_drivers/blob/master/dart/tool/service.md#script. final Map<Integer, Pair<Integer, Integer>> result = new HashMap<>(); for (List<Integer> lineAndPairs : script.getTokenPosTable()) { final Iterator<Integer> iterator = lineAndPairs.iterator(); final int line = Math.max(0, iterator.next() - 1); while (iterator.hasNext()) { final int tokenPos = iterator.next(); final int column = Math.max(0, iterator.next() - 1); result.put(tokenPos, Pair.create(line, column)); } } return result; } @Nullable public Script getScriptFor(@NotNull ScriptRef ref) { return scriptMap.get(ref.getId()); } }
flutter-intellij/flutter-idea/src/io/flutter/perf/ScriptManager.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/perf/ScriptManager.java", "repo_id": "flutter-intellij", "token_count": 2207 }
516
/* * 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. */ package io.flutter.performance; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.ActionGroup; import com.intellij.openapi.actionSystem.ActionManager; import com.intellij.openapi.actionSystem.DataProvider; import com.intellij.openapi.actionSystem.DefaultActionGroup; import com.intellij.openapi.fileEditor.TextEditor; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.SimpleColoredRenderer; import com.intellij.ui.SimpleTextAttributes; import com.intellij.ui.components.JBLabel; import com.intellij.ui.treeStructure.treetable.ListTreeTableModelOnColumns; import com.intellij.ui.treeStructure.treetable.TreeTable; import com.intellij.util.PathUtil; import com.intellij.util.ui.ColumnInfo; import com.intellij.xdebugger.XSourcePosition; import gnu.trove.TIntArrayList; import io.flutter.inspector.InspectorActions; import io.flutter.inspector.InspectorTree; import io.flutter.perf.*; import io.flutter.run.daemon.FlutterApp; import io.flutter.utils.AsyncUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.event.TreeSelectionEvent; import javax.swing.table.JTableHeader; import javax.swing.table.TableCellRenderer; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreeNode; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.ArrayList; import java.util.HashSet; import static io.flutter.perf.Icons.getIconForCount; class WidgetPerfTable extends TreeTable implements DataProvider, PerfModel { @SuppressWarnings("rawtypes") private final ColumnInfo[] modelColumns; private final CountColumnInfo countColumnInfo; private final WidgetNameColumnInfo widgetNameColumnInfo; private final FlutterApp app; private final FlutterWidgetPerfManager perfManager; private final ListTreeTableModelOnColumns model; private final DefaultMutableTreeNode root; private final PerfMetric metric; private final HashSet<String> openPaths = new HashSet<>(); private final ArrayList<PerfMetric> metrics; private ArrayList<SlidingWindowStatsSummary> entries = new ArrayList<>(); private boolean idle; private DefaultMutableTreeNode currentSelection; WidgetPerfTable(FlutterApp app, Disposable parentDisposable, PerfMetric metric) { super(new ListTreeTableModelOnColumns( new DefaultMutableTreeNode(), new ColumnInfo[]{ new WidgetNameColumnInfo("Widget"), new LocationColumnInfo("Location"), new CountColumnInfo(metric), new CountColumnInfo(PerfMetric.totalSinceEnteringCurrentScreen) } )); getTableHeader().setReorderingAllowed(false); setSurrendersFocusOnKeystroke(false); this.app = app; model = getTreeModel(); modelColumns = model.getColumns(); widgetNameColumnInfo = (WidgetNameColumnInfo)model.getColumns()[0]; countColumnInfo = (CountColumnInfo)model.getColumns()[2]; perfManager = FlutterWidgetPerfManager.getInstance(app.getProject()); setRootVisible(false); setSelectionMode(ListSelectionModel.SINGLE_SELECTION); getTree().addTreeSelectionListener(this::selectionListener); final MouseListener mouseListener = new MouseAdapter() { public void mousePressed(MouseEvent e) { final int rowIndex = getTree().getRowForLocation(e.getX(), e.getY()); if (rowIndex != -1) { onClickRow(rowIndex); } } @Override public void mouseEntered(MouseEvent e) { showLineMarkers(true); } @Override public void mouseExited(MouseEvent e) { showLineMarkers(false); } private void showLineMarkers(boolean show) { final FlutterWidgetPerf stats = perfManager.getCurrentStats(); if (stats != null) { stats.setAlwaysShowLineMarkersOverride(true); } } }; addMouseListener(mouseListener); setStriped(true); final JTableHeader tableHeader = getTableHeader(); tableHeader.setPreferredSize(new Dimension(0, getRowHeight())); getColumnModel().getColumn(0).setPreferredWidth(120); getColumnModel().getColumn(1).setPreferredWidth(200); getColumnModel().getColumn(2).setPreferredWidth(60); this.metric = metric; this.metrics = new ArrayList<>(); metrics.add(metric); metrics.add(PerfMetric.totalSinceEnteringCurrentScreen); root = new DefaultMutableTreeNode(); model.setRoot(root); } void sortByMetric(ArrayList<SlidingWindowStatsSummary> entries) { openPaths.clear(); for (TextEditor editor : perfManager.getSelectedEditors()) { final VirtualFile file = editor.getFile(); if (file != null) { openPaths.add(file.getPath()); } } if (entries != null) { entries.sort((a, b) -> { final int comparison = Integer.compare(b.getValue(metric), a.getValue(metric)); if (comparison != 0) { return comparison; } return Boolean.compare(isOpenLocation(b.getLocation()), isOpenLocation(a.getLocation())); }); } } public ArrayList<PerfMetric> getMetrics() { return metrics; } private boolean isOpenLocation(Location location) { if (location == null) { return false; } return openPaths.contains(location.path); } public void clear() { showStats(new ArrayList<>()); } @Override public boolean isAnimationActive() { if (idle) { return false; } // If any rows will be animating, the first row will be animating. return !entries.isEmpty() && entries.get(0).getValue(metric) > 0; } @Override public void onFrame() { if (app.isReloading() || entries.isEmpty() || !isAnimationActive()) { return; } updateIconUIAnimations(); } private void updateIconUIAnimations() { int lastActive = -1; // TODO(devoncarew): We've seen NPEs from here. for (int i = 0; i < entries.size() && entries.get(i).getValue(metric) > 0; ++i) { lastActive = i; } if (lastActive >= 0) { final int[] active = new int[lastActive + 1]; for (int i = 0; i <= lastActive; i++) { active[i] = i; } model.nodesChanged(root, active); } } private void onClickRow(int index) { if (index < 0 || index >= entries.size()) { return; } final SlidingWindowStatsSummary stats = entries.get(index); // If the selection is changed by this click there is no need to trigger // the navigation event here as it will be triggered by the selectionListener. final boolean selectionChanged = currentSelection == null || currentSelection.getUserObject() == stats; if (!selectionChanged) { navigateToStatsEntry(stats); } } private void selectionListener(TreeSelectionEvent event) { final DefaultMutableTreeNode selection = (DefaultMutableTreeNode)event.getPath().getLastPathComponent(); if (!event.isAddedPath()) { // We only care about selection events not deselection events. return; } if (currentSelection == selection) { // Selection didn't really change. Unfortunately, events about modifying // nodes result in spurious selection changed events. return; } currentSelection = selection; if (selection != null) { final SlidingWindowStatsSummary stats = (SlidingWindowStatsSummary)selection.getUserObject(); navigateToStatsEntry(stats); } } private void navigateToStatsEntry(SlidingWindowStatsSummary stats) { if (stats == null) { return; } final Location location = stats.getLocation(); final XSourcePosition position = location.getXSourcePosition(); if (position != null) { AsyncUtils.invokeLater(() -> { position.createNavigatable(app.getProject()).navigate(false); }); } } @Override public TableCellRenderer getCellRenderer(int row, int column) { //noinspection unchecked return modelColumns[column].getRenderer(null); } private ActionGroup createTreePopupActions() { final DefaultActionGroup group = new DefaultActionGroup(); final ActionManager actionManager = ActionManager.getInstance(); group.add(actionManager.getAction(InspectorActions.JUMP_TO_SOURCE)); return group; } ListTreeTableModelOnColumns getTreeModel() { return (ListTreeTableModelOnColumns)getTableModel(); } public void markAppIdle() { idle = true; widgetNameColumnInfo.setIdle(true); updateIconUIAnimations(); } public void showStats(ArrayList<SlidingWindowStatsSummary> entries) { if (entries == null) { entries = new ArrayList<>(); } idle = false; widgetNameColumnInfo.setIdle(false); final ArrayList<SlidingWindowStatsSummary> oldEntries = this.entries; sortByMetric(entries); this.entries = entries; int selectionIndex = -1; Location lastSelectedLocation = null; if (statsChanged(oldEntries, entries)) { final int selectedRowIndex = getSelectedRow(); if (selectedRowIndex != -1) { final Object selectedRow = getTreeModel().getRowValue(selectedRowIndex); if (selectedRow instanceof DefaultMutableTreeNode) { final DefaultMutableTreeNode selectedRowNode = (DefaultMutableTreeNode)selectedRow; final SlidingWindowStatsSummary selectedStats = (SlidingWindowStatsSummary)selectedRowNode.getUserObject(); if (selectedStats != null) { lastSelectedLocation = selectedStats.getLocation(); } } } final boolean previouslyEmpty = root.getChildCount() == 0; int childIndex = 0; final TIntArrayList indicesChanged = new TIntArrayList(); final TIntArrayList indicesInserted = new TIntArrayList(); for (SlidingWindowStatsSummary entry : entries) { if (entry.getLocation().equals(lastSelectedLocation)) { selectionIndex = childIndex; } if (childIndex >= root.getChildCount()) { root.add(new DefaultMutableTreeNode(entry, false)); indicesInserted.add(childIndex); } else { final DefaultMutableTreeNode existing = (DefaultMutableTreeNode)root.getChildAt(childIndex); final SlidingWindowStatsSummary existingEntry = (SlidingWindowStatsSummary)existing.getUserObject(); if (displayChanged(entry, existingEntry)) { model.nodeChanged(existing); indicesChanged.add(childIndex); } existing.setUserObject(entry); } childIndex++; } final int endChildIndex = childIndex; final ArrayList<TreeNode> nodesRemoved = new ArrayList<>(); final TIntArrayList indicesRemoved = new TIntArrayList(); // Gather nodes to remove. for (int j = endChildIndex; j < root.getChildCount(); j++) { nodesRemoved.add(root.getChildAt(j)); indicesRemoved.add(j); } // Actuallly remove nodes. while (endChildIndex < root.getChildCount()) { // Removing the last element is slightly more efficient. final int lastChild = root.getChildCount() - 1; root.remove(lastChild); } if (previouslyEmpty) { // TODO(jacobr): I'm not clear why this event is needed in this case. model.nodeStructureChanged(root); } else { // Report events for all the changes made to the table. if (!indicesChanged.isEmpty()) { model.nodesChanged(root, indicesChanged.toNativeArray()); } if (!indicesInserted.isEmpty()) { model.nodesWereInserted(root, indicesInserted.toNativeArray()); } if (!indicesRemoved.isEmpty()) { model.nodesWereRemoved(root, indicesRemoved.toNativeArray(), nodesRemoved.toArray()); } } if (selectionIndex >= 0) { getSelectionModel().setSelectionInterval(selectionIndex, selectionIndex); currentSelection = (DefaultMutableTreeNode)root.getChildAt(selectionIndex); } else { getSelectionModel().clearSelection(); } } } private boolean statsChanged(ArrayList<SlidingWindowStatsSummary> previous, ArrayList<SlidingWindowStatsSummary> current) { if (previous == current) { return false; } if (previous == null || current == null) { return true; } if (previous.size() != current.size()) { return true; } for (int i = 0; i < previous.size(); ++i) { if (displayChanged(previous.get(i), current.get(i))) { return true; } } return false; } private boolean displayChanged(SlidingWindowStatsSummary previous, SlidingWindowStatsSummary current) { // We only care about updating if the value for the current metric being displayed has changed. if (!previous.getLocation().equals(current.getLocation())) { return true; } for (PerfMetric metric : getMetrics()) { if (previous.getValue(metric) != current.getValue(metric)) { return true; } } return false; } @Nullable @Override public Object getData(@NotNull String dataId) { return InspectorTree.INSPECTOR_KEY.is(dataId) ? getTree() : null; } private static class WidgetNameRenderer extends SimpleColoredRenderer implements TableCellRenderer { private boolean idle = false; @Override public final Component getTableCellRendererComponent(JTable table, @Nullable Object value, boolean isSelected, boolean hasFocus, int row, int col) { final JPanel panel = new JPanel(); if (value == null) return panel; panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS)); if (value instanceof SlidingWindowStatsSummary) { final SlidingWindowStatsSummary stats = (SlidingWindowStatsSummary)value; final SimpleTextAttributes attributes = SimpleTextAttributes.REGULAR_ATTRIBUTES; final JBLabel label = new JBLabel(stats.getLocation().name); if (isSelected) { label.setForeground(table.getSelectionForeground()); } final int count = stats.getValue(PerfMetric.lastFrame); label.setIcon(getIconForCount(idle ? 0 : count, true)); panel.add(Box.createHorizontalStrut(16)); panel.add(label); } clear(); setPaintFocusBorder(hasFocus && table.getCellSelectionEnabled()); acquireState(table, isSelected, hasFocus, row, col); getCellState().updateRenderer(this); if (isSelected) { panel.setBackground(table.getSelectionBackground()); } return panel; } public void setIdle(boolean idle) { this.idle = idle; } } private static class WidgetLocationRenderer extends SimpleColoredRenderer implements TableCellRenderer { @Override public final Component getTableCellRendererComponent(JTable table, @Nullable Object value, boolean isSelected, boolean hasFocus, int row, int col) { final JPanel panel = new JPanel(); if (value == null) return panel; panel.setLayout(new BorderLayout()); if (value instanceof SlidingWindowStatsSummary) { final SlidingWindowStatsSummary stats = (SlidingWindowStatsSummary)value; final SimpleTextAttributes attributes = SimpleTextAttributes.REGULAR_ATTRIBUTES; final Location location = stats.getLocation(); final String path = location.path; final String filename = PathUtil.getFileName(path); append(filename, attributes); final JBLabel label = new JBLabel(filename); label.setHorizontalAlignment(SwingConstants.RIGHT); panel.add(Box.createHorizontalGlue()); panel.add(label, BorderLayout.CENTER); final JBLabel lineLabel = new JBLabel(":" + location.line); panel.add(lineLabel, BorderLayout.EAST); if (isSelected) { label.setForeground(table.getSelectionForeground()); lineLabel.setForeground(table.getSelectionForeground()); } } clear(); setPaintFocusBorder(hasFocus && table.getCellSelectionEnabled()); acquireState(table, isSelected, hasFocus, row, col); getCellState().updateRenderer(this); if (isSelected) { panel.setBackground(table.getSelectionBackground()); } return panel; } } private static class CountRenderer extends SimpleColoredRenderer implements TableCellRenderer { private final PerfMetric metric; CountRenderer(PerfMetric metric) { this.metric = metric; } @Override public final Component getTableCellRendererComponent(JTable table, @Nullable Object value, boolean isSelected, boolean hasFocus, int row, int col) { final JPanel panel = new JPanel(); if (value == null) return panel; panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS)); if (value instanceof SlidingWindowStatsSummary) { final SlidingWindowStatsSummary stats = (SlidingWindowStatsSummary)value; final SimpleTextAttributes attributes = SimpleTextAttributes.REGULAR_ATTRIBUTES; final int count = stats.getValue(metric); final JBLabel label = new JBLabel(Integer.toString(count)); panel.add(Box.createHorizontalGlue()); panel.add(label); panel.add(Box.createHorizontalStrut(8)); if (isSelected) { label.setForeground(table.getSelectionForeground()); } } clear(); setPaintFocusBorder(hasFocus && table.getCellSelectionEnabled()); acquireState(table, isSelected, hasFocus, row, col); getCellState().updateRenderer(this); if (isSelected) { panel.setBackground(table.getSelectionBackground()); } return panel; } } static class WidgetNameColumnInfo extends ColumnInfo<DefaultMutableTreeNode, SlidingWindowStatsSummary> { private final WidgetNameRenderer renderer = new WidgetNameRenderer(); public WidgetNameColumnInfo(String name) { super(name); } @Nullable @Override public SlidingWindowStatsSummary valueOf(DefaultMutableTreeNode node) { return (SlidingWindowStatsSummary)node.getUserObject(); } @Override public TableCellRenderer getRenderer(DefaultMutableTreeNode item) { return renderer; } @Override public String getTooltipText() { return "The widget that was rebuilt."; } public void setIdle(boolean idle) { renderer.setIdle(idle); } } static class LocationColumnInfo extends ColumnInfo<DefaultMutableTreeNode, SlidingWindowStatsSummary> { private final TableCellRenderer renderer = new WidgetLocationRenderer(); public LocationColumnInfo(String name) { super(name); } @Nullable @Override public SlidingWindowStatsSummary valueOf(DefaultMutableTreeNode node) { return (SlidingWindowStatsSummary)node.getUserObject(); } @Override public TableCellRenderer getRenderer(DefaultMutableTreeNode item) { return renderer; } @Override public String getTooltipText() { return "Click to locate the widget's constructor in the code."; } } static class CountColumnInfo extends ColumnInfo<DefaultMutableTreeNode, SlidingWindowStatsSummary> { private final CountRenderer defaultRenderer; private final PerfMetric metric; public CountColumnInfo(PerfMetric metric) { super(metric.name); this.metric = metric; defaultRenderer = new CountRenderer(metric); } @Nullable @Override public SlidingWindowStatsSummary valueOf(DefaultMutableTreeNode node) { return (SlidingWindowStatsSummary)node.getUserObject(); } @Override public TableCellRenderer getRenderer(DefaultMutableTreeNode item) { return defaultRenderer; } @Override public String getTooltipText() { switch (metric) { case lastFrame: return "The number of times the widget was rebuilt in the last frame."; case totalSinceEnteringCurrentScreen: return "The number of times the widget was rebuilt since entering the current screen."; default: return null; } } } }
flutter-intellij/flutter-idea/src/io/flutter/performance/WidgetPerfTable.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/performance/WidgetPerfTable.java", "repo_id": "flutter-intellij", "token_count": 7549 }
517
/* * Copyright 2017 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. */ package io.flutter.pub; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; /** * Queries returning a list of {@link PubRoot} directories. */ public class PubRoots { // Not instantiable. private PubRoots() { } /** * Returns a PubRoot for each of the module's content roots that contains a pubspec.yaml file. * <p> * (Based on the filesystem cache; doesn't refresh anything.) */ @NotNull public static List<PubRoot> forModule(@NotNull Module module) { final List<PubRoot> result = new ArrayList<>(); if (module.isDisposed()) return result; for (VirtualFile dir : ModuleRootManager.getInstance(module).getContentRoots()) { final PubRoot root = PubRoot.forDirectory(dir); if (root != null) { result.add(root); } } return result; } /** * Returns a PubRoot for each of the project's content roots that contains a pubspec.yaml file. * <p> * (Based on the filesystem cache; doesn't refresh anything.) */ @NotNull public static List<PubRoot> forProject(@NotNull Project project) { final List<PubRoot> result = new ArrayList<>(); if (project.isDisposed()) return result; for (Module module : ModuleManager.getInstance(project).getModules()) { result.addAll(forModule(module)); } return result; } }
flutter-intellij/flutter-idea/src/io/flutter/pub/PubRoots.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/pub/PubRoots.java", "repo_id": "flutter-intellij", "token_count": 587 }
518
/* * Copyright 2017 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. */ package io.flutter.run; import com.intellij.execution.*; import com.intellij.execution.configurations.CommandLineState; import com.intellij.execution.configurations.GeneralCommandLine; import com.intellij.execution.configurations.RunProfile; import com.intellij.execution.configurations.RunProfileState; import com.intellij.execution.executors.DefaultDebugExecutor; import com.intellij.execution.executors.DefaultRunExecutor; import com.intellij.execution.process.ColoredProcessHandler; import com.intellij.execution.process.ProcessHandler; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.execution.runners.GenericProgramRunner; import com.intellij.execution.runners.ProgramRunner; import com.intellij.execution.runners.RunContentBuilder; import com.intellij.execution.ui.ConsoleView; import com.intellij.execution.ui.ConsoleViewContentType; import com.intellij.execution.ui.RunContentDescriptor; import com.intellij.icons.AllIcons; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.Separator; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.xdebugger.XDebugProcess; import com.intellij.xdebugger.XDebugProcessStarter; import com.intellij.xdebugger.XDebugSession; import com.intellij.xdebugger.XDebuggerManager; import com.jetbrains.lang.dart.ide.runner.DartExecutionHelper; import com.jetbrains.lang.dart.util.DartUrlResolver; import io.flutter.FlutterConstants; import io.flutter.FlutterUtils; import io.flutter.dart.DartPlugin; import io.flutter.run.bazel.BazelRunConfig; import io.flutter.run.common.RunMode; import io.flutter.run.daemon.DaemonConsoleView; import io.flutter.run.daemon.DeviceService; import io.flutter.run.daemon.FlutterApp; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Launches a flutter app, showing it in the console. * <p> * Normally creates a debugging session, which is needed for hot reload. */ public class LaunchState extends CommandLineState { // We use the profile launch type, contributed by the Android IntelliJ plugins // in 2017.3 and Android Studio 3.0, if it's available. This allows us to support // their 'profile' launch button, next to the regular run and debug ones. public static final String ANDROID_PROFILER_EXECUTOR_ID = "Android Profiler"; private final @NotNull VirtualFile workDir; /** * The file or directory holding the Flutter app's source code. * This determines how the analysis server resolves URI's (for breakpoints, etc). * <p> * If a file, this should be the file containing the main() method. */ private final @NotNull VirtualFile sourceLocation; private final @NotNull RunConfig runConfig; private final @NotNull CreateAppCallback myCreateAppCallback; public LaunchState(@NotNull ExecutionEnvironment env, @NotNull VirtualFile workDir, @NotNull VirtualFile sourceLocation, @NotNull RunConfig runConfig, @NotNull CreateAppCallback createAppCallback) { super(env); this.workDir = workDir; this.sourceLocation = sourceLocation; this.runConfig = runConfig; this.myCreateAppCallback = createAppCallback; DaemonConsoleView.install(this, env, workDir); } @NotNull protected CreateAppCallback getCreateAppCallback() { return myCreateAppCallback; } protected RunContentDescriptor launch(@NotNull ExecutionEnvironment env) throws ExecutionException { FileDocumentManager.getInstance().saveAllDocuments(); // Set our FlutterLaunchMode up in the ExecutionEnvironment. if (RunMode.fromEnv(env).isProfiling()) { FlutterLaunchMode.addToEnvironment(env, FlutterLaunchMode.PROFILE); } final Project project = getEnvironment().getProject(); @Nullable final FlutterDevice device = DeviceService.getInstance(project).getSelectedDevice(); if (device == null) { showNoDeviceConnectedMessage(project); return null; } final FlutterApp app = myCreateAppCallback.createApp(device); // Cache for use in console configuration. FlutterApp.addToEnvironment(env, app); // Remember the run configuration that started this process. app.getProcessHandler().putUserData(FLUTTER_RUN_CONFIG_KEY, runConfig); final ExecutionResult result = setUpConsoleAndActions(app); // For Bazel run configurations, where the console is not null, and we find the expected // process handler type, print the command line command to the console. if (runConfig instanceof BazelRunConfig && app.getConsole() != null && app.getProcessHandler() instanceof ColoredProcessHandler) { final String commandLineString = ((ColoredProcessHandler)app.getProcessHandler()).getCommandLine().trim(); if (StringUtil.isNotEmpty(commandLineString)) { app.getConsole().print(commandLineString + "\n", ConsoleViewContentType.NORMAL_OUTPUT); } } device.bringToFront(); // Check for and display any analysis errors when we launch an app. if (env.getRunProfile() instanceof SdkRunConfig) { final Class dartExecutionHelper = classForName("com.jetbrains.lang.dart.ide.runner.DartExecutionHelper"); if (dartExecutionHelper != null) { final String message = ("<a href='open.dart.analysis'>Analysis issues</a> may affect " + "the execution of '" + env.getRunProfile().getName() + "'."); final SdkRunConfig config = (SdkRunConfig)env.getRunProfile(); final SdkFields sdkFields = config.getFields(); final MainFile mainFile = MainFile.verify(sdkFields.getFilePath(), env.getProject()).get(); DartExecutionHelper.displayIssues(project, mainFile.getFile(), message, env.getRunProfile().getIcon()); } } final FlutterLaunchMode launchMode = FlutterLaunchMode.fromEnv(env); final RunContentDescriptor descriptor; if (launchMode.supportsDebugConnection()) { descriptor = createDebugSession(env, app, result).getRunContentDescriptor(); } else { descriptor = new RunContentBuilder(result, env).showRunContent(env.getContentToReuse()); } try { final Field f = descriptor.getClass().getDeclaredField("myDisplayName"); f.setAccessible(true); f.set(descriptor, descriptor.getDisplayName() + " (" + device.deviceName() + ")"); } catch (IllegalAccessException | NoSuchFieldException e) { LOG.info(e); } return descriptor; } private static Class classForName(String className) { try { return Class.forName(className); } catch (ClassNotFoundException e) { return null; } } protected void showNoDeviceConnectedMessage(Project project) { Messages.showDialog( project, "No connected devices found; please connect a device, or see flutter.dev/setup for getting started instructions.", "No Connected Devices Found", new String[]{Messages.OK_BUTTON}, 0, AllIcons.General.InformationDialog); } @NotNull protected XDebugSession createDebugSession(@NotNull final ExecutionEnvironment env, @NotNull final FlutterApp app, @NotNull final ExecutionResult executionResult) throws ExecutionException { final DartUrlResolver resolver = DartUrlResolver.getInstance(env.getProject(), sourceLocation); final FlutterPositionMapper mapper = createPositionMapper(env, app, resolver); final XDebuggerManager manager = XDebuggerManager.getInstance(env.getProject()); final XDebugSession session = manager.startSession(env, new XDebugProcessStarter() { @Override @NotNull public XDebugProcess start(@NotNull final XDebugSession session) { return new FlutterDebugProcess(app, env, session, executionResult, resolver, mapper); } }); if (app.getMode() != RunMode.DEBUG) { session.setBreakpointMuted(true); } return session; } @NotNull private FlutterPositionMapper createPositionMapper(@NotNull ExecutionEnvironment env, @NotNull FlutterApp app, @NotNull DartUrlResolver resolver) { final FlutterPositionMapper.Analyzer analyzer; if (app.getMode() == RunMode.DEBUG) { analyzer = FlutterPositionMapper.Analyzer.create(env.getProject(), sourceLocation); } else { analyzer = null; // Don't need analysis server just to run. } // Choose source root containing the Dart application. // TODO(skybrian) for bazel, we probably should pass in three source roots here (for bazel-bin, bazel-genfiles, etc). final VirtualFile pubspec = resolver.getPubspecYamlFile(); final VirtualFile sourceRoot = pubspec != null ? pubspec.getParent() : workDir; return new FlutterPositionMapper(env.getProject(), sourceRoot, resolver, analyzer); } @NotNull protected ExecutionResult setUpConsoleAndActions(@NotNull FlutterApp app) throws ExecutionException { final ConsoleView console = createConsole(getEnvironment().getExecutor()); if (console != null) { app.setConsole(console); console.attachToProcess(app.getProcessHandler()); } // Add observatory actions. // These actions are effectively added only to the Run tool window. // For Debug see FlutterDebugProcess.registerAdditionalActions() final Computable<Boolean> observatoryAvailable = () -> !app.getProcessHandler().isProcessTerminated() && app.getConnector().getBrowserUrl() != null; final List<AnAction> actions = new ArrayList<>(Arrays.asList( super.createActions(console, app.getProcessHandler(), getEnvironment().getExecutor()))); actions.add(new Separator()); actions.add(new OpenDevToolsAction(app, observatoryAvailable)); return new DefaultExecutionResult(console, app.getProcessHandler(), actions.toArray(new AnAction[0])); } @Override public @NotNull ExecutionResult execute(@NotNull Executor executor, @NotNull ProgramRunner runner) throws ExecutionException { throw new ExecutionException("not implemented"); // Not used; launch() does this. } @Override protected @NotNull ProcessHandler startProcess() throws ExecutionException { // This can happen if there isn't a custom runner defined in plugin.xml. // The runner should extend LaunchState.Runner (below). throw new ExecutionException("need to implement LaunchState.Runner for " + runConfig.getClass()); } /** * Starts the process and wraps it in a FlutterApp. * <p> * The callback knows the appropriate command line arguments (bazel versus non-bazel). */ public interface CreateAppCallback { FlutterApp createApp(@Nullable FlutterDevice device) throws ExecutionException; } /** * A run configuration that works with Launcher. */ public interface RunConfig extends RunProfile { Project getProject(); @Override @NotNull LaunchState getState(@NotNull Executor executor, @NotNull ExecutionEnvironment environment) throws ExecutionException; @NotNull GeneralCommandLine getCommand(ExecutionEnvironment environment, @NotNull FlutterDevice device) throws ExecutionException; } /** * A runner that automatically invokes {@link #launch}. */ public static abstract class Runner<C extends RunConfig> extends GenericProgramRunner { private final Class<C> runConfigClass; public Runner(Class<C> runConfigClass) { this.runConfigClass = runConfigClass; } @SuppressWarnings("SimplifiableIfStatement") @Override public boolean canRun(final @NotNull String executorId, final @NotNull RunProfile profile) { if (!DefaultRunExecutor.EXECUTOR_ID.equals(executorId) && !DefaultDebugExecutor.EXECUTOR_ID.equals(executorId) && !ANDROID_PROFILER_EXECUTOR_ID.equals(executorId)) { return false; } if (!(profile instanceof RunConfig)) { return false; } // If the app is running and the launch mode is the same, then we can run. final RunConfig config = (RunConfig)profile; final ProcessHandler process = getRunningAppProcess(config); if (process != null) { final FlutterApp app = FlutterApp.fromProcess(process); if (app == null) { return false; } final String selectedDeviceId = getSelectedDeviceId(config.getProject()); // Only continue checks for this app if the launched device is the same as the selected one. if (StringUtil.equals(app.deviceId(), selectedDeviceId)) { // Disable if no app or this isn't the mode that app was launched in. if (!executorId.equals(app.getMode().mode())) { return false; } // Disable the run/debug buttons if the app is starting up. if (app.getState() == FlutterApp.State.STARTING || app.getState() == FlutterApp.State.RELOADING || app.getState() == FlutterApp.State.RESTARTING) { return false; } } } if (DartPlugin.getDartSdk(config.getProject()) == null) { return false; } return runConfigClass.isInstance(profile) && canRun(runConfigClass.cast(profile)); } /** * Subclass hook for additional checks. */ protected boolean canRun(C config) { return true; } @Override protected RunContentDescriptor doExecute(@NotNull RunProfileState state, @NotNull ExecutionEnvironment env) throws ExecutionException { if (!(state instanceof LaunchState)) { LOG.error("unexpected RunProfileState: " + state.getClass()); return null; } final LaunchState launchState = (LaunchState)state; final String executorId = env.getExecutor().getId(); // See if we should issue a hot-reload. final List<RunContentDescriptor> runningProcesses = ExecutionManager.getInstance(env.getProject()).getContentManager().getAllDescriptors(); final ProcessHandler process = getRunningAppProcess(launchState.runConfig); if (process != null) { final FlutterApp app = FlutterApp.fromProcess(process); final String selectedDeviceId = getSelectedDeviceId(env.getProject()); if (app != null) { final boolean sameDevice = StringUtil.equals(app.deviceId(), selectedDeviceId); if (sameDevice) { if (executorId.equals(app.getMode().mode())) { if (!identicalCommands(app.getCommand(), launchState.runConfig.getCommand(env, app.device()))) { // To be safe, relaunch as the arguments to launch have changed. try { // TODO(jacobr): ideally we shouldn't be synchronously waiting for futures like this // but I don't see a better option. In practice this seems fine. app.shutdownAsync().get(); } catch (InterruptedException | java.util.concurrent.ExecutionException e) { FlutterUtils.warn(LOG, e); } return launchState.launch(env); } final FlutterLaunchMode launchMode = FlutterLaunchMode.fromEnv(env); if (launchMode.supportsReload() && app.isStarted()) { // Map a re-run action to a flutter hot restart. final FlutterReloadManager reloadManager = FlutterReloadManager.getInstance(env.getProject()); reloadManager.saveAllAndRestart(app, FlutterConstants.RELOAD_REASON_MANUAL); } } return null; } } } // Else, launch the app. return launchState.launch(env); } private static boolean identicalCommands(GeneralCommandLine a, GeneralCommandLine b) { return a.getParametersList().getList().equals(b.getParametersList().getList()); } @Nullable private String getSelectedDeviceId(@NotNull Project project) { final FlutterDevice selectedDevice = DeviceService.getInstance(project).getSelectedDevice(); return selectedDevice == null ? null : selectedDevice.deviceId(); } } /** * Returns the currently running app for the given RunConfig, if any. */ @Nullable public static ProcessHandler getRunningAppProcess(RunConfig config) { final Project project = config.getProject(); final List<RunContentDescriptor> runningProcesses = ExecutionManager.getInstance(project).getContentManager().getAllDescriptors(); for (RunContentDescriptor descriptor : runningProcesses) { final ProcessHandler process = descriptor.getProcessHandler(); if (process != null && !process.isProcessTerminated() && process.getUserData(FLUTTER_RUN_CONFIG_KEY) == config) { return process; } } return null; } private static final Key<RunConfig> FLUTTER_RUN_CONFIG_KEY = new Key<>("FLUTTER_RUN_CONFIG_KEY"); private static final Logger LOG = Logger.getInstance(LaunchState.class); }
flutter-intellij/flutter-idea/src/io/flutter/run/LaunchState.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/run/LaunchState.java", "repo_id": "flutter-intellij", "token_count": 6254 }
519
/* * 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. */ package io.flutter.run.bazelTest; import com.google.common.annotations.VisibleForTesting; import com.intellij.execution.actions.ConfigurationContext; import com.intellij.execution.actions.ConfigurationFromContext; import com.intellij.execution.actions.RunConfigurationProducer; import com.intellij.execution.configurations.ConfigurationFactory; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiElement; import com.jetbrains.lang.dart.psi.DartFile; import io.flutter.FlutterUtils; import io.flutter.bazel.Workspace; import io.flutter.bazel.WorkspaceCache; import io.flutter.dart.DartPlugin; import io.flutter.run.FlutterRunConfigurationProducer; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * Determines when we can run a Flutter test using "bazel test". */ public class BazelTestConfigProducer extends RunConfigurationProducer<BazelTestConfig> { private final BazelTestConfigUtils bazelTestConfigUtils; protected BazelTestConfigProducer() { this(FlutterBazelTestConfigurationType.getInstance().factory); } protected BazelTestConfigProducer(@NotNull ConfigurationFactory factory) { super(factory); bazelTestConfigUtils = BazelTestConfigUtils.getInstance(); } @VisibleForTesting BazelTestConfigProducer(BazelTestConfigUtils bazelTestConfigUtils) { super(FlutterBazelTestConfigurationType.getInstance()); this.bazelTestConfigUtils = bazelTestConfigUtils; } private boolean isBazelFlutterContext(@NotNull ConfigurationContext context) { final PsiElement location = context.getPsiLocation(); return location != null && getWorkspace(context.getProject()) != null; } @VisibleForTesting @Nullable protected Workspace getWorkspace(@NotNull Project project) { return WorkspaceCache.getInstance(project).get(); } /** * If the current file looks like a Flutter test, initializes the run config to run it. * <p> * Returns true if successfully set up. */ @Override protected boolean setupConfigurationFromContext(@NotNull BazelTestConfig config, @NotNull ConfigurationContext context, @NotNull Ref<PsiElement> sourceElement) { if (!isBazelFlutterContext(context)) return false; final PsiElement elt = context.getPsiLocation(); final DartFile file = FlutterUtils.getDartFile(elt); if (file == null) { return false; } final String testName = bazelTestConfigUtils.findTestName(elt); if (testName != null) { return setupForSingleTest(config, context, file, testName); } return setupForDartFile(config, context, file); } private boolean setupForSingleTest( @NotNull BazelTestConfig config, @NotNull ConfigurationContext context, @NotNull DartFile file, @NotNull String testName) { final VirtualFile testFile = verifyFlutterTestFile(config, context, file); if (testFile == null) return false; config.setFields(BazelTestFields.forTestName(testName, testFile.getPath(), config.getFields().getAdditionalArgs())); config.setGeneratedName(); config.setName("Run '" + testName + "' in '" + file.getName() + "'"); return true; } private boolean setupForDartFile(@NotNull BazelTestConfig config, @NotNull ConfigurationContext context, @NotNull DartFile file) { final VirtualFile testFile = verifyFlutterTestFile(config, context, file); if (testFile == null) return false; config.setFields(BazelTestFields.forFile(testFile.getPath(), config.getFields().getAdditionalArgs())); config.setName("Run '" + file.getName() + "'"); return true; } @Nullable @VisibleForTesting VirtualFile verifyFlutterTestFile(@NotNull BazelTestConfig config, @NotNull ConfigurationContext context, @NotNull DartFile file) { final VirtualFile candidate = FlutterRunConfigurationProducer.getFlutterEntryFile(context, false, false); if (candidate == null) return null; return file.getVirtualFile().getPath().contains("/test/") ? candidate : null; } /** * Called on existing run configurations to check if one has already been created for the given {@param context}. * * @return true if a run config was already created for this context. If so we will reuse it. */ @Override public boolean isConfigurationFromContext(@NotNull BazelTestConfig config, @NotNull ConfigurationContext context) { // Check if the config is a non-watch producer and the producer is a watch producer or vice versa, then the given configuration // is not a replacement for one by this producer. if (!StringUtil.equals(getId(config), getConfigurationFactory().getId())) return false; final VirtualFile file = config.getFields().getFile(); if (file == null) return false; final PsiElement target = context.getPsiLocation(); if (target instanceof PsiDirectory) { return ((PsiDirectory)target).getVirtualFile().equals(file); } if (!FlutterRunConfigurationProducer.hasDartFile(context, file.getPath())) return false; final String testName = bazelTestConfigUtils.findTestName(context.getPsiLocation()); if (config.getFields().getTestName() != null) { return testName != null && testName.equals(config.getFields().getTestName()); } return testName == null; } @Override public boolean shouldReplace(@NotNull ConfigurationFromContext self, @NotNull ConfigurationFromContext other) { return DartPlugin.isDartTestConfiguration(other.getConfigurationType()); } @NotNull private String getId(BazelTestConfig config) { return config.getFields().isWatchConfig() ? "Watch" : "No Watch"; } }
flutter-intellij/flutter-idea/src/io/flutter/run/bazelTest/BazelTestConfigProducer.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/run/bazelTest/BazelTestConfigProducer.java", "repo_id": "flutter-intellij", "token_count": 2006 }
520
/* * Copyright 2021 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ package io.flutter.run.coverage; import com.intellij.coverage.CoverageDataManager; import com.intellij.coverage.CoverageSuitesBundle; import com.intellij.coverage.SimpleCoverageAnnotator; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.vfs.VirtualFile; import io.flutter.utils.FlutterModuleUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class FlutterCoverageAnnotator extends SimpleCoverageAnnotator { @Nullable public static FlutterCoverageAnnotator getInstance(Project project) { return project.getService(FlutterCoverageAnnotator.class); } public FlutterCoverageAnnotator(Project project) { super(project); } @Override protected FileCoverageInfo fillInfoForUncoveredFile(@NotNull File file) { return new FileCoverageInfo(); } @Override protected boolean shouldCollectCoverageInsideLibraryDirs() { return false; } @Override protected VirtualFile[] getRoots(Project project, @NotNull CoverageDataManager dataManager, CoverageSuitesBundle suite) { return dataManager.doInReadActionIfProjectOpen(() -> { final List<VirtualFile> roots = new ArrayList<>(); for (Module module : FlutterModuleUtils.findModulesWithFlutterContents(project)) { final ModuleRootManager rootManager = ModuleRootManager.getInstance(module); roots.addAll(Arrays.asList(rootManager.getContentRoots())); } return roots.toArray(VirtualFile.EMPTY_ARRAY); }); } }
flutter-intellij/flutter-idea/src/io/flutter/run/coverage/FlutterCoverageAnnotator.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/run/coverage/FlutterCoverageAnnotator.java", "repo_id": "flutter-intellij", "token_count": 671 }
521
/* * 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. */ package io.flutter.run.test; import com.google.common.annotations.VisibleForTesting; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.intellij.execution.Location; import com.intellij.execution.PsiLocation; import com.intellij.execution.testframework.sm.runner.SMTestLocator; import com.intellij.openapi.editor.Document; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiManager; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.PsiElementProcessor; import com.intellij.psi.util.PsiTreeUtil; import com.jetbrains.lang.dart.ide.runner.util.TestUtil; import com.jetbrains.lang.dart.psi.*; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collections; import java.util.List; @SuppressWarnings("Duplicates") public class DartTestLocationProviderZ implements SMTestLocator, DumbAware { @SuppressWarnings("rawtypes") private static final List<Location> NONE = Collections.emptyList(); private static final Gson GSON = new Gson(); public static final DartTestLocationProviderZ INSTANCE = new DartTestLocationProviderZ(); public static final Type STRING_LIST_TYPE = new TypeToken<List<String>>() { }.getType(); @NotNull @Override @SuppressWarnings("rawtypes") public List<Location> getLocation(@NotNull String protocol, @NotNull String path, @NotNull Project project, @NotNull GlobalSearchScope scope) { // see DartTestEventsConverterZ.addLocationHint() // path is like /Users/x/projects/foo/test/foo_test.dart,35,12,["main tests","calculate_fail"] final int commaIdx1 = path.indexOf(','); final int commaIdx2 = path.indexOf(',', commaIdx1 + 1); final int commaIdx3 = path.indexOf(',', commaIdx2 + 1); if (commaIdx3 < 0) return NONE; final String filePath = path.substring(0, commaIdx1); final int line = Integer.parseInt(path.substring(commaIdx1 + 1, commaIdx2)); final int column = Integer.parseInt(path.substring(commaIdx2 + 1, commaIdx3)); final String names = path.substring(commaIdx3 + 1); final VirtualFile file = LocalFileSystem.getInstance().findFileByPath(filePath); final PsiFile psiFile = file == null ? null : PsiManager.getInstance(project).findFile(file); if (!(psiFile instanceof DartFile)) return NONE; if (line >= 0 && column >= 0) { final Location<PsiElement> location = getLocationByLineAndColumn(psiFile, line, column); if (location != null) { return Collections.singletonList(location); } } final List<String> nodes = pathToNodes(names); if (nodes.isEmpty()) { return Collections.singletonList(new PsiLocation<PsiElement>(psiFile)); } return getLocationByGroupAndTestNames(psiFile, nodes); } @Nullable protected Location<PsiElement> getLocationByLineAndColumn(@NotNull final PsiFile file, final int line, final int column) { final Document document = PsiDocumentManager.getInstance(file.getProject()).getDocument(file); if (document == null) return null; if (line >= document.getLineCount()) return null; final int offset = document.getLineStartOffset(line) + column; final PsiElement element = file.findElementAt(offset); final PsiElement parent1 = element == null ? null : element.getParent(); final PsiElement parent2 = parent1 instanceof DartId ? parent1.getParent() : null; final PsiElement parent3 = parent2 instanceof DartReferenceExpression ? parent2.getParent() : null; if (parent3 instanceof DartCallExpression) { if (TestUtil.isTest((DartCallExpression)parent3) || TestUtil.isGroup((DartCallExpression)parent3)) { return new PsiLocation<>(parent3); } } return null; } private static List<String> pathToNodes(final String element) { return GSON.fromJson(element, STRING_LIST_TYPE); } @VisibleForTesting @SuppressWarnings("rawtypes") public List<Location> getLocationForTest(@NotNull final PsiFile psiFile, @NotNull final String testPath) { return getLocationByGroupAndTestNames(psiFile, pathToNodes(testPath)); } @SuppressWarnings("rawtypes") protected List<Location> getLocationByGroupAndTestNames(final PsiFile psiFile, final List<String> nodes) { final List<Location> locations = new ArrayList<>(); if (psiFile instanceof DartFile && !nodes.isEmpty()) { final PsiElementProcessor<PsiElement> collector = new PsiElementProcessor<PsiElement>() { @Override public boolean execute(@NotNull final PsiElement element) { if (element instanceof DartCallExpression) { DartCallExpression expression = (DartCallExpression)element; if (isTest(expression) || TestUtil.isGroup(expression)) { if (nodes.get(nodes.size() - 1).equals(getTestLabel(expression))) { boolean matches = true; for (int i = nodes.size() - 2; i >= 0 && matches; --i) { expression = getGroup(expression); if (expression == null || !nodes.get(i).equals(getTestLabel(expression))) { matches = false; } } if (matches) { locations.add(new PsiLocation<>(element)); return false; } } } } return true; } @Nullable private DartCallExpression getGroup(final DartCallExpression expression) { return (DartCallExpression)PsiTreeUtil.findFirstParent(expression, true, element -> element instanceof DartCallExpression && TestUtil.isGroup((DartCallExpression)element)); } }; PsiTreeUtil.processElements(psiFile, collector); } return locations; } protected boolean isTest(@NotNull DartCallExpression expression) { return TestUtil.isTest(expression); } @Nullable public static String getTestLabel(@NotNull final DartCallExpression testCallExpression) { final DartArguments arguments = testCallExpression.getArguments(); final DartArgumentList argumentList = arguments == null ? null : arguments.getArgumentList(); final List<DartExpression> argExpressions = argumentList == null ? null : argumentList.getExpressionList(); return argExpressions != null && !argExpressions.isEmpty() && argExpressions.get(0) instanceof DartStringLiteralExpression ? StringUtil.unquoteString(argExpressions.get(0).getText()) : null; } }
flutter-intellij/flutter-idea/src/io/flutter/run/test/DartTestLocationProviderZ.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/run/test/DartTestLocationProviderZ.java", "repo_id": "flutter-intellij", "token_count": 2796 }
522
/* * 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. */ package io.flutter.samples; import org.jetbrains.annotations.NotNull; public class FlutterSample { @NotNull private final String libraryName; @NotNull private final String className; FlutterSample(@NotNull String libraryName, @NotNull String className) { this.libraryName = libraryName; this.className = className; } @NotNull public String getLibraryName() { return libraryName; } @NotNull public String getClassName() { return className; } @NotNull public String getDisplayName() { return libraryName + "." + className; } @NotNull public String getHostedDocsUrl() { // https://api.flutter.dev/flutter/material/AppBar-class.html return "https://api.flutter.dev/flutter/" + libraryName + "/" + className + "-class.html"; } @Override public String toString() { return getLibraryName() + "." + getClassName(); } }
flutter-intellij/flutter-idea/src/io/flutter/samples/FlutterSample.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/samples/FlutterSample.java", "repo_id": "flutter-intellij", "token_count": 345 }
523
/* * Copyright 2016 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. */ package io.flutter.sdk; import com.google.common.annotations.VisibleForTesting; import com.intellij.openapi.util.Version; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.nio.charset.StandardCharsets; public class FlutterSdkVersion implements Comparable<FlutterSdkVersion> { /** * The version for which the distributed icons can be used. */ @VisibleForTesting public static final FlutterSdkVersion DISTRIBUTED_ICONS = new FlutterSdkVersion("3.1.0"); /** * The minimum version we suggest people use. */ private static final FlutterSdkVersion MIN_SUPPORTED_SDK = new FlutterSdkVersion("0.0.12"); /** * The minimum version we suggest people use to enable track-widget-creation. * <p> * Before this version there were issues if you ran the app from the command * line without the flag after running */ private static final FlutterSdkVersion MIN_SAFE_TRACK_WIDGET_CREATION_SDK = new FlutterSdkVersion("0.10.2"); /** * The version that supports --dart-define in the run command. */ private static final FlutterSdkVersion MIN_DART_DEFINE_SDK = new FlutterSdkVersion("1.12.0"); /** * The version of the stable channel that supports --androidx in the create command. */ private static final FlutterSdkVersion MIN_PUB_OUTDATED_SDK = new FlutterSdkVersion("1.16.4"); /** * The version that supports --platform in flutter create. */ private static final FlutterSdkVersion MIN_CREATE_PLATFORMS_SDK = new FlutterSdkVersion("1.20.0"); /** * The version that supports --config-only when configuring Xcode for opening a project. */ private static final FlutterSdkVersion MIN_XCODE_CONFIG_ONLY = new FlutterSdkVersion("1.22.0-12.0.pre"); /** * The last version of stable that does not support --platform in flutter create. */ private static final FlutterSdkVersion MAX_STABLE_NO_PLATFORMS_SDK = new FlutterSdkVersion("1.22.6"); /** * The version that supports --devtools-server-address in flutter run. */ @NotNull private static final FlutterSdkVersion MIN_PASS_DEVTOOLS_SDK = new FlutterSdkVersion("1.26.0-11.0.pre"); @NotNull private static final FlutterSdkVersion MIN_OPTIONAL_PASS_DEVTOOLS_SDK = new FlutterSdkVersion("2.7.0-3.0.pre"); /** * Past this version we want to use the daemon to start DevTools. */ @NotNull private static final FlutterSdkVersion MIN_USE_DAEMON_FOR_DEVTOOLS = new FlutterSdkVersion("1.26.0-11.0.pre"); /** * The version that includes the skeleton template. */ private static final FlutterSdkVersion MIN_SKELETON_TEMPLATE = new FlutterSdkVersion("2.5.0"); /** * The version that includes the skeleton template. */ private static final FlutterSdkVersion MIN_PLUGIN_FFI_TEMPLATE = new FlutterSdkVersion("3.0.0"); /** * The version that includes the skeleton template. */ private static final FlutterSdkVersion MIN_EMPTY_PROJECT = new FlutterSdkVersion("3.6.0-0.1.pre"); /** * The version that implements URI mapping for web. */ @NotNull private static final FlutterSdkVersion MIN_URI_MAPPING_FOR_WEB = new FlutterSdkVersion("2.13.0-0.1.pre"); @NotNull private static final FlutterSdkVersion MIN_STABLE_WEB_PLATFORM = new FlutterSdkVersion("2.0.0"); @NotNull private static final FlutterSdkVersion MIN_STABLE_WINDOWS_PLATFORM = new FlutterSdkVersion("2.10.0"); @NotNull private static final FlutterSdkVersion MIN_STABLE_LINUX_PLATFORM = new FlutterSdkVersion("3.0.0"); @NotNull private static final FlutterSdkVersion MIN_STABLE_MACOS_PLATFORM = new FlutterSdkVersion("3.0.0"); @NotNull private static final FlutterSdkVersion MIN_SUPPORTS_DEVTOOLS_PATH_URLS = new FlutterSdkVersion("3.3.0"); @Nullable private final Version version; @Nullable private final String versionText; @Nullable private final Version betaVersion; private final int masterVersion; @VisibleForTesting public FlutterSdkVersion(@Nullable String versionString) { versionText = versionString; if (versionString != null) { final String[] split = versionString.split("-"); version = Version.parseVersion(split[0]); if (split.length > 1) { betaVersion = Version.parseVersion(split[1]); final String[] parts = split[1].split("\\."); masterVersion = parts.length > 3 ? Integer.parseInt(parts[3]) : 0; } else { betaVersion = null; masterVersion = 0; } } else { version = null; betaVersion = null; masterVersion = 0; } } @NotNull public static FlutterSdkVersion readFromSdk(@NotNull VirtualFile sdkHome) { return readFromFile(sdkHome.findChild("version")); } @NotNull private static FlutterSdkVersion readFromFile(@Nullable VirtualFile file) { if (file == null) { return new FlutterSdkVersion(null); } final String versionString = readVersionString(file); if (versionString == null) { return new FlutterSdkVersion(null); } return new FlutterSdkVersion(versionString); } private static String readVersionString(VirtualFile file) { try { final String data = new String(file.contentsToByteArray(), StandardCharsets.UTF_8); for (String line : data.split("\n")) { line = line.trim(); if (line.isEmpty() || line.startsWith("#")) { continue; } return line; } return null; } catch (IOException e) { return null; } } public boolean isMinRecommendedSupported() { assert (MIN_SUPPORTED_SDK.version != null); return version != null && version.compareTo(MIN_SUPPORTED_SDK.version) >= 0; } public boolean isTrackWidgetCreationRecommended() { assert (MIN_SAFE_TRACK_WIDGET_CREATION_SDK.version != null); return version != null && version.compareTo(MIN_SAFE_TRACK_WIDGET_CREATION_SDK.version) >= 0; } public boolean isDartDefineSupported() { //noinspection ConstantConditions return version != null && version.compareTo(MIN_DART_DEFINE_SDK.version) >= 0; } public boolean isXcodeConfigOnlySupported() { //noinspection ConstantConditions return version != null && version.compareTo(MIN_XCODE_CONFIG_ONLY.version) >= 0; } public boolean flutterCreateSupportsPlatforms() { //noinspection ConstantConditions return version != null && version.compareTo(MIN_CREATE_PLATFORMS_SDK.version) >= 0; } public boolean stableChannelSupportsPlatforms() { //noinspection ConstantConditions return version != null && version.compareTo(MAX_STABLE_NO_PLATFORMS_SDK.version) > 0; } public boolean flutterRunSupportsDevToolsUrl() { return version != null && this.compareTo(MIN_PASS_DEVTOOLS_SDK) >= 0 && this.compareTo(MIN_OPTIONAL_PASS_DEVTOOLS_SDK) < 0; } public boolean useDaemonForDevTools() { return version != null && this.compareTo(MIN_PASS_DEVTOOLS_SDK) >= 0; } public boolean flutterTestSupportsMachineMode() { return isMinRecommendedSupported(); } public boolean flutterTestSupportsFiltering() { return isMinRecommendedSupported(); } public boolean isPubOutdatedSupported() { //noinspection ConstantConditions return version != null && version.compareTo(MIN_PUB_OUTDATED_SDK.version) >= 0; } public boolean isSkeletonTemplateAvailable() { return version != null && version.compareTo(MIN_SKELETON_TEMPLATE.version) >= 0; } public boolean isPluginFfiTemplateAvailable() { return version != null && version.compareTo(MIN_PLUGIN_FFI_TEMPLATE.version) >= 0; } public boolean isEmptyProjectAvailable() { return version != null && version.compareTo(MIN_EMPTY_PROJECT.version) >= 0; } public boolean isUriMappingSupportedForWeb() { return version != null && this.compareTo(MIN_URI_MAPPING_FOR_WEB) >= 0; } public boolean isWebPlatformStable() { return version != null && this.compareTo(MIN_STABLE_WEB_PLATFORM) >= 0; } public boolean isWindowsPlatformStable() { return version != null && this.compareTo(MIN_STABLE_WINDOWS_PLATFORM) >= 0; } public boolean isLinuxPlatformStable() { return version != null && this.compareTo(MIN_STABLE_LINUX_PLATFORM) >= 0; } public boolean isMacOSPlatformStable() { return version != null && this.compareTo(MIN_STABLE_MACOS_PLATFORM) >= 0; } public boolean canUseDistributedIcons() { return version != null && this.compareTo(DISTRIBUTED_ICONS) >= 0; } public boolean canUseDevToolsPathUrls() { return version != null && this.compareTo(MIN_SUPPORTS_DEVTOOLS_PATH_URLS) >= 0; } public boolean isValid() { return version != null; } public String fullVersion() { return version == null ? "unknown version" : version.toString(); } /** * Return the raw version text from the version file. */ @Nullable public String getVersionText() { return versionText; } @Override public String toString() { return version == null ? "unknown version" : version.toCompactString(); } @Override public int compareTo(@NotNull FlutterSdkVersion otherVersion) { // TODO(messick) Remove "version != null" prior to calling this method everywhere in this file. if (version == null) return -1; if (otherVersion.version == null) return 1; final int standardComparisonResult = version.compareTo(otherVersion.version); if (standardComparisonResult != 0) { return standardComparisonResult; } // Check for beta version strings if standard versions are equivalent. if (betaVersion == null && otherVersion.betaVersion == null) { return 0; } else if (betaVersion == null) { return 1; } else if (otherVersion.betaVersion == null) { return -1; } final int betaComparisonResult = betaVersion.compareTo(otherVersion.betaVersion); if (betaComparisonResult != 0) { return betaComparisonResult; } // Check master version ints if both have master version ints and versions are otherwise equivalent. // Otherwise, the version without a master version is further ahead. if (masterVersion != 0 && otherVersion.masterVersion != 0) { return Integer.compare(masterVersion, otherVersion.masterVersion); } else if (masterVersion != 0) { return -1; } else if (otherVersion.masterVersion != 0) { return 1; } else { return 0; } } }
flutter-intellij/flutter-idea/src/io/flutter/sdk/FlutterSdkVersion.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/sdk/FlutterSdkVersion.java", "repo_id": "flutter-intellij", "token_count": 3668 }
524
/* * 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. */ package io.flutter.utils; import com.google.common.util.concurrent.RateLimiter; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Computable; import com.intellij.util.Alarm; import javax.swing.*; import java.util.concurrent.CompletableFuture; /** * Rate limiter that issues requests asynchronously on the ui thread * ensuring framesPerSecond rate is not exceeded and that no more than 1 * request is issued at a time. * <p> * Methods from this class must only be invoked from the main UI thread. */ public class AsyncRateLimiter { private static final Logger LOG = Logger.getInstance(AsyncRateLimiter.class); private final String requestScheduleLock = "requestScheduleLock"; private final RateLimiter rateLimiter; private final Alarm requestScheduler; private final Computable<CompletableFuture<?>> callback; /** * Number of requests pending including the request currently executing. */ private volatile int numRequestsPending; /** * Number of requests currently executing. * <p> * This should only be 0 or 1 but we track it as an integer to make it easier * to catch logic bugs. */ private volatile int numRequestsExecuting; public AsyncRateLimiter(double framesPerSecond, Computable<CompletableFuture<?>> callback, Disposable parentDisposable) { this.callback = callback; rateLimiter = RateLimiter.create(framesPerSecond); requestScheduler = new Alarm(Alarm.ThreadToUse.POOLED_THREAD, parentDisposable); } public void scheduleRequest() { final boolean scheduleRequestImmediately; synchronized (requestScheduleLock) { scheduleRequestImmediately = numRequestsPending == 0; assert (numRequestsPending >= 0); // Logic error if we ever complete more requests than we started. assert (numRequestsPending < 3); // Logic error if we ever have more than 2 requests pending. assert (numRequestsExecuting < 2); // Logic error if we ever have more than 1 request executing. final int numRequestsNotYetStarted = numRequestsPending - numRequestsExecuting; // If there is alredy a request that has yet to begin, no need to schedule new request. if (numRequestsNotYetStarted == 0) { numRequestsPending++; } } if (scheduleRequestImmediately) { scheduleRequestHelper(); } } // This method may be called on any thread. public void scheduleRequestHelper() { // Don't schedule the request if this rate limiter has been disposed. if (requestScheduler.isDisposed()) { return; } // Schedule a request to occur once the rate limiter is available. requestScheduler.addRequest(() -> { rateLimiter.acquire(); performRequestOnUiThread(); }, 0); } private void performRequestOnUiThread() { final Runnable doRun = () -> { if (requestScheduler.isDisposed()) { return; } performRequest(); }; final Application app = ApplicationManager.getApplication(); if (app == null || app.isUnitTestMode()) { // This case exists to support unittesting. SwingUtilities.invokeLater(doRun); } else { app.invokeLater(doRun); } } private void performRequest() { synchronized (requestScheduleLock) { assert (numRequestsPending > 0); assert (numRequestsExecuting == 0); numRequestsExecuting++; } try { final CompletableFuture<?> requestComplete = callback.compute(); requestComplete.whenCompleteAsync( (v, e) -> onRequestComplete()); } catch (Exception e) { LOG.warn(e); onRequestComplete(); } } private void onRequestComplete() { final boolean requestsPending; synchronized (requestScheduleLock) { assert (numRequestsPending > 0); assert (numRequestsExecuting == 1); numRequestsPending--; numRequestsExecuting--; requestsPending = numRequestsPending > 0; } if (requestsPending) { scheduleRequestHelper(); } } }
flutter-intellij/flutter-idea/src/io/flutter/utils/AsyncRateLimiter.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/utils/AsyncRateLimiter.java", "repo_id": "flutter-intellij", "token_count": 1429 }
525
/* * Copyright 2016 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. */ package io.flutter.utils; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.progress.Task; import com.intellij.openapi.project.Project; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; public class ProgressHelper { final Project myProject; final List<String> myTasks = new ArrayList<>(); private Task.Backgroundable myTask; public ProgressHelper(@NotNull Project project) { this.myProject = project; } /** * Start a progress task. * * @param log the title of the progress task */ public void start(String log) { synchronized (myTasks) { myTasks.add(log); myTasks.notifyAll(); if (myTask == null) { myTask = new Task.Backgroundable(myProject, log, false) { @Override public void run(@NotNull ProgressIndicator indicator) { indicator.setText(log); synchronized (myTasks) { while (!myTasks.isEmpty()) { indicator.setText(myTasks.get(myTasks.size() - 1)); try { myTasks.wait(); } catch (InterruptedException e) { // ignore } myTask = null; } } } }; ApplicationManager.getApplication().invokeLater(() -> { synchronized (myTasks) { if (myTask != null && !myProject.isDisposed()) { ProgressManager.getInstance().run(myTask); } } }); } } } /** * Notify that a progress task has finished. */ public void done() { synchronized (myTasks) { if (!myTasks.isEmpty()) { myTasks.remove(myTasks.size() - 1); myTasks.notifyAll(); } } } /** * Finish any outstanding progress tasks. */ public void cancel() { synchronized (myTasks) { myTasks.clear(); myTasks.notifyAll(); } } }
flutter-intellij/flutter-idea/src/io/flutter/utils/ProgressHelper.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/utils/ProgressHelper.java", "repo_id": "flutter-intellij", "token_count": 994 }
526
/* * 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. */ package io.flutter.utils.math; import java.util.Arrays; /** * 4D Matrix. * <p> * Values are stored in column major order. * <p> * This code is ported from the Matrix4 class in the Dart vector_math * package. The Class is ported as is without concern for making the code * consistent with Java api conventions to keep the code consistent with * the Dart code to simplify using Transform Matrixes returned by Flutter. */ @SuppressWarnings({"Duplicates", "PointlessArithmeticExpression", "UnnecessaryLocalVariable", "JoinDeclarationAndAssignmentJava"}) public class Matrix4 { final double[] _m4storage; /** * Constructs a new mat4. */ public Matrix4( double arg0, double arg1, double arg2, double arg3, double arg4, double arg5, double arg6, double arg7, double arg8, double arg9, double arg10, double arg11, double arg12, double arg13, double arg14, double arg15) { _m4storage = new double[16]; setValues(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15); } /** * Zero matrix. */ Matrix4() { _m4storage = new double[16]; } /** * Constructs Matrix4 with given [double[]] as [storage]. */ public Matrix4(double[] storage) { this._m4storage = storage; } /** * Solve [A] * [x] = [b]. */ static void solve2(Matrix4 A, Vector2 x, Vector2 b) { final double a11 = A.entry(0, 0); final double a12 = A.entry(0, 1); final double a21 = A.entry(1, 0); final double a22 = A.entry(1, 1); final double bx = b.getX() - A._m4storage[8]; final double by = b.getY() - A._m4storage[9]; double det = a11 * a22 - a12 * a21; if (det != 0.0) { det = 1.0 / det; } x.setX(det * (a22 * bx - a12 * by)); x.setY(det * (a11 * by - a21 * bx)); } /** * Solve [A] * [x] = [b]. */ public static void solve3(Matrix4 A, Vector3 x, Vector3 b) { final double A0x = A.entry(0, 0); final double A0y = A.entry(1, 0); final double A0z = A.entry(2, 0); final double A1x = A.entry(0, 1); final double A1y = A.entry(1, 1); final double A1z = A.entry(2, 1); final double A2x = A.entry(0, 2); final double A2y = A.entry(1, 2); final double A2z = A.entry(2, 2); final double bx = b.getX() - A._m4storage[12]; final double by = b.getY() - A._m4storage[13]; final double bz = b.getZ() - A._m4storage[14]; double rx, ry, rz; double det; // Column1 cross Column 2 rx = A1y * A2z - A1z * A2y; ry = A1z * A2x - A1x * A2z; rz = A1x * A2y - A1y * A2x; // A.getColumn(0).dot(x) det = A0x * rx + A0y * ry + A0z * rz; if (det != 0.0) { det = 1.0 / det; } // b dot [Column1 cross Column 2] final double x_ = det * (bx * rx + by * ry + bz * rz); // Column2 cross b rx = -(A2y * bz - A2z * by); ry = -(A2z * bx - A2x * bz); rz = -(A2x * by - A2y * bx); // Column0 dot -[Column2 cross b (Column3)] final double y_ = det * (A0x * rx + A0y * ry + A0z * rz); // b cross Column 1 rx = -(by * A1z - bz * A1y); ry = -(bz * A1x - bx * A1z); rz = -(bx * A1y - by * A1x); // Column0 dot -[b cross Column 1] final double z_ = det * (A0x * rx + A0y * ry + A0z * rz); x.setX(x_); x.setY(y_); x.setZ(z_); } /** * Solve [A] * [x] = [b]. */ static void solve(Matrix4 A, Vector4 x, Vector4 b) { final double a00 = A._m4storage[0]; final double a01 = A._m4storage[1]; final double a02 = A._m4storage[2]; final double a03 = A._m4storage[3]; final double a10 = A._m4storage[4]; final double a11 = A._m4storage[5]; final double a12 = A._m4storage[6]; final double a13 = A._m4storage[7]; final double a20 = A._m4storage[8]; final double a21 = A._m4storage[9]; final double a22 = A._m4storage[10]; final double a23 = A._m4storage[11]; final double a30 = A._m4storage[12]; final double a31 = A._m4storage[13]; final double a32 = A._m4storage[14]; final double a33 = A._m4storage[15]; final double b00 = a00 * a11 - a01 * a10; final double b01 = a00 * a12 - a02 * a10; final double b02 = a00 * a13 - a03 * a10; final double b03 = a01 * a12 - a02 * a11; final double b04 = a01 * a13 - a03 * a11; final double b05 = a02 * a13 - a03 * a12; final double b06 = a20 * a31 - a21 * a30; final double b07 = a20 * a32 - a22 * a30; final double b08 = a20 * a33 - a23 * a30; final double b09 = a21 * a32 - a22 * a31; final double b10 = a21 * a33 - a23 * a31; final double b11 = a22 * a33 - a23 * a32; final double bX = b.getStorage()[0]; final double bY = b.getStorage()[1]; final double bZ = b.getStorage()[2]; final double bW = b.getStorage()[3]; double det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; if (det != 0.0) { det = 1.0 / det; } x .setX(det * ((a11 * b11 - a12 * b10 + a13 * b09) * bX - (a10 * b11 - a12 * b08 + a13 * b07) * bY + (a10 * b10 - a11 * b08 + a13 * b06) * bZ - (a10 * b09 - a11 * b07 + a12 * b06) * bW)); x.setY(det * -((a01 * b11 - a02 * b10 + a03 * b09) * bX - (a00 * b11 - a02 * b08 + a03 * b07) * bY + (a00 * b10 - a01 * b08 + a03 * b06) * bZ - (a00 * b09 - a01 * b07 + a02 * b06) * bW)); x.setZ(det * ((a31 * b05 - a32 * b04 + a33 * b03) * bX - (a30 * b05 - a32 * b02 + a33 * b01) * bY + (a30 * b04 - a31 * b02 + a33 * b00) * bZ - (a30 * b03 - a31 * b01 + a32 * b00) * bW)); x.setW(det * -((a21 * b05 - a22 * b04 + a23 * b03) * bX - (a20 * b05 - a22 * b02 + a23 * b01) * bY + (a20 * b04 - a21 * b02 + a23 * b00) * bZ - (a20 * b03 - a21 * b01 + a22 * b00) * bW)); } /** * Returns a matrix that is the inverse of [other] if [other] is invertible, * otherwise `null`. */ static Matrix4 tryInvert(Matrix4 other) { final Matrix4 r = new Matrix4(); final double determinant = r.copyInverse(other); if (determinant == 0.0) { return null; } return r; } /** * New matrix from [values]. */ public static Matrix4 fromList(double[] values) { final Matrix4 ret = new Matrix4(); ret.setValues( values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7], values[8], values[9], values[10], values[11], values[12], values[13], values[14], values[15]); return ret; } public static Matrix4 zero() { return new Matrix4(); } /** * Identity matrix. */ public static Matrix4 identity() { final Matrix4 ret = new Matrix4(); ret.setIdentity(); return ret; } /** * Copies values from [other]. */ public static Matrix4 copy(Matrix4 other) { final Matrix4 ret = new Matrix4(); ret.setFrom(other); return ret; } /** * Constructs a matrix that is the inverse of [other]. */ public static Matrix4 inverted(Matrix4 other) { final Matrix4 r = new Matrix4(); final double determinant = r.copyInverse(other); if (determinant == 0.0) { throw new IllegalArgumentException( "" + other + "other Matrix cannot be inverted"); } return r; } /** * Constructs a new mat4 from columns. */ public static Matrix4 columns( Vector4 arg0, Vector4 arg1, Vector4 arg2, Vector4 arg3) { final Matrix4 ret = new Matrix4(); ret.setColumns(arg0, arg1, arg2, arg3); return ret; } /** * Outer product of [u] and [v]. */ public static Matrix4 outer(Vector4 u, Vector4 v) { final Matrix4 ret = new Matrix4(); ret.setOuter(u, v); return ret; } /** * Rotation of [radians_] around X. */ public static Matrix4 rotationX(double radians) { final Matrix4 ret = new Matrix4(); ret._m4storage[15] = 1.0; ret.setRotationX(radians); return ret; } /** * Rotation of [radians_] around Y. */ public static Matrix4 rotationY(double radians) { final Matrix4 ret = new Matrix4(); ret._m4storage[15] = 1.0; ret.setRotationY(radians); return ret; } /** * Rotation of [radians_] around Z. */ public static Matrix4 rotationZ(double radians) { final Matrix4 ret = new Matrix4(); ret._m4storage[15] = 1.0; ret.setRotationZ(radians); return ret; } /** * Translation matrix. */ public static Matrix4 translation(Vector3 translation) { final Matrix4 ret = new Matrix4(); ret.setIdentity(); ret.setTranslation(translation); return ret; } /** * Translation matrix. */ public static Matrix4 translationValues(double x, double y, double z) { final Matrix4 ret = new Matrix4(); ret.setIdentity(); ret.setTranslationRaw(x, y, z); return ret; } /** * Scale matrix. */ public static Matrix4 diagonal3(Vector3 scale) { final Matrix4 m = new Matrix4(); final double[] mStorage = m._m4storage; final double[] scaleStorage = scale._v3storage; mStorage[15] = 1.0; mStorage[10] = scaleStorage[2]; mStorage[5] = scaleStorage[1]; mStorage[0] = scaleStorage[0]; return m; } /** * Scale matrix. */ public static Matrix4 diagonal3Values(double x, double y, double z) { final Matrix4 ret = new Matrix4(); ret._m4storage[15] = 1.0; ret._m4storage[10] = z; ret._m4storage[5] = y; ret._m4storage[0] = x; return ret; } /** * Skew matrix around X axis */ public static Matrix4 skewX(double alpha) { final Matrix4 m = Matrix4.identity(); m._m4storage[4] = Math.tan(alpha); return m; } /** * Skew matrix around Y axis. */ public static Matrix4 skewY(double beta) { final Matrix4 m = Matrix4.identity(); m._m4storage[1] = Math.tan(beta); return m; } /** * Skew matrix around X axis (alpha) and Y axis (beta). */ public static Matrix4 skew(double alpha, double beta) { final Matrix4 m = Matrix4.identity(); m._m4storage[1] = Math.tan(beta); m._m4storage[4] = Math.tan(alpha); return m; } /** * Constructs Matrix4 from [translation], [rotation] and [scale]. */ public static Matrix4 compose( Vector3 translation, Quaternion rotation, Vector3 scale) { final Matrix4 matrix = new Matrix4(); matrix.setFromTranslationRotationScale(translation, rotation, scale); return matrix; } /** * The components of the matrix. */ double[] getStorage() { return _m4storage; } /** * Return index in storage for [row], [col] value. */ public int index(int row, int col) { return (col * 4) + row; } /** * Value at [row], [col]. */ public double entry(int row, int col) { assert ((row >= 0) && (row < getDimension())); assert ((col >= 0) && (col < getDimension())); return _m4storage[index(row, col)]; } /** * Set value at [row], [col] to be [v]. */ void setEntry(int row, int col, double v) { assert ((row >= 0) && (row < getDimension())); assert ((col >= 0) && (col < getDimension())); _m4storage[index(row, col)] = v; } /** * Sets the diagonal to [arg]. */ void splatDiagonal(double arg) { _m4storage[0] = arg; _m4storage[5] = arg; _m4storage[10] = arg; _m4storage[15] = arg; } /** * Sets the matrix with specified values. */ void setValues( double arg0, double arg1, double arg2, double arg3, double arg4, double arg5, double arg6, double arg7, double arg8, double arg9, double arg10, double arg11, double arg12, double arg13, double arg14, double arg15) { _m4storage[15] = arg15; _m4storage[14] = arg14; _m4storage[13] = arg13; _m4storage[12] = arg12; _m4storage[11] = arg11; _m4storage[10] = arg10; _m4storage[9] = arg9; _m4storage[8] = arg8; _m4storage[7] = arg7; _m4storage[6] = arg6; _m4storage[5] = arg5; _m4storage[4] = arg4; _m4storage[3] = arg3; _m4storage[2] = arg2; _m4storage[1] = arg1; _m4storage[0] = arg0; } /** * Sets the entire matrix to the column values. */ void setColumns(Vector4 arg0, Vector4 arg1, Vector4 arg2, Vector4 arg3) { final double[] arg0Storage = arg0._v4storage; final double[] arg1Storage = arg1._v4storage; final double[] arg2Storage = arg2._v4storage; final double[] arg3Storage = arg3._v4storage; _m4storage[0] = arg0Storage[0]; _m4storage[1] = arg0Storage[1]; _m4storage[2] = arg0Storage[2]; _m4storage[3] = arg0Storage[3]; _m4storage[4] = arg1Storage[0]; _m4storage[5] = arg1Storage[1]; _m4storage[6] = arg1Storage[2]; _m4storage[7] = arg1Storage[3]; _m4storage[8] = arg2Storage[0]; _m4storage[9] = arg2Storage[1]; _m4storage[10] = arg2Storage[2]; _m4storage[11] = arg2Storage[3]; _m4storage[12] = arg3Storage[0]; _m4storage[13] = arg3Storage[1]; _m4storage[14] = arg3Storage[2]; _m4storage[15] = arg3Storage[3]; } /** * Sets the entire matrix to the matrix in [arg]. */ void setFrom(Matrix4 arg) { final double[] argStorage = arg._m4storage; _m4storage[15] = argStorage[15]; _m4storage[14] = argStorage[14]; _m4storage[13] = argStorage[13]; _m4storage[12] = argStorage[12]; _m4storage[11] = argStorage[11]; _m4storage[10] = argStorage[10]; _m4storage[9] = argStorage[9]; _m4storage[8] = argStorage[8]; _m4storage[7] = argStorage[7]; _m4storage[6] = argStorage[6]; _m4storage[5] = argStorage[5]; _m4storage[4] = argStorage[4]; _m4storage[3] = argStorage[3]; _m4storage[2] = argStorage[2]; _m4storage[1] = argStorage[1]; _m4storage[0] = argStorage[0]; } /** * Sets the matrix from translation [arg0] and rotation [arg1]. */ void setFromTranslationRotation(Vector3 arg0, Quaternion arg1) { final double[] arg1Storage = arg1._qStorage; final double x = arg1Storage[0]; final double y = arg1Storage[1]; final double z = arg1Storage[2]; final double w = arg1Storage[3]; final double x2 = x + x; final double y2 = y + y; final double z2 = z + z; final double xx = x * x2; final double xy = x * y2; final double xz = x * z2; final double yy = y * y2; final double yz = y * z2; final double zz = z * z2; final double wx = w * x2; final double wy = w * y2; final double wz = w * z2; final double[] arg0Storage = arg0._v3storage; _m4storage[0] = 1.0 - (yy + zz); _m4storage[1] = xy + wz; _m4storage[2] = xz - wy; _m4storage[3] = 0.0; _m4storage[4] = xy - wz; _m4storage[5] = 1.0 - (xx + zz); _m4storage[6] = yz + wx; _m4storage[7] = 0.0; _m4storage[8] = xz + wy; _m4storage[9] = yz - wx; _m4storage[10] = 1.0 - (xx + yy); _m4storage[11] = 0.0; _m4storage[12] = arg0Storage[0]; _m4storage[13] = arg0Storage[1]; _m4storage[14] = arg0Storage[2]; _m4storage[15] = 1.0; } /** * Sets the matrix from [translation], [rotation] and [scale]. */ void setFromTranslationRotationScale( Vector3 translation, Quaternion rotation, Vector3 scale) { setFromTranslationRotation(translation, rotation); this.scale(scale); } /** * Sets the diagonal of the matrix to be [arg]. */ void setDiagonal(Vector4 arg) { final double[] argStorage = arg._v4storage; _m4storage[0] = argStorage[0]; _m4storage[5] = argStorage[1]; _m4storage[10] = argStorage[2]; _m4storage[15] = argStorage[3]; } void setOuter(Vector4 u, Vector4 v) { final double[] uStorage = u._v4storage; final double[] vStorage = v._v4storage; _m4storage[0] = uStorage[0] * vStorage[0]; _m4storage[1] = uStorage[0] * vStorage[1]; _m4storage[2] = uStorage[0] * vStorage[2]; _m4storage[3] = uStorage[0] * vStorage[3]; _m4storage[4] = uStorage[1] * vStorage[0]; _m4storage[5] = uStorage[1] * vStorage[1]; _m4storage[6] = uStorage[1] * vStorage[2]; _m4storage[7] = uStorage[1] * vStorage[3]; _m4storage[8] = uStorage[2] * vStorage[0]; _m4storage[9] = uStorage[2] * vStorage[1]; _m4storage[10] = uStorage[2] * vStorage[2]; _m4storage[11] = uStorage[2] * vStorage[3]; _m4storage[12] = uStorage[3] * vStorage[0]; _m4storage[13] = uStorage[3] * vStorage[1]; _m4storage[14] = uStorage[3] * vStorage[2]; _m4storage[15] = uStorage[3] * vStorage[3]; } /** * Returns a printable string */ @Override() public String toString() { return "[0] " + getRow(0) + "\n" + "[1] " + getRow(1) + "\n" + "[2] " + getRow(2) + "\n" + "[3] " + getRow(3) + "\n"; } /** * Dimension of the matrix. */ public int getDimension() { return 4; } /** * Access the element of the matrix at the index [i]. */ double get(int i) { return _m4storage[i]; } /** * Set the element of the matrix at the index [i]. */ void set(int i, double v) { _m4storage[i] = v; } /** * Check if two matrices are the same. */ @Override() public boolean equals(Object o) { if (!(o instanceof Matrix4)) { return false; } final Matrix4 other = (Matrix4)o; return (_m4storage[0] == other._m4storage[0]) && (_m4storage[1] == other._m4storage[1]) && (_m4storage[2] == other._m4storage[2]) && (_m4storage[3] == other._m4storage[3]) && (_m4storage[4] == other._m4storage[4]) && (_m4storage[5] == other._m4storage[5]) && (_m4storage[6] == other._m4storage[6]) && (_m4storage[7] == other._m4storage[7]) && (_m4storage[8] == other._m4storage[8]) && (_m4storage[9] == other._m4storage[9]) && (_m4storage[10] == other._m4storage[10]) && (_m4storage[11] == other._m4storage[11]) && (_m4storage[12] == other._m4storage[12]) && (_m4storage[13] == other._m4storage[13]) && (_m4storage[14] == other._m4storage[14]) && (_m4storage[15] == other._m4storage[15]); } @Override() public int hashCode() { return Arrays.hashCode(_m4storage); } /** * Returns row 0 */ public Vector4 getRow0() { return getRow(0); } /** * Sets row 0 to [arg] */ public void setRow0(Vector4 arg) { setRow(0, arg); } /** * Returns row 1 */ public Vector4 getRow1() { return getRow(1); } /** * Sets row 1 to [arg] */ public void setRow1(Vector4 arg) { setRow(1, arg); } /** * Returns row 2 */ public Vector4 getRow2() { return getRow(2); } /** * Sets row 2 to [arg] */ public void setRow2(Vector4 arg) { setRow(2, arg); } /** * Returns row 3 */ public Vector4 getRow3() { return getRow(3); } /** * Sets row 3 to [arg] */ public void setRow3(Vector4 arg) { setRow(3, arg); } /** * Assigns the [row] of the matrix [arg] */ public void setRow(int row, Vector4 arg) { final double[] argStorage = arg._v4storage; _m4storage[index(row, 0)] = argStorage[0]; _m4storage[index(row, 1)] = argStorage[1]; _m4storage[index(row, 2)] = argStorage[2]; _m4storage[index(row, 3)] = argStorage[3]; } /** * Gets the [row] of the matrix */ public Vector4 getRow(int row) { final Vector4 r = new Vector4(); final double[] rStorage = r._v4storage; rStorage[0] = _m4storage[index(row, 0)]; rStorage[1] = _m4storage[index(row, 1)]; rStorage[2] = _m4storage[index(row, 2)]; rStorage[3] = _m4storage[index(row, 3)]; return r; } /** * Assigns the [column] of the matrix [arg] */ public void setColumn(int column, Vector4 arg) { final int entry = column * 4; final double[] argStorage = arg._v4storage; _m4storage[entry + 3] = argStorage[3]; _m4storage[entry + 2] = argStorage[2]; _m4storage[entry + 1] = argStorage[1]; _m4storage[entry + 0] = argStorage[0]; } /** * Gets the [column] of the matrix */ public Vector4 getColumn(int column) { final Vector4 r = new Vector4(); final double[] rStorage = r._v4storage; final int entry = column * 4; rStorage[3] = _m4storage[entry + 3]; rStorage[2] = _m4storage[entry + 2]; rStorage[1] = _m4storage[entry + 1]; rStorage[0] = _m4storage[entry + 0]; return r; } /** * Clone matrix. */ @SuppressWarnings("MethodDoesntCallSuperMethod") @Override public Matrix4 clone() { return Matrix4.copy(this); } /** * Copy into [arg]. */ public Matrix4 copyInto(Matrix4 arg) { final double[] argStorage = arg._m4storage; argStorage[0] = _m4storage[0]; argStorage[1] = _m4storage[1]; argStorage[2] = _m4storage[2]; argStorage[3] = _m4storage[3]; argStorage[4] = _m4storage[4]; argStorage[5] = _m4storage[5]; argStorage[6] = _m4storage[6]; argStorage[7] = _m4storage[7]; argStorage[8] = _m4storage[8]; argStorage[9] = _m4storage[9]; argStorage[10] = _m4storage[10]; argStorage[11] = _m4storage[11]; argStorage[12] = _m4storage[12]; argStorage[13] = _m4storage[13]; argStorage[14] = _m4storage[14]; argStorage[15] = _m4storage[15]; return arg; } /** * Returns new matrix -this */ public Matrix4 operatorNegate() { final Matrix4 ret = clone(); ret.negate(); return ret; } /** * Returns a new vector or matrix by multiplying [this] with [arg]. */ Matrix4 operatorMultiply(double arg) { return scaled(arg); } public Vector4 operatorMultiply(Vector4 arg) { return transformed(arg); } public Vector3 operatorMultiply(Vector3 arg) { return transformed3(arg); } public Matrix4 operatorMultiply(Matrix4 arg) { return multiplied(arg); } /** * Returns new matrix after component wise [this] + [arg] */ public Matrix4 operatorAdd(Matrix4 arg) { final Matrix4 ret = clone(); ret.add(arg); return ret; } /** * Returns new matrix after component wise [this] - [arg] */ public Matrix4 operatorSub(Matrix4 arg) { final Matrix4 ret = clone(); ret.sub(arg); return ret; } /** * Translate this matrix by a [Vector3], [Vector4], or x,y,z */ public void translate(double x) { translate(x, 0, 0); } public void translate(Vector3 v) { translate(v.getX(), v.getY(), v.getZ()); } public void translate(Vector4 v) { translate(v.getX(), v.getY(), v.getZ(), v.getW()); } public void translate(double x, double y, double z) { translate(x, y, z, 1); } public void translate(double tx, double ty, double tz, double tw) { final double t1 = _m4storage[0] * tx + _m4storage[4] * ty + _m4storage[8] * tz + _m4storage[12] * tw; final double t2 = _m4storage[1] * tx + _m4storage[5] * ty + _m4storage[9] * tz + _m4storage[13] * tw; final double t3 = _m4storage[2] * tx + _m4storage[6] * ty + _m4storage[10] * tz + _m4storage[14] * tw; final double t4 = _m4storage[3] * tx + _m4storage[7] * ty + _m4storage[11] * tz + _m4storage[15] * tw; _m4storage[12] = t1; _m4storage[13] = t2; _m4storage[14] = t3; _m4storage[15] = t4; } /** * Multiply [this] by a translation from the left. */ public void leftTranslate(double x, double y, double z) { leftTranslater(x, y, z, 1); } public void leftTranslate(double x) { leftTranslater(x, 0, 0, 1); } public void leftTranslate(Vector4 v) { leftTranslater(v.getX(), v.getY(), v.getZ(), v.getW()); } public void leftTranslate(Vector3 v) { leftTranslater(v.getX(), v.getY(), v.getZ(), 1.0); } void leftTranslater(double tx, double ty, double tz, double tw) { // Column 1 _m4storage[0] += tx * _m4storage[3]; _m4storage[1] += ty * _m4storage[3]; _m4storage[2] += tz * _m4storage[3]; _m4storage[3] = tw * _m4storage[3]; // Column 2 _m4storage[4] += tx * _m4storage[7]; _m4storage[5] += ty * _m4storage[7]; _m4storage[6] += tz * _m4storage[7]; _m4storage[7] = tw * _m4storage[7]; // Column 3 _m4storage[8] += tx * _m4storage[11]; _m4storage[9] += ty * _m4storage[11]; _m4storage[10] += tz * _m4storage[11]; _m4storage[11] = tw * _m4storage[11]; // Column 4 _m4storage[12] += tx * _m4storage[15]; _m4storage[13] += ty * _m4storage[15]; _m4storage[14] += tz * _m4storage[15]; _m4storage[15] = tw * _m4storage[15]; } /** * Rotate this [angle] radians around [axis] */ public void rotate(Vector3 axis, double angle) { final double len = axis.getLength(); final double[] axisStorage = axis._v3storage; final double x = axisStorage[0] / len; final double y = axisStorage[1] / len; final double z = axisStorage[2] / len; final double c = Math.cos(angle); final double s = Math.sin(angle); final double C = 1.0 - c; final double m11 = x * x * C + c; final double m12 = x * y * C - z * s; final double m13 = x * z * C + y * s; final double m21 = y * x * C + z * s; final double m22 = y * y * C + c; final double m23 = y * z * C - x * s; final double m31 = z * x * C - y * s; final double m32 = z * y * C + x * s; final double m33 = z * z * C + c; final double t1 = _m4storage[0] * m11 + _m4storage[4] * m21 + _m4storage[8] * m31; final double t2 = _m4storage[1] * m11 + _m4storage[5] * m21 + _m4storage[9] * m31; final double t3 = _m4storage[2] * m11 + _m4storage[6] * m21 + _m4storage[10] * m31; final double t4 = _m4storage[3] * m11 + _m4storage[7] * m21 + _m4storage[11] * m31; final double t5 = _m4storage[0] * m12 + _m4storage[4] * m22 + _m4storage[8] * m32; final double t6 = _m4storage[1] * m12 + _m4storage[5] * m22 + _m4storage[9] * m32; final double t7 = _m4storage[2] * m12 + _m4storage[6] * m22 + _m4storage[10] * m32; final double t8 = _m4storage[3] * m12 + _m4storage[7] * m22 + _m4storage[11] * m32; final double t9 = _m4storage[0] * m13 + _m4storage[4] * m23 + _m4storage[8] * m33; final double t10 = _m4storage[1] * m13 + _m4storage[5] * m23 + _m4storage[9] * m33; final double t11 = _m4storage[2] * m13 + _m4storage[6] * m23 + _m4storage[10] * m33; final double t12 = _m4storage[3] * m13 + _m4storage[7] * m23 + _m4storage[11] * m33; _m4storage[0] = t1; _m4storage[1] = t2; _m4storage[2] = t3; _m4storage[3] = t4; _m4storage[4] = t5; _m4storage[5] = t6; _m4storage[6] = t7; _m4storage[7] = t8; _m4storage[8] = t9; _m4storage[9] = t10; _m4storage[10] = t11; _m4storage[11] = t12; } /** * Rotate this [angle] radians around X */ public void rotateX(double angle) { final double cosAngle = Math.cos(angle); final double sinAngle = Math.sin(angle); final double t1 = _m4storage[4] * cosAngle + _m4storage[8] * sinAngle; final double t2 = _m4storage[5] * cosAngle + _m4storage[9] * sinAngle; final double t3 = _m4storage[6] * cosAngle + _m4storage[10] * sinAngle; final double t4 = _m4storage[7] * cosAngle + _m4storage[11] * sinAngle; final double t5 = _m4storage[4] * -sinAngle + _m4storage[8] * cosAngle; final double t6 = _m4storage[5] * -sinAngle + _m4storage[9] * cosAngle; final double t7 = _m4storage[6] * -sinAngle + _m4storage[10] * cosAngle; final double t8 = _m4storage[7] * -sinAngle + _m4storage[11] * cosAngle; _m4storage[4] = t1; _m4storage[5] = t2; _m4storage[6] = t3; _m4storage[7] = t4; _m4storage[8] = t5; _m4storage[9] = t6; _m4storage[10] = t7; _m4storage[11] = t8; } /** * Rotate this matrix [angle] radians around Y */ public void rotateY(double angle) { final double cosAngle = Math.cos(angle); final double sinAngle = Math.sin(angle); final double t1 = _m4storage[0] * cosAngle + _m4storage[8] * -sinAngle; final double t2 = _m4storage[1] * cosAngle + _m4storage[9] * -sinAngle; final double t3 = _m4storage[2] * cosAngle + _m4storage[10] * -sinAngle; final double t4 = _m4storage[3] * cosAngle + _m4storage[11] * -sinAngle; final double t5 = _m4storage[0] * sinAngle + _m4storage[8] * cosAngle; final double t6 = _m4storage[1] * sinAngle + _m4storage[9] * cosAngle; final double t7 = _m4storage[2] * sinAngle + _m4storage[10] * cosAngle; final double t8 = _m4storage[3] * sinAngle + _m4storage[11] * cosAngle; _m4storage[0] = t1; _m4storage[1] = t2; _m4storage[2] = t3; _m4storage[3] = t4; _m4storage[8] = t5; _m4storage[9] = t6; _m4storage[10] = t7; _m4storage[11] = t8; } /** * Rotate this matrix [angle] radians around Z */ public void rotateZ(double angle) { final double cosAngle = Math.cos(angle); final double sinAngle = Math.sin(angle); final double t1 = _m4storage[0] * cosAngle + _m4storage[4] * sinAngle; final double t2 = _m4storage[1] * cosAngle + _m4storage[5] * sinAngle; final double t3 = _m4storage[2] * cosAngle + _m4storage[6] * sinAngle; final double t4 = _m4storage[3] * cosAngle + _m4storage[7] * sinAngle; final double t5 = _m4storage[0] * -sinAngle + _m4storage[4] * cosAngle; final double t6 = _m4storage[1] * -sinAngle + _m4storage[5] * cosAngle; final double t7 = _m4storage[2] * -sinAngle + _m4storage[6] * cosAngle; final double t8 = _m4storage[3] * -sinAngle + _m4storage[7] * cosAngle; _m4storage[0] = t1; _m4storage[1] = t2; _m4storage[2] = t3; _m4storage[3] = t4; _m4storage[4] = t5; _m4storage[5] = t6; _m4storage[6] = t7; _m4storage[7] = t8; } /** * Scale this matrix by a [Vector3], [Vector4], or x,y,z */ public void scale(double sx) { scale(sx, sx, sx); } public void scale(Vector3 v) { scale(v.getX(), v.getY(), v.getZ()); } public void scale(Vector4 v) { scale(v.getX(), v.getY(), v.getZ(), v.getW()); } public void scale(double sx, double sy, double sz) { scale(sx, sy, sz, 1.0); } public void scale(double sx, double sy, double sz, double sw) { _m4storage[0] *= sx; _m4storage[1] *= sx; _m4storage[2] *= sx; _m4storage[3] *= sx; _m4storage[4] *= sy; _m4storage[5] *= sy; _m4storage[6] *= sy; _m4storage[7] *= sy; _m4storage[8] *= sz; _m4storage[9] *= sz; _m4storage[10] *= sz; _m4storage[11] *= sz; _m4storage[12] *= sw; _m4storage[13] *= sw; _m4storage[14] *= sw; _m4storage[15] *= sw; } /** * Create a copy of [this] scaled by a [Vector3], [Vector4] or [x],[y], and * [z]. */ public Matrix4 scaled(double x) { return scaled(x, 1, 1); } public Matrix4 scaled(double x, double y) { return scaled(x, y, 1); } public Matrix4 scaled(double x, double y, double z) { final Matrix4 ret = clone(); ret.scale(x, y, z); return ret; } /** * Zeros [this]. */ public void setZero() { _m4storage[0] = 0.0; _m4storage[1] = 0.0; _m4storage[2] = 0.0; _m4storage[3] = 0.0; _m4storage[4] = 0.0; _m4storage[5] = 0.0; _m4storage[6] = 0.0; _m4storage[7] = 0.0; _m4storage[8] = 0.0; _m4storage[9] = 0.0; _m4storage[10] = 0.0; _m4storage[11] = 0.0; _m4storage[12] = 0.0; _m4storage[13] = 0.0; _m4storage[14] = 0.0; _m4storage[15] = 0.0; } /** * Makes [this] into the identity matrix. */ void setIdentity() { _m4storage[0] = 1.0; _m4storage[1] = 0.0; _m4storage[2] = 0.0; _m4storage[3] = 0.0; _m4storage[4] = 0.0; _m4storage[5] = 1.0; _m4storage[6] = 0.0; _m4storage[7] = 0.0; _m4storage[8] = 0.0; _m4storage[9] = 0.0; _m4storage[10] = 1.0; _m4storage[11] = 0.0; _m4storage[12] = 0.0; _m4storage[13] = 0.0; _m4storage[14] = 0.0; _m4storage[15] = 1.0; } /** * Returns the tranpose of this. */ public Matrix4 transposed() { final Matrix4 ret = clone(); ret.transpose(); return ret; } public void transpose() { double temp; temp = _m4storage[4]; _m4storage[4] = _m4storage[1]; _m4storage[1] = temp; temp = _m4storage[8]; _m4storage[8] = _m4storage[2]; _m4storage[2] = temp; temp = _m4storage[12]; _m4storage[12] = _m4storage[3]; _m4storage[3] = temp; temp = _m4storage[9]; _m4storage[9] = _m4storage[6]; _m4storage[6] = temp; temp = _m4storage[13]; _m4storage[13] = _m4storage[7]; _m4storage[7] = temp; temp = _m4storage[14]; _m4storage[14] = _m4storage[11]; _m4storage[11] = temp; } /** * Returns the component wise absolute value of this. */ public Matrix4 absolute() { final Matrix4 r = new Matrix4(); final double[] rStorage = r._m4storage; rStorage[0] = Math.abs(_m4storage[0]); rStorage[1] = Math.abs(_m4storage[1]); rStorage[2] = Math.abs(_m4storage[2]); rStorage[3] = Math.abs(_m4storage[3]); rStorage[4] = Math.abs(_m4storage[4]); rStorage[5] = Math.abs(_m4storage[5]); rStorage[6] = Math.abs(_m4storage[6]); rStorage[7] = Math.abs(_m4storage[7]); rStorage[8] = Math.abs(_m4storage[8]); rStorage[9] = Math.abs(_m4storage[9]); rStorage[10] = Math.abs(_m4storage[10]); rStorage[11] = Math.abs(_m4storage[11]); rStorage[12] = Math.abs(_m4storage[12]); rStorage[13] = Math.abs(_m4storage[13]); rStorage[14] = Math.abs(_m4storage[14]); rStorage[15] = Math.abs(_m4storage[15]); return r; } /** * Returns the determinant of this matrix. */ public double determinant() { final double det2_01_01 = _m4storage[0] * _m4storage[5] - _m4storage[1] * _m4storage[4]; final double det2_01_02 = _m4storage[0] * _m4storage[6] - _m4storage[2] * _m4storage[4]; final double det2_01_03 = _m4storage[0] * _m4storage[7] - _m4storage[3] * _m4storage[4]; final double det2_01_12 = _m4storage[1] * _m4storage[6] - _m4storage[2] * _m4storage[5]; final double det2_01_13 = _m4storage[1] * _m4storage[7] - _m4storage[3] * _m4storage[5]; final double det2_01_23 = _m4storage[2] * _m4storage[7] - _m4storage[3] * _m4storage[6]; final double det3_201_012 = _m4storage[8] * det2_01_12 - _m4storage[9] * det2_01_02 + _m4storage[10] * det2_01_01; final double det3_201_013 = _m4storage[8] * det2_01_13 - _m4storage[9] * det2_01_03 + _m4storage[11] * det2_01_01; final double det3_201_023 = _m4storage[8] * det2_01_23 - _m4storage[10] * det2_01_03 + _m4storage[11] * det2_01_02; final double det3_201_123 = _m4storage[9] * det2_01_23 - _m4storage[10] * det2_01_13 + _m4storage[11] * det2_01_12; return -det3_201_123 * _m4storage[12] + det3_201_023 * _m4storage[13] - det3_201_013 * _m4storage[14] + det3_201_012 * _m4storage[15]; } /** * Returns the dot product of row [i] and [v]. */ public double dotRow(int i, Vector4 v) { final double[] vStorage = v._v4storage; return _m4storage[i] * vStorage[0] + _m4storage[4 + i] * vStorage[1] + _m4storage[8 + i] * vStorage[2] + _m4storage[12 + i] * vStorage[3]; } /** * Returns the dot product of column [j] and [v]. */ public double dotColumn(int j, Vector4 v) { final double[] vStorage = v._v4storage; return _m4storage[j * 4] * vStorage[0] + _m4storage[j * 4 + 1] * vStorage[1] + _m4storage[j * 4 + 2] * vStorage[2] + _m4storage[j * 4 + 3] * vStorage[3]; } /** * Returns the trace of the matrix. The trace of a matrix is the sum of the * diagonal entries. */ public double trace() { double t = 0.0; t += _m4storage[0]; t += _m4storage[5]; t += _m4storage[10]; t += _m4storage[15]; return t; } /** * Returns infinity norm of the matrix. Used for numerical analysis. */ public double infinityNorm() { double norm = 0.0; { double row_norm = 0.0; row_norm += Math.abs(_m4storage[0]); row_norm += Math.abs(_m4storage[1]); row_norm += Math.abs(_m4storage[2]); row_norm += Math.abs(_m4storage[3]); norm = Math.max(row_norm, norm); } { double row_norm = 0.0; row_norm += Math.abs(_m4storage[4]); row_norm += Math.abs(_m4storage[5]); row_norm += Math.abs(_m4storage[6]); row_norm += Math.abs(_m4storage[7]); norm = Math.max(row_norm, norm); } { double row_norm = 0.0; row_norm += Math.abs(_m4storage[8]); row_norm += Math.abs(_m4storage[9]); row_norm += Math.abs(_m4storage[10]); row_norm += Math.abs(_m4storage[11]); norm = Math.max(row_norm, norm); } { double row_norm = 0.0; row_norm += Math.abs(_m4storage[12]); row_norm += Math.abs(_m4storage[13]); row_norm += Math.abs(_m4storage[14]); row_norm += Math.abs(_m4storage[15]); norm = Math.max(row_norm, norm); } return norm; } /** * Returns relative error between [this] and [correct] */ public double relativeError(Matrix4 correct) { final Matrix4 diff = correct.operatorSub(this); final double correct_norm = correct.infinityNorm(); final double diff_norm = diff.infinityNorm(); return diff_norm / correct_norm; } /** * Returns absolute error between [this] and [correct] */ public double absoluteError(Matrix4 correct) { final double this_norm = infinityNorm(); final double correct_norm = correct.infinityNorm(); final double diff_norm = Math.abs(this_norm - correct_norm); return diff_norm; } /** * Returns the translation vector from this homogeneous transformation matrix. */ public Vector3 getTranslation() { final double z = _m4storage[14]; final double y = _m4storage[13]; final double x = _m4storage[12]; return new Vector3(x, y, z); } /** * Sets the translation vector in this homogeneous transformation matrix. */ public void setTranslation(Vector3 t) { final double[] tStorage = t._v3storage; final double z = tStorage[2]; final double y = tStorage[1]; final double x = tStorage[0]; _m4storage[14] = z; _m4storage[13] = y; _m4storage[12] = x; } /** * Sets the translation vector in this homogeneous transformation matrix. */ public void setTranslationRaw(double x, double y, double z) { _m4storage[14] = z; _m4storage[13] = y; _m4storage[12] = x; } /** * Returns the max scale value of the 3 axes. */ public double getMaxScaleOnAxis() { final double scaleXSq = _m4storage[0] * _m4storage[0] + _m4storage[1] * _m4storage[1] + _m4storage[2] * _m4storage[2]; final double scaleYSq = _m4storage[4] * _m4storage[4] + _m4storage[5] * _m4storage[5] + _m4storage[6] * _m4storage[6]; final double scaleZSq = _m4storage[8] * _m4storage[8] + _m4storage[9] * _m4storage[9] + _m4storage[10] * _m4storage[10]; return Math.sqrt(Math.max(scaleXSq, Math.max(scaleYSq, scaleZSq))); } /** * Transposes just the upper 3x3 rotation matrix. */ public void transposeRotation() { double temp; temp = _m4storage[1]; _m4storage[1] = _m4storage[4]; _m4storage[4] = temp; temp = _m4storage[2]; _m4storage[2] = _m4storage[8]; _m4storage[8] = temp; temp = _m4storage[4]; _m4storage[4] = _m4storage[1]; _m4storage[1] = temp; temp = _m4storage[6]; _m4storage[6] = _m4storage[9]; _m4storage[9] = temp; temp = _m4storage[8]; _m4storage[8] = _m4storage[2]; _m4storage[2] = temp; temp = _m4storage[9]; _m4storage[9] = _m4storage[6]; _m4storage[6] = temp; } /** * Invert [this]. */ public double invert() { return copyInverse(this); } /** * Set this matrix to be the inverse of [arg] */ public double copyInverse(Matrix4 arg) { final double[] argStorage = arg._m4storage; final double a00 = argStorage[0]; final double a01 = argStorage[1]; final double a02 = argStorage[2]; final double a03 = argStorage[3]; final double a10 = argStorage[4]; final double a11 = argStorage[5]; final double a12 = argStorage[6]; final double a13 = argStorage[7]; final double a20 = argStorage[8]; final double a21 = argStorage[9]; final double a22 = argStorage[10]; final double a23 = argStorage[11]; final double a30 = argStorage[12]; final double a31 = argStorage[13]; final double a32 = argStorage[14]; final double a33 = argStorage[15]; final double b00 = a00 * a11 - a01 * a10; final double b01 = a00 * a12 - a02 * a10; final double b02 = a00 * a13 - a03 * a10; final double b03 = a01 * a12 - a02 * a11; final double b04 = a01 * a13 - a03 * a11; final double b05 = a02 * a13 - a03 * a12; final double b06 = a20 * a31 - a21 * a30; final double b07 = a20 * a32 - a22 * a30; final double b08 = a20 * a33 - a23 * a30; final double b09 = a21 * a32 - a22 * a31; final double b10 = a21 * a33 - a23 * a31; final double b11 = a22 * a33 - a23 * a32; final double det = (b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06); if (det == 0.0) { setFrom(arg); return 0.0; } final double invDet = 1.0 / det; _m4storage[0] = (a11 * b11 - a12 * b10 + a13 * b09) * invDet; _m4storage[1] = (-a01 * b11 + a02 * b10 - a03 * b09) * invDet; _m4storage[2] = (a31 * b05 - a32 * b04 + a33 * b03) * invDet; _m4storage[3] = (-a21 * b05 + a22 * b04 - a23 * b03) * invDet; _m4storage[4] = (-a10 * b11 + a12 * b08 - a13 * b07) * invDet; _m4storage[5] = (a00 * b11 - a02 * b08 + a03 * b07) * invDet; _m4storage[6] = (-a30 * b05 + a32 * b02 - a33 * b01) * invDet; _m4storage[7] = (a20 * b05 - a22 * b02 + a23 * b01) * invDet; _m4storage[8] = (a10 * b10 - a11 * b08 + a13 * b06) * invDet; _m4storage[9] = (-a00 * b10 + a01 * b08 - a03 * b06) * invDet; _m4storage[10] = (a30 * b04 - a31 * b02 + a33 * b00) * invDet; _m4storage[11] = (-a20 * b04 + a21 * b02 - a23 * b00) * invDet; _m4storage[12] = (-a10 * b09 + a11 * b07 - a12 * b06) * invDet; _m4storage[13] = (a00 * b09 - a01 * b07 + a02 * b06) * invDet; _m4storage[14] = (-a30 * b03 + a31 * b01 - a32 * b00) * invDet; _m4storage[15] = (a20 * b03 - a21 * b01 + a22 * b00) * invDet; return det; } public double invertRotation() { final double det = determinant(); if (det == 0.0) { return 0.0; } final double invDet = 1.0 / det; final double ix; final double iy; final double iz; final double jx; final double jy; final double jz; final double kx; final double ky; final double kz; ix = invDet * (_m4storage[5] * _m4storage[10] - _m4storage[6] * _m4storage[9]); iy = invDet * (_m4storage[2] * _m4storage[9] - _m4storage[1] * _m4storage[10]); iz = invDet * (_m4storage[1] * _m4storage[6] - _m4storage[2] * _m4storage[5]); jx = invDet * (_m4storage[6] * _m4storage[8] - _m4storage[4] * _m4storage[10]); jy = invDet * (_m4storage[0] * _m4storage[10] - _m4storage[2] * _m4storage[8]); jz = invDet * (_m4storage[2] * _m4storage[4] - _m4storage[0] * _m4storage[6]); kx = invDet * (_m4storage[4] * _m4storage[9] - _m4storage[5] * _m4storage[8]); ky = invDet * (_m4storage[1] * _m4storage[8] - _m4storage[0] * _m4storage[9]); kz = invDet * (_m4storage[0] * _m4storage[5] - _m4storage[1] * _m4storage[4]); _m4storage[0] = ix; _m4storage[1] = iy; _m4storage[2] = iz; _m4storage[4] = jx; _m4storage[5] = jy; _m4storage[6] = jz; _m4storage[8] = kx; _m4storage[9] = ky; _m4storage[10] = kz; return det; } /** * Sets the upper 3x3 to a rotation of [radians] around X */ public void setRotationX(double radians) { final double c = Math.cos(radians); final double s = Math.sin(radians); _m4storage[0] = 1.0; _m4storage[1] = 0.0; _m4storage[2] = 0.0; _m4storage[4] = 0.0; _m4storage[5] = c; _m4storage[6] = s; _m4storage[8] = 0.0; _m4storage[9] = -s; _m4storage[10] = c; _m4storage[3] = 0.0; _m4storage[7] = 0.0; _m4storage[11] = 0.0; } /** * Sets the upper 3x3 to a rotation of [radians] around Y */ public void setRotationY(double radians) { final double c = Math.cos(radians); final double s = Math.sin(radians); _m4storage[0] = c; _m4storage[1] = 0.0; _m4storage[2] = -s; _m4storage[4] = 0.0; _m4storage[5] = 1.0; _m4storage[6] = 0.0; _m4storage[8] = s; _m4storage[9] = 0.0; _m4storage[10] = c; _m4storage[3] = 0.0; _m4storage[7] = 0.0; _m4storage[11] = 0.0; } /** * Sets the upper 3x3 to a rotation of [radians] around Z */ public void setRotationZ(double radians) { final double c = Math.cos(radians); final double s = Math.sin(radians); _m4storage[0] = c; _m4storage[1] = s; _m4storage[2] = 0.0; _m4storage[4] = -s; _m4storage[5] = c; _m4storage[6] = 0.0; _m4storage[8] = 0.0; _m4storage[9] = 0.0; _m4storage[10] = 1.0; _m4storage[3] = 0.0; _m4storage[7] = 0.0; _m4storage[11] = 0.0; } /** * Converts into Adjugate matrix and scales by [scale] */ public void scaleAdjoint(double scale) { // Adapted from code by Richard Carling. final double a1 = _m4storage[0]; final double b1 = _m4storage[4]; final double c1 = _m4storage[8]; final double d1 = _m4storage[12]; final double a2 = _m4storage[1]; final double b2 = _m4storage[5]; final double c2 = _m4storage[9]; final double d2 = _m4storage[13]; final double a3 = _m4storage[2]; final double b3 = _m4storage[6]; final double c3 = _m4storage[10]; final double d3 = _m4storage[14]; final double a4 = _m4storage[3]; final double b4 = _m4storage[7]; final double c4 = _m4storage[11]; final double d4 = _m4storage[15]; _m4storage[0] = (b2 * (c3 * d4 - c4 * d3) - c2 * (b3 * d4 - b4 * d3) + d2 * (b3 * c4 - b4 * c3)) * scale; _m4storage[1] = -(a2 * (c3 * d4 - c4 * d3) - c2 * (a3 * d4 - a4 * d3) + d2 * (a3 * c4 - a4 * c3)) * scale; _m4storage[2] = (a2 * (b3 * d4 - b4 * d3) - b2 * (a3 * d4 - a4 * d3) + d2 * (a3 * b4 - a4 * b3)) * scale; _m4storage[3] = -(a2 * (b3 * c4 - b4 * c3) - b2 * (a3 * c4 - a4 * c3) + c2 * (a3 * b4 - a4 * b3)) * scale; _m4storage[4] = -(b1 * (c3 * d4 - c4 * d3) - c1 * (b3 * d4 - b4 * d3) + d1 * (b3 * c4 - b4 * c3)) * scale; _m4storage[5] = (a1 * (c3 * d4 - c4 * d3) - c1 * (a3 * d4 - a4 * d3) + d1 * (a3 * c4 - a4 * c3)) * scale; _m4storage[6] = -(a1 * (b3 * d4 - b4 * d3) - b1 * (a3 * d4 - a4 * d3) + d1 * (a3 * b4 - a4 * b3)) * scale; _m4storage[7] = (a1 * (b3 * c4 - b4 * c3) - b1 * (a3 * c4 - a4 * c3) + c1 * (a3 * b4 - a4 * b3)) * scale; _m4storage[8] = (b1 * (c2 * d4 - c4 * d2) - c1 * (b2 * d4 - b4 * d2) + d1 * (b2 * c4 - b4 * c2)) * scale; _m4storage[9] = -(a1 * (c2 * d4 - c4 * d2) - c1 * (a2 * d4 - a4 * d2) + d1 * (a2 * c4 - a4 * c2)) * scale; _m4storage[10] = (a1 * (b2 * d4 - b4 * d2) - b1 * (a2 * d4 - a4 * d2) + d1 * (a2 * b4 - a4 * b2)) * scale; _m4storage[11] = -(a1 * (b2 * c4 - b4 * c2) - b1 * (a2 * c4 - a4 * c2) + c1 * (a2 * b4 - a4 * b2)) * scale; _m4storage[12] = -(b1 * (c2 * d3 - c3 * d2) - c1 * (b2 * d3 - b3 * d2) + d1 * (b2 * c3 - b3 * c2)) * scale; _m4storage[13] = (a1 * (c2 * d3 - c3 * d2) - c1 * (a2 * d3 - a3 * d2) + d1 * (a2 * c3 - a3 * c2)) * scale; _m4storage[14] = -(a1 * (b2 * d3 - b3 * d2) - b1 * (a2 * d3 - a3 * d2) + d1 * (a2 * b3 - a3 * b2)) * scale; _m4storage[15] = (a1 * (b2 * c3 - b3 * c2) - b1 * (a2 * c3 - a3 * c2) + c1 * (a2 * b3 - a3 * b2)) * scale; } /** * Rotates [arg] by the absolute rotation of [this] * Returns [arg]. * Primarily used by AABB transformation code. */ public Vector3 absoluteRotate(Vector3 arg) { final double m00 = Math.abs(_m4storage[0]); final double m01 = Math.abs(_m4storage[4]); final double m02 = Math.abs(_m4storage[8]); final double m10 = Math.abs(_m4storage[1]); final double m11 = Math.abs(_m4storage[5]); final double m12 = Math.abs(_m4storage[9]); final double m20 = Math.abs(_m4storage[2]); final double m21 = Math.abs(_m4storage[6]); final double m22 = Math.abs(_m4storage[10]); final double[] argStorage = arg._v3storage; final double x = argStorage[0]; final double y = argStorage[1]; final double z = argStorage[2]; argStorage[0] = x * m00 + y * m01 + z * m02 + 0.0 * 0.0; argStorage[1] = x * m10 + y * m11 + z * m12 + 0.0 * 0.0; argStorage[2] = x * m20 + y * m21 + z * m22 + 0.0 * 0.0; return arg; } /** * Adds [o] to [this]. */ public void add(Matrix4 o) { final double[] oStorage = o._m4storage; _m4storage[0] = _m4storage[0] + oStorage[0]; _m4storage[1] = _m4storage[1] + oStorage[1]; _m4storage[2] = _m4storage[2] + oStorage[2]; _m4storage[3] = _m4storage[3] + oStorage[3]; _m4storage[4] = _m4storage[4] + oStorage[4]; _m4storage[5] = _m4storage[5] + oStorage[5]; _m4storage[6] = _m4storage[6] + oStorage[6]; _m4storage[7] = _m4storage[7] + oStorage[7]; _m4storage[8] = _m4storage[8] + oStorage[8]; _m4storage[9] = _m4storage[9] + oStorage[9]; _m4storage[10] = _m4storage[10] + oStorage[10]; _m4storage[11] = _m4storage[11] + oStorage[11]; _m4storage[12] = _m4storage[12] + oStorage[12]; _m4storage[13] = _m4storage[13] + oStorage[13]; _m4storage[14] = _m4storage[14] + oStorage[14]; _m4storage[15] = _m4storage[15] + oStorage[15]; } /** * Subtracts [o] from [this]. */ public void sub(Matrix4 o) { final double[] oStorage = o._m4storage; _m4storage[0] = _m4storage[0] - oStorage[0]; _m4storage[1] = _m4storage[1] - oStorage[1]; _m4storage[2] = _m4storage[2] - oStorage[2]; _m4storage[3] = _m4storage[3] - oStorage[3]; _m4storage[4] = _m4storage[4] - oStorage[4]; _m4storage[5] = _m4storage[5] - oStorage[5]; _m4storage[6] = _m4storage[6] - oStorage[6]; _m4storage[7] = _m4storage[7] - oStorage[7]; _m4storage[8] = _m4storage[8] - oStorage[8]; _m4storage[9] = _m4storage[9] - oStorage[9]; _m4storage[10] = _m4storage[10] - oStorage[10]; _m4storage[11] = _m4storage[11] - oStorage[11]; _m4storage[12] = _m4storage[12] - oStorage[12]; _m4storage[13] = _m4storage[13] - oStorage[13]; _m4storage[14] = _m4storage[14] - oStorage[14]; _m4storage[15] = _m4storage[15] - oStorage[15]; } /** * Negate [this]. */ public void negate() { _m4storage[0] = -_m4storage[0]; _m4storage[1] = -_m4storage[1]; _m4storage[2] = -_m4storage[2]; _m4storage[3] = -_m4storage[3]; _m4storage[4] = -_m4storage[4]; _m4storage[5] = -_m4storage[5]; _m4storage[6] = -_m4storage[6]; _m4storage[7] = -_m4storage[7]; _m4storage[8] = -_m4storage[8]; _m4storage[9] = -_m4storage[9]; _m4storage[10] = -_m4storage[10]; _m4storage[11] = -_m4storage[11]; _m4storage[12] = -_m4storage[12]; _m4storage[13] = -_m4storage[13]; _m4storage[14] = -_m4storage[14]; _m4storage[15] = -_m4storage[15]; } /** * Multiply [this] by [arg]. */ public void multiply(Matrix4 arg) { final double m00 = _m4storage[0]; final double m01 = _m4storage[4]; final double m02 = _m4storage[8]; final double m03 = _m4storage[12]; final double m10 = _m4storage[1]; final double m11 = _m4storage[5]; final double m12 = _m4storage[9]; final double m13 = _m4storage[13]; final double m20 = _m4storage[2]; final double m21 = _m4storage[6]; final double m22 = _m4storage[10]; final double m23 = _m4storage[14]; final double m30 = _m4storage[3]; final double m31 = _m4storage[7]; final double m32 = _m4storage[11]; final double m33 = _m4storage[15]; final double[] argStorage = arg._m4storage; final double n00 = argStorage[0]; final double n01 = argStorage[4]; final double n02 = argStorage[8]; final double n03 = argStorage[12]; final double n10 = argStorage[1]; final double n11 = argStorage[5]; final double n12 = argStorage[9]; final double n13 = argStorage[13]; final double n20 = argStorage[2]; final double n21 = argStorage[6]; final double n22 = argStorage[10]; final double n23 = argStorage[14]; final double n30 = argStorage[3]; final double n31 = argStorage[7]; final double n32 = argStorage[11]; final double n33 = argStorage[15]; _m4storage[0] = (m00 * n00) + (m01 * n10) + (m02 * n20) + (m03 * n30); _m4storage[4] = (m00 * n01) + (m01 * n11) + (m02 * n21) + (m03 * n31); _m4storage[8] = (m00 * n02) + (m01 * n12) + (m02 * n22) + (m03 * n32); _m4storage[12] = (m00 * n03) + (m01 * n13) + (m02 * n23) + (m03 * n33); _m4storage[1] = (m10 * n00) + (m11 * n10) + (m12 * n20) + (m13 * n30); _m4storage[5] = (m10 * n01) + (m11 * n11) + (m12 * n21) + (m13 * n31); _m4storage[9] = (m10 * n02) + (m11 * n12) + (m12 * n22) + (m13 * n32); _m4storage[13] = (m10 * n03) + (m11 * n13) + (m12 * n23) + (m13 * n33); _m4storage[2] = (m20 * n00) + (m21 * n10) + (m22 * n20) + (m23 * n30); _m4storage[6] = (m20 * n01) + (m21 * n11) + (m22 * n21) + (m23 * n31); _m4storage[10] = (m20 * n02) + (m21 * n12) + (m22 * n22) + (m23 * n32); _m4storage[14] = (m20 * n03) + (m21 * n13) + (m22 * n23) + (m23 * n33); _m4storage[3] = (m30 * n00) + (m31 * n10) + (m32 * n20) + (m33 * n30); _m4storage[7] = (m30 * n01) + (m31 * n11) + (m32 * n21) + (m33 * n31); _m4storage[11] = (m30 * n02) + (m31 * n12) + (m32 * n22) + (m33 * n32); _m4storage[15] = (m30 * n03) + (m31 * n13) + (m32 * n23) + (m33 * n33); } /** * Multiply a copy of [this] with [arg]. */ public Matrix4 multiplied(Matrix4 arg) { final Matrix4 ret = clone(); ret.multiply(arg); return ret; } /** * Multiply a transposed [this] with [arg]. */ public void transposeMultiply(Matrix4 arg) { final double m00 = _m4storage[0]; final double m01 = _m4storage[1]; final double m02 = _m4storage[2]; final double m03 = _m4storage[3]; final double m10 = _m4storage[4]; final double m11 = _m4storage[5]; final double m12 = _m4storage[6]; final double m13 = _m4storage[7]; final double m20 = _m4storage[8]; final double m21 = _m4storage[9]; final double m22 = _m4storage[10]; final double m23 = _m4storage[11]; final double m30 = _m4storage[12]; final double m31 = _m4storage[13]; final double m32 = _m4storage[14]; final double m33 = _m4storage[15]; final double[] argStorage = arg._m4storage; _m4storage[0] = (m00 * argStorage[0]) + (m01 * argStorage[1]) + (m02 * argStorage[2]) + (m03 * argStorage[3]); _m4storage[4] = (m00 * argStorage[4]) + (m01 * argStorage[5]) + (m02 * argStorage[6]) + (m03 * argStorage[7]); _m4storage[8] = (m00 * argStorage[8]) + (m01 * argStorage[9]) + (m02 * argStorage[10]) + (m03 * argStorage[11]); _m4storage[12] = (m00 * argStorage[12]) + (m01 * argStorage[13]) + (m02 * argStorage[14]) + (m03 * argStorage[15]); _m4storage[1] = (m10 * argStorage[0]) + (m11 * argStorage[1]) + (m12 * argStorage[2]) + (m13 * argStorage[3]); _m4storage[5] = (m10 * argStorage[4]) + (m11 * argStorage[5]) + (m12 * argStorage[6]) + (m13 * argStorage[7]); _m4storage[9] = (m10 * argStorage[8]) + (m11 * argStorage[9]) + (m12 * argStorage[10]) + (m13 * argStorage[11]); _m4storage[13] = (m10 * argStorage[12]) + (m11 * argStorage[13]) + (m12 * argStorage[14]) + (m13 * argStorage[15]); _m4storage[2] = (m20 * argStorage[0]) + (m21 * argStorage[1]) + (m22 * argStorage[2]) + (m23 * argStorage[3]); _m4storage[6] = (m20 * argStorage[4]) + (m21 * argStorage[5]) + (m22 * argStorage[6]) + (m23 * argStorage[7]); _m4storage[10] = (m20 * argStorage[8]) + (m21 * argStorage[9]) + (m22 * argStorage[10]) + (m23 * argStorage[11]); _m4storage[14] = (m20 * argStorage[12]) + (m21 * argStorage[13]) + (m22 * argStorage[14]) + (m23 * argStorage[15]); _m4storage[3] = (m30 * argStorage[0]) + (m31 * argStorage[1]) + (m32 * argStorage[2]) + (m33 * argStorage[3]); _m4storage[7] = (m30 * argStorage[4]) + (m31 * argStorage[5]) + (m32 * argStorage[6]) + (m33 * argStorage[7]); _m4storage[11] = (m30 * argStorage[8]) + (m31 * argStorage[9]) + (m32 * argStorage[10]) + (m33 * argStorage[11]); _m4storage[15] = (m30 * argStorage[12]) + (m31 * argStorage[13]) + (m32 * argStorage[14]) + (m33 * argStorage[15]); } /** * Multiply [this] with a transposed [arg]. */ public void multiplyTranspose(Matrix4 arg) { final double m00 = _m4storage[0]; final double m01 = _m4storage[4]; final double m02 = _m4storage[8]; final double m03 = _m4storage[12]; final double m10 = _m4storage[1]; final double m11 = _m4storage[5]; final double m12 = _m4storage[9]; final double m13 = _m4storage[13]; final double m20 = _m4storage[2]; final double m21 = _m4storage[6]; final double m22 = _m4storage[10]; final double m23 = _m4storage[14]; final double m30 = _m4storage[3]; final double m31 = _m4storage[7]; final double m32 = _m4storage[11]; final double m33 = _m4storage[15]; final double[] argStorage = arg._m4storage; _m4storage[0] = (m00 * argStorage[0]) + (m01 * argStorage[4]) + (m02 * argStorage[8]) + (m03 * argStorage[12]); _m4storage[4] = (m00 * argStorage[1]) + (m01 * argStorage[5]) + (m02 * argStorage[9]) + (m03 * argStorage[13]); _m4storage[8] = (m00 * argStorage[2]) + (m01 * argStorage[6]) + (m02 * argStorage[10]) + (m03 * argStorage[14]); _m4storage[12] = (m00 * argStorage[3]) + (m01 * argStorage[7]) + (m02 * argStorage[11]) + (m03 * argStorage[15]); _m4storage[1] = (m10 * argStorage[0]) + (m11 * argStorage[4]) + (m12 * argStorage[8]) + (m13 * argStorage[12]); _m4storage[5] = (m10 * argStorage[1]) + (m11 * argStorage[5]) + (m12 * argStorage[9]) + (m13 * argStorage[13]); _m4storage[9] = (m10 * argStorage[2]) + (m11 * argStorage[6]) + (m12 * argStorage[10]) + (m13 * argStorage[14]); _m4storage[13] = (m10 * argStorage[3]) + (m11 * argStorage[7]) + (m12 * argStorage[11]) + (m13 * argStorage[15]); _m4storage[2] = (m20 * argStorage[0]) + (m21 * argStorage[4]) + (m22 * argStorage[8]) + (m23 * argStorage[12]); _m4storage[6] = (m20 * argStorage[1]) + (m21 * argStorage[5]) + (m22 * argStorage[9]) + (m23 * argStorage[13]); _m4storage[10] = (m20 * argStorage[2]) + (m21 * argStorage[6]) + (m22 * argStorage[10]) + (m23 * argStorage[14]); _m4storage[14] = (m20 * argStorage[3]) + (m21 * argStorage[7]) + (m22 * argStorage[11]) + (m23 * argStorage[15]); _m4storage[3] = (m30 * argStorage[0]) + (m31 * argStorage[4]) + (m32 * argStorage[8]) + (m33 * argStorage[12]); _m4storage[7] = (m30 * argStorage[1]) + (m31 * argStorage[5]) + (m32 * argStorage[9]) + (m33 * argStorage[13]); _m4storage[11] = (m30 * argStorage[2]) + (m31 * argStorage[6]) + (m32 * argStorage[10]) + (m33 * argStorage[14]); _m4storage[15] = (m30 * argStorage[3]) + (m31 * argStorage[7]) + (m32 * argStorage[11]) + (m33 * argStorage[15]); } // TODO(jacobr): this method might be worth pulling in the matrix3 class for. // Decomposes [this] into [translation], [rotation] and [scale] components. /* public void decompose(Vector3 translation, Quaternion rotation, Vector3 scale) { final Vector3 v = new Vector3(); v.setValues(_m4storage[0], _m4storage[1], _m4storage[2]); double sx = v.getLength(); v.setValues(_m4storage[4], _m4storage[5], _m4storage[6]); final double sy = v.getLength(); v.setValues(_m4storage[8], _m4storage[9], _m4storage[10]); final double sz = v.getLength(); if (determinant() < 0) { sx = -sx; } translation._v3storage[0] = _m4storage[12]; translation._v3storage[1] = _m4storage[13]; translation._v3storage[2] = _m4storage[14]; final double invSX = 1.0 / sx; final double invSY = 1.0 / sy; final double invSZ = 1.0 / sz; final Matrix4 m = Matrix4.copy(this); m._m4storage[0] *= invSX; m._m4storage[1] *= invSX; m._m4storage[2] *= invSX; m._m4storage[4] *= invSY; m._m4storage[5] *= invSY; m._m4storage[6] *= invSY; m._m4storage[8] *= invSZ; m._m4storage[9] *= invSZ; m._m4storage[10] *= invSZ; rotation.setFromRotation(m.getRotation()); scale._v3storage[0] = sx; scale._v3storage[1] = sy; scale._v3storage[2] = sz; } */ /** * Rotate [arg] of type [Vector3] using the rotation defined by [this]. */ public Vector3 rotate3(Vector3 arg) { final double[] argStorage = arg._v3storage; final double x_ = (_m4storage[0] * argStorage[0]) + (_m4storage[4] * argStorage[1]) + (_m4storage[8] * argStorage[2]); final double y_ = (_m4storage[1] * argStorage[0]) + (_m4storage[5] * argStorage[1]) + (_m4storage[9] * argStorage[2]); final double z_ = (_m4storage[2] * argStorage[0]) + (_m4storage[6] * argStorage[1]) + (_m4storage[10] * argStorage[2]); argStorage[0] = x_; argStorage[1] = y_; argStorage[2] = z_; return arg; } /** * Rotate a copy of [arg] of type [Vector3] using the rotation defined by * [this]. If a [out] parameter is supplied, the copy is stored in [out]. */ public Vector3 rotated3(Vector3 arg, Vector3 out) { if (out == null) { out = Vector3.copy(arg); } else { out.setFrom(arg); } return rotate3(out); } /** * Transform [arg] of type [Vector3] using the transformation defined by * [this]. */ public Vector3 transform3(Vector3 arg) { final double[] argStorage = arg._v3storage; final double x_ = (_m4storage[0] * argStorage[0]) + (_m4storage[4] * argStorage[1]) + (_m4storage[8] * argStorage[2]) + _m4storage[12]; final double y_ = (_m4storage[1] * argStorage[0]) + (_m4storage[5] * argStorage[1]) + (_m4storage[9] * argStorage[2]) + _m4storage[13]; final double z_ = (_m4storage[2] * argStorage[0]) + (_m4storage[6] * argStorage[1]) + (_m4storage[10] * argStorage[2]) + _m4storage[14]; argStorage[0] = x_; argStorage[1] = y_; argStorage[2] = z_; return arg; } /** * Transform a copy of [arg] of type [Vector3] using the transformation * defined by [this]. If a [out] parameter is supplied, the copy is stored in * [out]. */ public Vector3 transformed3(Vector3 arg) { return transformed3(arg, null); } public Vector3 transformed3(Vector3 arg, Vector3 out) { if (out == null) { out = Vector3.copy(arg); } else { out.setFrom(arg); } return transform3(out); } /** * Transform [arg] of type [Vector4] using the transformation defined by * [this]. */ public Vector4 transform(Vector4 arg) { final double[] argStorage = arg._v4storage; final double x_ = (_m4storage[0] * argStorage[0]) + (_m4storage[4] * argStorage[1]) + (_m4storage[8] * argStorage[2]) + (_m4storage[12] * argStorage[3]); final double y_ = (_m4storage[1] * argStorage[0]) + (_m4storage[5] * argStorage[1]) + (_m4storage[9] * argStorage[2]) + (_m4storage[13] * argStorage[3]); final double z_ = (_m4storage[2] * argStorage[0]) + (_m4storage[6] * argStorage[1]) + (_m4storage[10] * argStorage[2]) + (_m4storage[14] * argStorage[3]); final double w_ = (_m4storage[3] * argStorage[0]) + (_m4storage[7] * argStorage[1]) + (_m4storage[11] * argStorage[2]) + (_m4storage[15] * argStorage[3]); argStorage[0] = x_; argStorage[1] = y_; argStorage[2] = z_; argStorage[3] = w_; return arg; } /** * Transform [arg] of type [Vector3] using the perspective transformation * defined by [this]. */ public Vector3 perspectiveTransform(Vector3 arg) { final double[] argStorage = arg._v3storage; final double x_ = (_m4storage[0] * argStorage[0]) + (_m4storage[4] * argStorage[1]) + (_m4storage[8] * argStorage[2]) + _m4storage[12]; final double y_ = (_m4storage[1] * argStorage[0]) + (_m4storage[5] * argStorage[1]) + (_m4storage[9] * argStorage[2]) + _m4storage[13]; final double z_ = (_m4storage[2] * argStorage[0]) + (_m4storage[6] * argStorage[1]) + (_m4storage[10] * argStorage[2]) + _m4storage[14]; final double w_ = 1.0 / ((_m4storage[3] * argStorage[0]) + (_m4storage[7] * argStorage[1]) + (_m4storage[11] * argStorage[2]) + _m4storage[15]); argStorage[0] = x_ * w_; argStorage[1] = y_ * w_; argStorage[2] = z_ * w_; return arg; } /** * Transform a copy of [arg] of type [Vector4] using the transformation * defined by [this]. If a [out] parameter is supplied, the copy is stored in * [out]. */ public Vector4 transformed(Vector4 arg) { return transformed(arg, null); } public Vector4 transformed(Vector4 arg, Vector4 out) { if (out == null) { out = Vector4.copy(arg); } else { out.setFrom(arg); } return transform(out); } /** * Copies [this] into [array] starting at [offset]. */ void copyIntoArray(double[] array, int offset /*= 0*/) { final int i = offset; array[i + 15] = _m4storage[15]; array[i + 14] = _m4storage[14]; array[i + 13] = _m4storage[13]; array[i + 12] = _m4storage[12]; array[i + 11] = _m4storage[11]; array[i + 10] = _m4storage[10]; array[i + 9] = _m4storage[9]; array[i + 8] = _m4storage[8]; array[i + 7] = _m4storage[7]; array[i + 6] = _m4storage[6]; array[i + 5] = _m4storage[5]; array[i + 4] = _m4storage[4]; array[i + 3] = _m4storage[3]; array[i + 2] = _m4storage[2]; array[i + 1] = _m4storage[1]; array[i + 0] = _m4storage[0]; } /** * Copies elements from [array] into [this] starting at [offset]. */ void copyFromArray(double[] array, int offset/* = 0*/) { final int i = offset; _m4storage[15] = array[i + 15]; _m4storage[14] = array[i + 14]; _m4storage[13] = array[i + 13]; _m4storage[12] = array[i + 12]; _m4storage[11] = array[i + 11]; _m4storage[10] = array[i + 10]; _m4storage[9] = array[i + 9]; _m4storage[8] = array[i + 8]; _m4storage[7] = array[i + 7]; _m4storage[6] = array[i + 6]; _m4storage[5] = array[i + 5]; _m4storage[4] = array[i + 4]; _m4storage[3] = array[i + 3]; _m4storage[2] = array[i + 2]; _m4storage[1] = array[i + 1]; _m4storage[0] = array[i + 0]; } /** * Multiply [this] to each set of xyz values in [array] starting at [offset]. */ double[] applyToVector3Array(double[] array) { return applyToVector3Array(array, 0); } double[] applyToVector3Array(double[] array, int offset) { for (int i = 0, j = offset; i < array.length; i += 3, j += 3) { final Vector3 v = Vector3.array(array, j); v.applyMatrix4(this); array[j] = v.getStorage()[0]; array[j + 1] = v.getStorage()[1]; array[j + 2] = v.getStorage()[2]; } return array; } public Vector3 getRight() { final double x = _m4storage[0]; final double y = _m4storage[1]; final double z = _m4storage[2]; return new Vector3(x, y, z); } public Vector3 getUp() { final double x = _m4storage[4]; final double y = _m4storage[5]; final double z = _m4storage[6]; return new Vector3(x, y, z); } public Vector3 getForward() { final double x = _m4storage[8]; final double y = _m4storage[9]; final double z = _m4storage[10]; return new Vector3(x, y, z); } /** * Is [this] the identity matrix? */ public boolean isIdentity() { return _m4storage[0] == 1.0 // col 1 && _m4storage[1] == 0.0 && _m4storage[2] == 0.0 && _m4storage[3] == 0.0 && _m4storage[4] == 0.0 // col 2 && _m4storage[5] == 1.0 && _m4storage[6] == 0.0 && _m4storage[7] == 0.0 && _m4storage[8] == 0.0 // col 3 && _m4storage[9] == 0.0 && _m4storage[10] == 1.0 && _m4storage[11] == 0.0 && _m4storage[12] == 0.0 // col 4 && _m4storage[13] == 0.0 && _m4storage[14] == 0.0 && _m4storage[15] == 1.0; } /** * Is [this] the zero matrix? */ public boolean isZero() { return _m4storage[0] == 0.0 // col 1 && _m4storage[1] == 0.0 && _m4storage[2] == 0.0 && _m4storage[3] == 0.0 && _m4storage[4] == 0.0 // col 2 && _m4storage[5] == 0.0 && _m4storage[6] == 0.0 && _m4storage[7] == 0.0 && _m4storage[8] == 0.0 // col 3 && _m4storage[9] == 0.0 && _m4storage[10] == 0.0 && _m4storage[11] == 0.0 && _m4storage[12] == 0.0 // col 4 && _m4storage[13] == 0.0 && _m4storage[14] == 0.0 && _m4storage[15] == 0.0; } }
flutter-intellij/flutter-idea/src/io/flutter/utils/math/Matrix4.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/utils/math/Matrix4.java", "repo_id": "flutter-intellij", "token_count": 36240 }
527
/* * 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. */ package io.flutter.view; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.Presentation; import com.intellij.openapi.actionSystem.Toggleable; import com.intellij.openapi.application.ApplicationManager; import io.flutter.run.daemon.FlutterApp; import io.flutter.utils.EventStream; import io.flutter.utils.StreamSubscription; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; abstract class FlutterViewLocalToggleableAction extends FlutterViewAction implements Toggleable, Disposable { private boolean selected = false; private StreamSubscription<Boolean> subscription; private final EventStream<Boolean> stream; FlutterViewLocalToggleableAction(@NotNull FlutterApp app, @Nullable String text, EventStream<Boolean> stream) { super(app, text); this.stream = stream; } FlutterViewLocalToggleableAction(@NotNull FlutterApp app, @Nullable String text, @Nullable String description, @Nullable Icon icon, EventStream<Boolean> stream) { super(app, text, description, icon); this.stream = stream; } @Override public final void update(@NotNull AnActionEvent e) { // selected final boolean selected = this.isSelected(); final Presentation presentation = e.getPresentation(); presentation.putClientProperty("selected", selected); if (!app.isSessionActive()) { if (subscription != null) { subscription.dispose(); subscription = null; } e.getPresentation().setEnabled(false); return; } if (subscription == null) { subscription = stream.listen((value) -> { this.setSelected(e, value); }, true); } } @Override public void dispose() { if (subscription != null) { subscription.dispose(); subscription = null; } } @Override public void actionPerformed(@NotNull AnActionEvent event) { this.setSelected(event, !isSelected()); final Presentation presentation = event.getPresentation(); presentation.putClientProperty("selected", isSelected()); super.actionPerformed(event); } @Override protected void perform(@Nullable AnActionEvent event) { stream.setValue(selected); } public boolean isSelected() { return selected; } public void setSelected(@Nullable AnActionEvent event, boolean selected) { this.selected = selected; if (event != null) { ApplicationManager.getApplication().invokeLater(() -> this.update(event)); } } }
flutter-intellij/flutter-idea/src/io/flutter/view/FlutterViewLocalToggleableAction.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/view/FlutterViewLocalToggleableAction.java", "repo_id": "flutter-intellij", "token_count": 1030 }
528
// This code is forked from // com.intellij.openapi.actionSystem.ex.ComboBoxAction // to create a ComboBoxAction that dispays in a toolbar without a button border. // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package io.flutter.view; import com.intellij.icons.AllIcons; import com.intellij.ide.DataManager; import com.intellij.ide.HelpTooltip; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.actionSystem.ex.ComboBoxAction; import com.intellij.openapi.actionSystem.ex.CustomComponentAction; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.keymap.KeymapUtil; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.popup.JBPopup; import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.ui.popup.ListPopup; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.wm.IdeFocusManager; import com.intellij.openapi.wm.IdeFrame; import com.intellij.openapi.wm.WindowManager; import com.intellij.ui.UserActivityProviderComponent; import com.intellij.util.ui.*; import com.intellij.util.ui.accessibility.ScreenReader; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.plaf.ButtonUI; import javax.swing.plaf.basic.BasicButtonUI; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionAdapter; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; public abstract class ToolbarComboBoxAction extends AnAction implements CustomComponentAction { private static Icon myIcon = null; private static Icon myDisabledIcon = null; private static Icon myWin10ComboDropTriangleIcon = null; public static Icon getArrowIcon(boolean enabled) { // We want to use a darker icon when the combo box is enabled. return enabled ? AllIcons.General.ArrowDown : ComboBoxAction.getArrowIcon(enabled); } private boolean mySmallVariant = true; private String myPopupTitle; protected ToolbarComboBoxAction() { } @Override public void actionPerformed(@NotNull AnActionEvent e) { final Project project = e.getProject(); if (project == null) return; final JFrame frame = WindowManager.getInstance().getFrame(project); if (!(frame instanceof IdeFrame)) return; final ListPopup popup = createActionPopup(e.getDataContext(), ((IdeFrame)frame).getComponent(), null); popup.showCenteredInCurrentWindow(project); } @NotNull private ListPopup createActionPopup(@NotNull DataContext context, @NotNull JComponent component, @Nullable Runnable disposeCallback) { final DefaultActionGroup group = createPopupActionGroup(component, context); final ListPopup popup = JBPopupFactory.getInstance().createActionGroupPopup( myPopupTitle, group, context, false, shouldShowDisabledActions(), false, disposeCallback, getMaxRows(), getPreselectCondition()); popup.setMinimumSize(new Dimension(getMinWidth(), getMinHeight())); return popup; } @NotNull @Override public JComponent createCustomComponent(@NotNull Presentation presentation) { final JPanel panel = new JPanel(new GridBagLayout()); final ToolbarComboBoxButton button = createComboBoxButton(presentation); panel.add(button, new GridBagConstraints(0, 0, 1, 1, 1, 1, GridBagConstraints.CENTER, GridBagConstraints.BOTH, JBUI.insets(0, 3), 0, 0)); return panel; } protected ToolbarComboBoxButton createComboBoxButton(Presentation presentation) { return new ToolbarComboBoxButton(presentation); } public boolean isSmallVariant() { return mySmallVariant; } public void setSmallVariant(boolean smallVariant) { mySmallVariant = smallVariant; } public void setPopupTitle(String popupTitle) { myPopupTitle = popupTitle; } protected boolean shouldShowDisabledActions() { return false; } @NotNull protected abstract DefaultActionGroup createPopupActionGroup(JComponent button); @NotNull protected DefaultActionGroup createPopupActionGroup(JComponent button, @NotNull DataContext dataContext) { return createPopupActionGroup(button); } protected int getMaxRows() { return 30; } protected int getMinHeight() { return 1; } protected int getMinWidth() { return 1; } protected class ToolbarComboBoxButton extends JButton implements UserActivityProviderComponent { private final Presentation myPresentation; private boolean myForcePressed = false; private PropertyChangeListener myButtonSynchronizer; @Override public void setUI(ButtonUI ui) { // We use the BasicButtonUI so we can display a button without a // background. super.setUI(new BasicButtonUI()); } public ToolbarComboBoxButton(Presentation presentation) { myPresentation = presentation; setModel(new MyButtonModel()); getModel().setEnabled(myPresentation.isEnabled()); setVisible(presentation.isVisible()); setHorizontalAlignment(LEFT); setFocusable(ScreenReader.isActive()); setBorder(JBUI.Borders.empty()); putClientProperty("styleCombo", ToolbarComboBoxAction.this); setMargin(JBUI.insets(0, 0, 0, 2)); if (isSmallVariant()) { // TODO(jacobr): it would be better to use // JBUI.Fonts.toolbarSmallComboBoxFont but it isn't availabe in all // versions of IntelliJ we support. setFont(JBUI.Fonts.miniFont()); } addMouseListener(new MouseAdapter() { @Override public void mousePressed(final MouseEvent e) { if (SwingUtilities.isLeftMouseButton(e)) { e.consume(); doClick(); } } }); addMouseMotionListener(new MouseMotionAdapter() { @Override public void mouseDragged(MouseEvent e) { mouseMoved(MouseEventAdapter.convert(e, e.getComponent(), MouseEvent.MOUSE_MOVED, e.getWhen(), e.getModifiers() | e.getModifiersEx(), e.getX(), e.getY())); } }); } @Override protected void fireActionPerformed(ActionEvent event) { if (!myForcePressed) { IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown(this::showPopup); } } @NotNull private Runnable setForcePressed() { myForcePressed = true; repaint(); return () -> { // give the button a chance to handle action listener ApplicationManager.getApplication().invokeLater(() -> { myForcePressed = false; repaint(); }, ModalityState.any()); repaint(); fireStateChanged(); }; } @Nullable @Override public String getToolTipText() { return myForcePressed || Registry.is("ide.helptooltip.enabled") ? null : super.getToolTipText(); } public void showPopup() { final JBPopup popup = createPopup(setForcePressed()); if (Registry.is("ide.helptooltip.enabled")) { HelpTooltip.setMasterPopup(this, popup); } popup.showUnderneathOf(this); } protected JBPopup createPopup(Runnable onDispose) { return createActionPopup(getDataContext(), this, onDispose); } protected DataContext getDataContext() { return DataManager.getInstance().getDataContext(this); } @Override public void removeNotify() { if (myButtonSynchronizer != null) { myPresentation.removePropertyChangeListener(myButtonSynchronizer); myButtonSynchronizer = null; } super.removeNotify(); } @Override public void addNotify() { super.addNotify(); if (myButtonSynchronizer == null) { myButtonSynchronizer = new MyButtonSynchronizer(); myPresentation.addPropertyChangeListener(myButtonSynchronizer); } initButton(); } private void initButton() { setIcon(myPresentation.getIcon()); setText(myPresentation.getText()); updateTooltipText(myPresentation.getDescription()); updateButtonSize(); } private void updateTooltipText(String description) { final String tooltip = KeymapUtil.createTooltipText(description, ToolbarComboBoxAction.this); if (Registry.is("ide.helptooltip.enabled") && StringUtil.isNotEmpty(tooltip)) { HelpTooltip.dispose(this); new HelpTooltip().setDescription(tooltip).setLocation(HelpTooltip.Alignment.BOTTOM).installOn(this); } else { setToolTipText(!tooltip.isEmpty() ? tooltip : null); } } protected class MyButtonModel extends DefaultButtonModel { @Override public boolean isPressed() { return myForcePressed || super.isPressed(); } @Override public boolean isArmed() { return myForcePressed || super.isArmed(); } } private class MyButtonSynchronizer implements PropertyChangeListener { @Override public void propertyChange(PropertyChangeEvent evt) { final String propertyName = evt.getPropertyName(); if (Presentation.PROP_TEXT.equals(propertyName)) { setText((String)evt.getNewValue()); updateButtonSize(); } else if (Presentation.PROP_DESCRIPTION.equals(propertyName)) { updateTooltipText((String)evt.getNewValue()); } else if (Presentation.PROP_ICON.equals(propertyName)) { setIcon((Icon)evt.getNewValue()); updateButtonSize(); } else if (Presentation.PROP_ENABLED.equals(propertyName)) { setEnabled((Boolean)evt.getNewValue()); } } } @Override public boolean isOpaque() { return !isSmallVariant(); } @Override public int getIconTextGap() { return 0; } @Override public Dimension getPreferredSize() { final Dimension prefSize = super.getPreferredSize(); final int width = prefSize.width + (myPresentation != null && isArrowVisible(myPresentation) ? getArrowIcon(isEnabled()).getIconWidth() : 0) + (StringUtil.isNotEmpty(getText()) ? getIconTextGap() : 0) + (UIUtil.isUnderWin10LookAndFeel() ? JBUI.scale(6) : 0); final Dimension size = new Dimension(width, isSmallVariant() ? JBUI.scale(24) : Math.max(JBUI.scale(24), prefSize.height)); JBInsets.addTo(size, getMargin()); return size; } @Override public Dimension getMinimumSize() { return new Dimension(super.getMinimumSize().width, getPreferredSize().height); } @Override public Font getFont() { // TODO(jacobr): it would be better to use // JBUI.Fonts.toolbarSmallComboBoxFont but it isn't availabe in all // versions of IntelliJ we support. return isSmallVariant() ? JBUI.Fonts.miniFont() : UIUtil.getLabelFont(); } @Override protected Graphics getComponentGraphics(Graphics graphics) { return JBSwingUtilities.runGlobalCGTransform(this, super.getComponentGraphics(graphics)); } @Override public void paint(Graphics g) { super.paint(g); if (!isArrowVisible(myPresentation)) { return; } final Icon icon = getArrowIcon(isEnabled()); final int x = getWidth() - icon.getIconWidth() - getInsets().right - getMargin().right; icon.paintIcon(null, g, x, (getHeight() - icon.getIconHeight()) / 2); } protected boolean isArrowVisible(@NotNull Presentation presentation) { return true; } @Override public void updateUI() { super.updateUI(); setMargin(JBUI.insets(0, 0, 0, 2)); updateButtonSize(); } protected void updateButtonSize() { invalidate(); repaint(); setSize(getPreferredSize()); repaint(); } } protected Condition<AnAction> getPreselectCondition() { return null; } }
flutter-intellij/flutter-idea/src/io/flutter/view/ToolbarComboBoxAction.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/view/ToolbarComboBoxAction.java", "repo_id": "flutter-intellij", "token_count": 4740 }
529
package io.flutter.vmService.frame; import com.intellij.icons.AllIcons; import com.intellij.ui.ColoredTextContainer; import com.intellij.ui.SimpleTextAttributes; import com.intellij.xdebugger.frame.XStackFrame; import org.jetbrains.annotations.NotNull; /** * A XStackFrame used to render a separator between two sets of async stack frames. */ public class DartAsyncMarkerFrame extends XStackFrame { public DartAsyncMarkerFrame() { } public void customizePresentation(@NotNull ColoredTextContainer component) { component.append("<asynchronous gap>", SimpleTextAttributes.EXCLUDED_ATTRIBUTES); component.setIcon(AllIcons.General.SeparatorH); } }
flutter-intellij/flutter-idea/src/io/flutter/vmService/frame/DartAsyncMarkerFrame.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/vmService/frame/DartAsyncMarkerFrame.java", "repo_id": "flutter-intellij", "token_count": 210 }
530
/* * Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file * for details. All rights reserved. Use of this source code is governed by a * BSD-style license that can be found in the LICENSE file. * * This file has been automatically generated. Please do not edit it manually. * To regenerate the file, use the script "pkg/analysis_server/tool/spec/generate_files". */ package org.dartlang.analysis.server.protocol; /** * An enumeration of the kinds of property editors. * * @coverage dart.server.generated.types */ public class FlutterWidgetPropertyEditorKind { /** * The editor for a property of type bool. */ public static final String BOOL = "BOOL"; /** * The editor for a property of the type double. */ public static final String DOUBLE = "DOUBLE"; /** * The editor for choosing an item of an enumeration, see the enumItems field of * FlutterWidgetPropertyEditor. */ public static final String ENUM = "ENUM"; /** * The editor for either choosing a pre-defined item from a list of provided static field * references (like ENUM), or specifying a free-form expression. */ public static final String ENUM_LIKE = "ENUM_LIKE"; /** * The editor for a property of type int. */ public static final String INT = "INT"; /** * The editor for a property of the type String. */ public static final String STRING = "STRING"; }
flutter-intellij/flutter-idea/src/org/dartlang/analysis/server/protocol/FlutterWidgetPropertyEditorKind.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/org/dartlang/analysis/server/protocol/FlutterWidgetPropertyEditorKind.java", "repo_id": "flutter-intellij", "token_count": 410 }
531
/* * Copyright 2017 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. */ package io.flutter.bazel; import com.intellij.openapi.roots.ModifiableRootModel; import com.intellij.openapi.roots.ModuleRootModificationUtil; import com.intellij.openapi.vfs.VirtualFile; import io.flutter.testing.ProjectFixture; import io.flutter.testing.TestDir; import io.flutter.testing.Testing; import org.junit.Before; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import static junit.framework.TestCase.assertNull; import static org.junit.Assert.*; public class WorkspaceCacheTest { @Rule public final ProjectFixture fixture = Testing.makeEmptyModule(); @Rule public final TestDir tmp = new TestDir(); private WorkspaceCache cache; @Before public void setUp() throws Exception { cache = WorkspaceCache.getInstance(fixture.getProject()); assertNotNull(cache); tmp.ensureDir("abc"); tmp.writeFile("abc/WORKSPACE", ""); tmp.ensureDir("abc/dart/config/ide"); final VirtualFile contentRoot = tmp.ensureDir("abc/dart/something"); Testing.runOnDispatchThread( () -> ModuleRootModificationUtil.addContentRoot(fixture.getModule(), contentRoot.getPath())); } @Test @Ignore("https://github.com/flutter/flutter-intellij/issues/3583") public void shouldDetectConfigFileChanges() throws Exception { // This test causes stack traces to be logged at shutdown in local history: "Recursive records found". // (Unknown cause.) checkNoConfig(); final String configPath = "abc/dart/config/ide/flutter.json"; tmp.writeFile(configPath, "{\"daemonScript\": \"first.sh\"}"); tmp.writeFile("abc/first.sh", ""); checkConfigSetting("first.sh"); tmp.writeFile(configPath, "{}"); checkConfigSetting(null); tmp.writeFile(configPath, "{\"daemonScript\": \"second.sh\"}"); tmp.writeFile("abc/second.sh", ""); checkConfigSetting("second.sh"); tmp.deleteFile(configPath); checkNoConfig(); } @Test @Ignore("https://github.com/flutter/flutter-intellij/issues/3583") public void shouldDetectModuleRootChange() throws Exception { checkWorkspaceExists(); removeContentRoot(); checkNoWorkspaceExists(); } private void removeContentRoot() throws Exception { Testing.runOnDispatchThread( () -> ModuleRootModificationUtil.updateModel( fixture.getModule(), (ModifiableRootModel model) -> model.removeContentEntry(model.getContentEntries()[0]))); } private void checkNoWorkspaceExists() { assertNull("expected no workspace to exist", cache.get()); } private void checkWorkspaceExists() { assertNotNull("expected a workspace but it doesn't exist", cache.get()); } private void checkNoConfig() { final Workspace w = cache.get(); assertNotNull("expected a workspace but it doesn't exist", w); assertFalse("workspace has unexpected plugin config", w.hasPluginConfig()); } private void checkConfigSetting(String expected) { final Workspace w = cache.get(); assertNotNull("expected a workspace but it doesn't exist", w); assertEquals(expected, w.getDaemonScript()); } }
flutter-intellij/flutter-idea/testSrc/unit/io/flutter/bazel/WorkspaceCacheTest.java/0
{ "file_path": "flutter-intellij/flutter-idea/testSrc/unit/io/flutter/bazel/WorkspaceCacheTest.java", "repo_id": "flutter-intellij", "token_count": 1053 }
532
/* * 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. */ package io.flutter.logging; import org.junit.Test; import static org.junit.Assert.assertEquals; public class FlutterErrorHelperTest { @Test public void testGetAnalyticsId() { assertEquals( "a-renderflex-overflowed-by-xxx-pixels-on-the-right", FlutterErrorHelper.getAnalyticsId("A RenderFlex overflowed by 1183 pixels on the right.")); assertEquals( "a-renderflex-overflowed-by-xxx-pixels-on-the-right", FlutterErrorHelper.getAnalyticsId("A RenderFlex overflowed by 22.3 pixels on the right.")); assertEquals( "no-material-widget-found", FlutterErrorHelper.getAnalyticsId("No Material widget found.")); assertEquals( "i-collapse-whitespace", FlutterErrorHelper.getAnalyticsId("I collapse whitespace.")); assertEquals( "scaffold.of-called-with-a-context-that-does-not-contain-a-scaffold", FlutterErrorHelper.getAnalyticsId("Scaffold.of() called with a context that does not contain a Scaffold.")); } @Test public void testGetAnalyticsId_scrubbing() { assertEquals( "failed-assertion", FlutterErrorHelper.getAnalyticsId( "'package:flutter/src/widgets/framework.dart':\n" + "failed assertion: line 123 pos 123: 'owner._debugcurrentbuildtarget == this': is not true")); assertEquals( "failed-assertion", FlutterErrorHelper.getAnalyticsId( "'package:flutter/src/widgets/framework.dart':\n" + "failed assertion: line 123 pos 123: 'owner._debugcurrentbuildtarget == this': is not true")); assertEquals( "unable-to-load-asset", FlutterErrorHelper.getAnalyticsId("unable to load asset: images/foobar.png")); assertEquals( "all-children-of-this-widget-must-have-a-key", FlutterErrorHelper.getAnalyticsId( "all children of this widget must have a key.\n" + "'package:flutter/src/material/reorderable_list.dart': failed assertion: line 123 pos xxx: 'children.every((widget w) => w.key != null)'")); assertEquals( "all-children-of-this-widget-must-have-a-key", FlutterErrorHelper.getAnalyticsId( "all children of this widget must have a key.\n" + "'package:flutter/src/material/reorderable_list.dart': failed assertion: line 123 pos 123: 'children.every((widget w) => w.key != null)'")); assertEquals( "could-not-find-a-generator-for-route-routesettings-in-the-_widgetsappstate", FlutterErrorHelper.getAnalyticsId("could not find a generator for route routesettings(\"/foobar\", null) in the _widgetsappstate")); assertEquals( "controller's-length-property-does-not-match-the-number-of-tabs", FlutterErrorHelper.getAnalyticsId("controller's length property (123) does not match the number of tabs")); } @Test public void testGetAnalyticsId_errorStudiesApp() { assertEquals( "renderbox-was-not-laid-out", FlutterErrorHelper .getAnalyticsId("RenderBox was not laid out: RenderViewport#d878b NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE\n" + "'package:flutter/src/rendering/box.dart':\n" + "Failed assertion: line 1785 pos 12: 'hasSize'")); assertEquals( "null-check-operator-used-on-a-null-value", FlutterErrorHelper.getAnalyticsId("Null check operator used on a null value")); assertEquals( "a-renderflex-overflowed-by-xxx-pixels-on-the-right", FlutterErrorHelper.getAnalyticsId("A RenderFlex overflowed by 13 pixels on the right.")); assertEquals( "no-material-widget-found", FlutterErrorHelper.getAnalyticsId("No Material widget found.")); assertEquals( "vertical-viewport-was-given-unbounded-height", FlutterErrorHelper.getAnalyticsId("Vertical viewport was given unbounded height.")); assertEquals( "scaffold.of-called-with-a-context-that-does-not-contain-a-scaffold", FlutterErrorHelper.getAnalyticsId("Scaffold.of() called with a context that does not contain a Scaffold.")); assertEquals( "exception", FlutterErrorHelper.getAnalyticsId("Exception: not today")); assertEquals( "setstate-or-markneedsbuild-called-during-build", FlutterErrorHelper.getAnalyticsId("setState() or markNeedsBuild() called during build.")); assertEquals( "simple-assertion", FlutterErrorHelper.getAnalyticsId("simple assertion\n" + "'package:flutter_error_studies/main.dart':\n" + "Failed assertion: line 40 pos 12: '1 == 2'")); assertEquals( "failed-assertion", FlutterErrorHelper .getAnalyticsId("'package:flutter_error_studies/main.dart': Failed assertion: line 41 pos 12: '1 == 2': is not true.")); assertEquals( "simple-assertion", FlutterErrorHelper.getAnalyticsId("simple assertion\n" + "'package:flutter_error_studies/main.dart':\n" + "Failed assertion: line 42 pos 12: '() {\n" + " return 1 == 2;\n" + " }()'")); assertEquals( "failed-assertion", FlutterErrorHelper.getAnalyticsId("'package:flutter_error_studies/main.dart': Failed assertion: line 45 pos 12: '() {\n" + " return 1 == 2;\n" + " }()': is not true.")); } }
flutter-intellij/flutter-idea/testSrc/unit/io/flutter/logging/FlutterErrorHelperTest.java/0
{ "file_path": "flutter-intellij/flutter-idea/testSrc/unit/io/flutter/logging/FlutterErrorHelperTest.java", "repo_id": "flutter-intellij", "token_count": 2373 }
533
/* * 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. */ package io.flutter.run.bazelTest; import org.junit.Test; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; /** * Verify the behavior of bazel test configuration factories. * * <p> * These tests validate preconditions from Bazel IntelliJ plugin logic for how run configurations are saved to Piper. * If these tests fail, you may need to update some g3 code to prevent breaking g3 Bazel run configurations. */ public class BazelTestConfigurationFactoryTest { final FlutterBazelTestConfigurationType type = new FlutterBazelTestConfigurationType(); @Test public void factoryIdsAreCorrect() { // Bazel code assumes the id of the factory as a precondition. assertThat(type.factory.getId(), equalTo("Flutter Test (Bazel)")); assertThat(type.watchFactory.getId(), equalTo("Watch Flutter Test (Bazel)")); } @Test public void factoryConfigTypesMatch() { assertThat(type.getId(), equalTo("FlutterBazelTestConfigurationType")); } }
flutter-intellij/flutter-idea/testSrc/unit/io/flutter/run/bazelTest/BazelTestConfigurationFactoryTest.java/0
{ "file_path": "flutter-intellij/flutter-idea/testSrc/unit/io/flutter/run/bazelTest/BazelTestConfigurationFactoryTest.java", "repo_id": "flutter-intellij", "token_count": 344 }
534
/* * Copyright 2017 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. */ package io.flutter.testing; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.testFramework.fixtures.IdeaProjectTestFixture; abstract public class ProjectFixture<T extends IdeaProjectTestFixture> extends AdaptedFixture<T> { ProjectFixture(Factory<T> factory, boolean setupOnDispatchThread) { super(factory, setupOnDispatchThread); } public Project getProject() { return getInner().getProject(); } public Module getModule() { return getInner().getModule(); } }
flutter-intellij/flutter-idea/testSrc/unit/io/flutter/testing/ProjectFixture.java/0
{ "file_path": "flutter-intellij/flutter-idea/testSrc/unit/io/flutter/testing/ProjectFixture.java", "repo_id": "flutter-intellij", "token_count": 218 }
535
/* * Copyright (c) 2015, the Dart project authors. * * Licensed under the Eclipse Public License v1.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.dartlang.vm.service.element; // This file is generated by the script: pkg/vm_service/tool/generate.dart in dart-lang/sdk. import com.google.gson.JsonElement; import com.google.gson.JsonObject; /** * A {@link Field} provides information about a Dart language field or variable. */ @SuppressWarnings({"WeakerAccess", "unused"}) public class Field extends Obj { public Field(JsonObject json) { super(json); } /** * The declared type of this field. * * The value will always be of one of the kinds: Type, TypeRef, TypeParameter, BoundedType. */ public InstanceRef getDeclaredType() { return new InstanceRef((JsonObject) json.get("declaredType")); } /** * The location of this field in the source code. * * Note: this may not agree with the location of `owner` if this is a field from a mixin * application, patched class, etc. * * Can return <code>null</code>. */ public SourceLocation getLocation() { JsonObject obj = (JsonObject) json.get("location"); if (obj == null) return null; final String type = json.get("type").getAsString(); if ("Instance".equals(type) || "@Instance".equals(type)) { final String kind = json.get("kind").getAsString(); if ("Null".equals(kind)) return null; } return new SourceLocation(obj); } /** * The name of this field. */ public String getName() { return getAsString("name"); } /** * The owner of this field, which can be either a Library or a Class. * * Note: the location of `owner` may not agree with `location` if this is a field from a mixin * application, patched class, etc. */ public ObjRef getOwner() { return new ObjRef((JsonObject) json.get("owner")); } /** * The value of this field, if the field is static. If uninitialized, this will take the value of * an uninitialized Sentinel. * * @return one of <code>InstanceRef</code> or <code>Sentinel</code> * * Can return <code>null</code>. */ public InstanceRef getStaticValue() { final JsonElement elem = json.get("staticValue"); if (!elem.isJsonObject()) return null; final JsonObject child = elem.getAsJsonObject(); final String type = child.get("type").getAsString(); if ("Sentinel".equals(type)) return null; return new InstanceRef(child); } /** * Is this field const? */ public boolean isConst() { return getAsBoolean("const"); } /** * Is this field final? */ public boolean isFinal() { return getAsBoolean("final"); } /** * Is this field static? */ public boolean isStatic() { return getAsBoolean("static"); } }
flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/Field.java/0
{ "file_path": "flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/Field.java", "repo_id": "flutter-intellij", "token_count": 1064 }
536
/* * Copyright (c) 2015, the Dart project authors. * * Licensed under the Eclipse Public License v1.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.dartlang.vm.service.element; // This file is generated by the script: pkg/vm_service/tool/generate.dart in dart-lang/sdk. import com.google.gson.JsonArray; import com.google.gson.JsonObject; /** * An {@link IsolateGroup} object provides information about an isolate group in the VM. */ @SuppressWarnings({"WeakerAccess", "unused"}) public class IsolateGroup extends Response { public IsolateGroup(JsonObject json) { super(json); } /** * The id which is passed to the getIsolateGroup RPC to reload this isolate. */ public String getId() { return getAsString("id"); } /** * Specifies whether the isolate group was spawned by the VM or embedder for internal use. If * `false`, this isolate group is likely running user code. */ public boolean getIsSystemIsolateGroup() { return getAsBoolean("isSystemIsolateGroup"); } /** * A list of all isolates in this isolate group. */ public ElementList<IsolateRef> getIsolates() { return new ElementList<IsolateRef>(json.get("isolates").getAsJsonArray()) { @Override protected IsolateRef basicGet(JsonArray array, int index) { return new IsolateRef(array.get(index).getAsJsonObject()); } }; } /** * A name identifying this isolate group. Not guaranteed to be unique. */ public String getName() { return getAsString("name"); } /** * A numeric id for this isolate, represented as a string. Unique. */ public String getNumber() { return getAsString("number"); } }
flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/IsolateGroup.java/0
{ "file_path": "flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/IsolateGroup.java", "repo_id": "flutter-intellij", "token_count": 660 }
537
/* * Copyright (c) 2015, the Dart project authors. * * Licensed under the Eclipse Public License v1.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.dartlang.vm.service.element; // This file is generated by the script: pkg/vm_service/tool/generate.dart in dart-lang/sdk. /** * A {@link SentinelKind} is used to distinguish different kinds of {@link Sentinel} objects. */ @SuppressWarnings({"WeakerAccess", "unused"}) public enum SentinelKind { /** * Indicates that a variable or field is in the process of being initialized. */ BeingInitialized, /** * Indicates that the object referred to has been collected by the GC. */ Collected, /** * Indicates that an object id has expired. */ Expired, /** * Reserved for future use. */ Free, /** * Indicates that a variable or field has not been initialized. */ NotInitialized, /** * Indicates that a variable has been eliminated by the optimizing compiler. */ OptimizedOut, /** * Represents a value returned by the VM but unknown to this client. */ Unknown }
flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/SentinelKind.java/0
{ "file_path": "flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/SentinelKind.java", "repo_id": "flutter-intellij", "token_count": 444 }
538