text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
// 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 io.flutter.plugin.common; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import io.flutter.BuildConfig; import io.flutter.Log; import java.io.ByteArrayOutputStream; import java.math.BigInteger; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; /** * MessageCodec using the Flutter standard binary encoding. * * <p>This codec is guaranteed to be compatible with the corresponding <a * href="https://api.flutter.dev/flutter/services/StandardMessageCodec-class.html">StandardMessageCodec</a> * on the Dart side. These parts of the Flutter SDK are evolved synchronously. * * <p>Supported messages are acyclic values of these forms: * * <ul> * <li>null * <li>Booleans * <li>Bytes, Shorts, Integers, Longs * <li>BigIntegers (see below) * <li>Floats, Doubles * <li>Strings * <li>byte[], int[], long[], float[], double[] * <li>Lists of supported values * <li>Maps with supported keys and values * </ul> * * <p>On the Dart side, these values are represented as follows: * * <ul> * <li>null: null * <li>Boolean: bool * <li>Byte, Short, Integer, Long: int * <li>Float, Double: double * <li>String: String * <li>byte[]: Uint8List * <li>int[]: Int32List * <li>long[]: Int64List * <li>float[]: Float32List * <li>double[]: Float64List * <li>List: List * <li>Map: Map * </ul> * * <p>BigIntegers are represented in Dart as strings with the hexadecimal representation of the * integer's value. * * <p>To extend the codec, overwrite the writeValue and readValueOfType methods. */ public class StandardMessageCodec implements MessageCodec<Object> { private static final String TAG = "StandardMessageCodec#"; public static final StandardMessageCodec INSTANCE = new StandardMessageCodec(); @Override @Nullable public ByteBuffer encodeMessage(@Nullable Object message) { if (message == null) { return null; } final ExposedByteArrayOutputStream stream = new ExposedByteArrayOutputStream(); writeValue(stream, message); final ByteBuffer buffer = ByteBuffer.allocateDirect(stream.size()); buffer.put(stream.buffer(), 0, stream.size()); return buffer; } @Override @Nullable public Object decodeMessage(@Nullable ByteBuffer message) { if (message == null) { return null; } message.order(ByteOrder.nativeOrder()); final Object value = readValue(message); if (message.hasRemaining()) { throw new IllegalArgumentException("Message corrupted"); } return value; } private static final boolean LITTLE_ENDIAN = ByteOrder.nativeOrder() == ByteOrder.LITTLE_ENDIAN; private static final Charset UTF8 = Charset.forName("UTF8"); private static final byte NULL = 0; private static final byte TRUE = 1; private static final byte FALSE = 2; private static final byte INT = 3; private static final byte LONG = 4; private static final byte BIGINT = 5; private static final byte DOUBLE = 6; private static final byte STRING = 7; private static final byte BYTE_ARRAY = 8; private static final byte INT_ARRAY = 9; private static final byte LONG_ARRAY = 10; private static final byte DOUBLE_ARRAY = 11; private static final byte LIST = 12; private static final byte MAP = 13; private static final byte FLOAT_ARRAY = 14; /** * Writes an int representing a size to the specified stream. Uses an expanding code of 1 to 5 * bytes to optimize for small values. */ protected static final void writeSize(@NonNull ByteArrayOutputStream stream, int value) { if (BuildConfig.DEBUG && 0 > value) { Log.e(TAG, "Attempted to write a negative size."); } if (value < 254) { stream.write(value); } else if (value <= 0xffff) { stream.write(254); writeChar(stream, value); } else { stream.write(255); writeInt(stream, value); } } /** Writes the least significant two bytes of the specified int to the specified stream. */ protected static final void writeChar(@NonNull ByteArrayOutputStream stream, int value) { if (LITTLE_ENDIAN) { stream.write(value); stream.write(value >>> 8); } else { stream.write(value >>> 8); stream.write(value); } } /** Writes the specified int as 4 bytes to the specified stream. */ protected static final void writeInt(@NonNull ByteArrayOutputStream stream, int value) { if (LITTLE_ENDIAN) { stream.write(value); stream.write(value >>> 8); stream.write(value >>> 16); stream.write(value >>> 24); } else { stream.write(value >>> 24); stream.write(value >>> 16); stream.write(value >>> 8); stream.write(value); } } /** Writes the specified long as 8 bytes to the specified stream. */ protected static final void writeLong(@NonNull ByteArrayOutputStream stream, long value) { if (LITTLE_ENDIAN) { stream.write((byte) value); stream.write((byte) (value >>> 8)); stream.write((byte) (value >>> 16)); stream.write((byte) (value >>> 24)); stream.write((byte) (value >>> 32)); stream.write((byte) (value >>> 40)); stream.write((byte) (value >>> 48)); stream.write((byte) (value >>> 56)); } else { stream.write((byte) (value >>> 56)); stream.write((byte) (value >>> 48)); stream.write((byte) (value >>> 40)); stream.write((byte) (value >>> 32)); stream.write((byte) (value >>> 24)); stream.write((byte) (value >>> 16)); stream.write((byte) (value >>> 8)); stream.write((byte) value); } } /** Writes the specified double as 4 bytes to the specified stream */ protected static final void writeFloat(@NonNull ByteArrayOutputStream stream, float value) { writeInt(stream, Float.floatToIntBits(value)); } /** Writes the specified double as 8 bytes to the specified stream. */ protected static final void writeDouble(@NonNull ByteArrayOutputStream stream, double value) { writeLong(stream, Double.doubleToLongBits(value)); } /** Writes the length and then the actual bytes of the specified array to the specified stream. */ protected static final void writeBytes( @NonNull ByteArrayOutputStream stream, @NonNull byte[] bytes) { writeSize(stream, bytes.length); stream.write(bytes, 0, bytes.length); } /** * Writes a number of padding bytes to the specified stream to ensure that the next value is * aligned to a whole multiple of the specified alignment. An example usage with alignment = 8 is * to ensure doubles are word-aligned in the stream. */ protected static final void writeAlignment(@NonNull ByteArrayOutputStream stream, int alignment) { final int mod = stream.size() % alignment; if (mod != 0) { for (int i = 0; i < alignment - mod; i++) { stream.write(0); } } } /** * Writes a type discriminator byte and then a byte serialization of the specified value to the * specified stream. * * <p>Subclasses can extend the codec by overriding this method, calling super for values that the * extension does not handle. */ protected void writeValue(@NonNull ByteArrayOutputStream stream, @Nullable Object value) { if (value == null || value.equals(null)) { stream.write(NULL); } else if (value instanceof Boolean) { stream.write(((Boolean) value).booleanValue() ? TRUE : FALSE); } else if (value instanceof Number) { if (value instanceof Integer || value instanceof Short || value instanceof Byte) { stream.write(INT); writeInt(stream, ((Number) value).intValue()); } else if (value instanceof Long) { stream.write(LONG); writeLong(stream, (long) value); } else if (value instanceof Float || value instanceof Double) { stream.write(DOUBLE); writeAlignment(stream, 8); writeDouble(stream, ((Number) value).doubleValue()); } else if (value instanceof BigInteger) { stream.write(BIGINT); writeBytes(stream, ((BigInteger) value).toString(16).getBytes(UTF8)); } else { throw new IllegalArgumentException("Unsupported Number type: " + value.getClass()); } } else if (value instanceof CharSequence) { stream.write(STRING); writeBytes(stream, value.toString().getBytes(UTF8)); } else if (value instanceof byte[]) { stream.write(BYTE_ARRAY); writeBytes(stream, (byte[]) value); } else if (value instanceof int[]) { stream.write(INT_ARRAY); final int[] array = (int[]) value; writeSize(stream, array.length); writeAlignment(stream, 4); for (final int n : array) { writeInt(stream, n); } } else if (value instanceof long[]) { stream.write(LONG_ARRAY); final long[] array = (long[]) value; writeSize(stream, array.length); writeAlignment(stream, 8); for (final long n : array) { writeLong(stream, n); } } else if (value instanceof double[]) { stream.write(DOUBLE_ARRAY); final double[] array = (double[]) value; writeSize(stream, array.length); writeAlignment(stream, 8); for (final double d : array) { writeDouble(stream, d); } } else if (value instanceof List) { stream.write(LIST); final List<?> list = (List) value; writeSize(stream, list.size()); for (final Object o : list) { writeValue(stream, o); } } else if (value instanceof Map) { stream.write(MAP); final Map<?, ?> map = (Map) value; writeSize(stream, map.size()); for (final Entry<?, ?> entry : map.entrySet()) { writeValue(stream, entry.getKey()); writeValue(stream, entry.getValue()); } } else if (value instanceof float[]) { stream.write(FLOAT_ARRAY); final float[] array = (float[]) value; writeSize(stream, array.length); writeAlignment(stream, 4); for (final float f : array) { writeFloat(stream, f); } } else { throw new IllegalArgumentException( "Unsupported value: '" + value + "' of type '" + value.getClass() + "'"); } } /** Reads an int representing a size as written by writeSize. */ protected static final int readSize(@NonNull ByteBuffer buffer) { if (!buffer.hasRemaining()) { throw new IllegalArgumentException("Message corrupted"); } final int value = buffer.get() & 0xff; if (value < 254) { return value; } else if (value == 254) { return buffer.getChar(); } else { return buffer.getInt(); } } /** Reads a byte array as written by writeBytes. */ @NonNull protected static final byte[] readBytes(@NonNull ByteBuffer buffer) { final int length = readSize(buffer); final byte[] bytes = new byte[length]; buffer.get(bytes); return bytes; } /** Reads alignment padding bytes as written by writeAlignment. */ protected static final void readAlignment(@NonNull ByteBuffer buffer, int alignment) { final int mod = buffer.position() % alignment; if (mod != 0) { buffer.position(buffer.position() + alignment - mod); } } /** Reads a value as written by writeValue. */ @NonNull protected final Object readValue(@NonNull ByteBuffer buffer) { if (!buffer.hasRemaining()) { throw new IllegalArgumentException("Message corrupted"); } final byte type = buffer.get(); return readValueOfType(type, buffer); } /** * Reads a value of the specified type. * * <p>Subclasses may extend the codec by overriding this method, calling super for types that the * extension does not handle. */ @Nullable protected Object readValueOfType(byte type, @NonNull ByteBuffer buffer) { final Object result; switch (type) { case NULL: result = null; break; case TRUE: result = true; break; case FALSE: result = false; break; case INT: result = buffer.getInt(); break; case LONG: result = buffer.getLong(); break; case BIGINT: { final byte[] hex = readBytes(buffer); result = new BigInteger(new String(hex, UTF8), 16); break; } case DOUBLE: readAlignment(buffer, 8); result = buffer.getDouble(); break; case STRING: { final byte[] bytes = readBytes(buffer); result = new String(bytes, UTF8); break; } case BYTE_ARRAY: { result = readBytes(buffer); break; } case INT_ARRAY: { final int length = readSize(buffer); final int[] array = new int[length]; readAlignment(buffer, 4); buffer.asIntBuffer().get(array); result = array; buffer.position(buffer.position() + 4 * length); break; } case LONG_ARRAY: { final int length = readSize(buffer); final long[] array = new long[length]; readAlignment(buffer, 8); buffer.asLongBuffer().get(array); result = array; buffer.position(buffer.position() + 8 * length); break; } case DOUBLE_ARRAY: { final int length = readSize(buffer); final double[] array = new double[length]; readAlignment(buffer, 8); buffer.asDoubleBuffer().get(array); result = array; buffer.position(buffer.position() + 8 * length); break; } case LIST: { final int size = readSize(buffer); final List<Object> list = new ArrayList<>(size); for (int i = 0; i < size; i++) { list.add(readValue(buffer)); } result = list; break; } case MAP: { final int size = readSize(buffer); final Map<Object, Object> map = new HashMap<>(); for (int i = 0; i < size; i++) { map.put(readValue(buffer), readValue(buffer)); } result = map; break; } case FLOAT_ARRAY: { final int length = readSize(buffer); final float[] array = new float[length]; readAlignment(buffer, 4); buffer.asFloatBuffer().get(array); result = array; buffer.position(buffer.position() + 4 * length); break; } default: throw new IllegalArgumentException("Message corrupted"); } return result; } static final class ExposedByteArrayOutputStream extends ByteArrayOutputStream { byte[] buffer() { return buf; } } }
engine/shell/platform/android/io/flutter/plugin/common/StandardMessageCodec.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/plugin/common/StandardMessageCodec.java", "repo_id": "engine", "token_count": 5695 }
312
// 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 io.flutter.plugin.platform; import android.annotation.SuppressLint; import android.view.View; import androidx.annotation.NonNull; import androidx.annotation.Nullable; /** A handle to an Android view to be embedded in the Flutter hierarchy. */ public interface PlatformView { /** Returns the Android view to be embedded in the Flutter hierarchy. */ @Nullable View getView(); /** * Called by the {@link io.flutter.embedding.engine.FlutterEngine} that owns this {@code * PlatformView} when the Android {@link View} responsible for rendering a Flutter UI is * associated with the {@link io.flutter.embedding.engine.FlutterEngine}. * * <p>This means that our associated {@link io.flutter.embedding.engine.FlutterEngine} can now * render a UI and interact with the user. * * <p>Some platform views may have unusual dependencies on the {@link View} that renders Flutter * UIs, such as unique keyboard interactions. That {@link View} is provided here for those * purposes. Use of this {@link View} should be avoided if it is not absolutely necessary, because * depending on this {@link View} will tend to make platform view code more brittle to future * changes. */ // Default interface methods are supported on all min SDK versions of Android. @SuppressLint("NewApi") default void onFlutterViewAttached(@NonNull View flutterView) {} /** * Called by the {@link io.flutter.embedding.engine.FlutterEngine} that owns this {@code * PlatformView} when the Android {@link View} responsible for rendering a Flutter UI is detached * and disassociated from the {@link io.flutter.embedding.engine.FlutterEngine}. * * <p>This means that our associated {@link io.flutter.embedding.engine.FlutterEngine} no longer * has a rendering surface, or a user interaction surface of any kind. * * <p>This platform view must release any references related to the Android {@link View} that was * provided in {@link #onFlutterViewAttached(View)}. */ // Default interface methods are supported on all min SDK versions of Android. @SuppressLint("NewApi") default void onFlutterViewDetached() {} /** * Dispose this platform view. * * <p>The {@link PlatformView} object is unusable after this method is called. * * <p>Plugins implementing {@link PlatformView} must clear all references to the View object and * the PlatformView after this method is called. Failing to do so will result in a memory leak. * * <p>References related to the Android {@link View} attached in {@link * #onFlutterViewAttached(View)} must be released in {@code dispose()} to avoid memory leaks. */ void dispose(); /** * Callback fired when the platform's input connection is locked, or should be used. * * <p>This hook only exists for rare cases where the plugin relies on the state of the input * connection. This probably doesn't need to be implemented. */ @SuppressLint("NewApi") default void onInputConnectionLocked() {} /** * Callback fired when the platform input connection has been unlocked. * * <p>This hook only exists for rare cases where the plugin relies on the state of the input * connection. This probably doesn't need to be implemented. */ @SuppressLint("NewApi") default void onInputConnectionUnlocked() {} }
engine/shell/platform/android/io/flutter/plugin/platform/PlatformView.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/plugin/platform/PlatformView.java", "repo_id": "engine", "token_count": 1009 }
313
// 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 io.flutter.util; import static io.flutter.Build.API_LEVELS; import android.os.Build; import android.os.Handler; import android.os.Looper; /** Compatability wrapper over {@link Handler}. */ public final class HandlerCompat { /** * Create a new Handler whose posted messages and runnables are not subject to synchronization * barriers such as display vsync. * * <p>Messages sent to an async handler are guaranteed to be ordered with respect to one another, * but not necessarily with respect to messages from other Handlers. Compatibility behavior: * * <ul> * <li>SDK 28 and above, this method matches platform behavior. * <li>Otherwise, returns a synchronous handler instance. * </ul> * * @param looper the Looper that the new Handler should be bound to * @return a new async Handler instance * @see Handler#createAsync(Looper) */ public static Handler createAsyncHandler(Looper looper) { if (Build.VERSION.SDK_INT >= API_LEVELS.API_28) { return Handler.createAsync(looper); } return new Handler(looper); } }
engine/shell/platform/android/io/flutter/util/HandlerCompat.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/util/HandlerCompat.java", "repo_id": "engine", "token_count": 383 }
314
// 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_SHELL_PLATFORM_ANDROID_PLATFORM_VIEW_ANDROID_JNI_IMPL_H_ #define FLUTTER_SHELL_PLATFORM_ANDROID_PLATFORM_VIEW_ANDROID_JNI_IMPL_H_ #include "flutter/fml/platform/android/jni_weak_ref.h" #include "flutter/shell/platform/android/jni/platform_view_android_jni.h" namespace flutter { //------------------------------------------------------------------------------ /// @brief Concrete implementation of `PlatformViewAndroidJNI` that is /// compiled with the Android toolchain. /// class PlatformViewAndroidJNIImpl final : public PlatformViewAndroidJNI { public: explicit PlatformViewAndroidJNIImpl( const fml::jni::JavaObjectWeakGlobalRef& java_object); ~PlatformViewAndroidJNIImpl() override; void FlutterViewHandlePlatformMessage( std::unique_ptr<flutter::PlatformMessage> message, int responseId) override; void FlutterViewHandlePlatformMessageResponse( int responseId, std::unique_ptr<fml::Mapping> data) override; void FlutterViewUpdateSemantics( std::vector<uint8_t> buffer, std::vector<std::string> strings, std::vector<std::vector<uint8_t>> string_attribute_args) override; void FlutterViewUpdateCustomAccessibilityActions( std::vector<uint8_t> actions_buffer, std::vector<std::string> strings) override; void FlutterViewOnFirstFrame() override; void FlutterViewOnPreEngineRestart() override; void SurfaceTextureAttachToGLContext(JavaLocalRef surface_texture, int textureId) override; bool SurfaceTextureShouldUpdate(JavaLocalRef surface_texture) override; void SurfaceTextureUpdateTexImage(JavaLocalRef surface_texture) override; void SurfaceTextureGetTransformMatrix(JavaLocalRef surface_texture, SkMatrix& transform) override; void SurfaceTextureDetachFromGLContext(JavaLocalRef surface_texture) override; JavaLocalRef ImageProducerTextureEntryAcquireLatestImage( JavaLocalRef image_texture_entry) override; JavaLocalRef ImageGetHardwareBuffer(JavaLocalRef image) override; void ImageClose(JavaLocalRef image) override; void HardwareBufferClose(JavaLocalRef hardware_buffer) override; void FlutterViewOnDisplayPlatformView(int view_id, int x, int y, int width, int height, int viewWidth, int viewHeight, MutatorsStack mutators_stack) override; void FlutterViewDisplayOverlaySurface(int surface_id, int x, int y, int width, int height) override; void FlutterViewBeginFrame() override; void FlutterViewEndFrame() override; std::unique_ptr<PlatformViewAndroidJNI::OverlayMetadata> FlutterViewCreateOverlaySurface() override; void FlutterViewDestroyOverlaySurfaces() override; std::unique_ptr<std::vector<std::string>> FlutterViewComputePlatformResolvedLocale( std::vector<std::string> supported_locales_data) override; double GetDisplayRefreshRate() override; double GetDisplayWidth() override; double GetDisplayHeight() override; double GetDisplayDensity() override; bool RequestDartDeferredLibrary(int loading_unit_id) override; double FlutterViewGetScaledFontSize(double unscaled_font_size, int configuration_id) const override; private: // Reference to FlutterJNI object. const fml::jni::JavaObjectWeakGlobalRef java_object_; FML_DISALLOW_COPY_AND_ASSIGN(PlatformViewAndroidJNIImpl); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_ANDROID_PLATFORM_VIEW_ANDROID_JNI_IMPL_H_
engine/shell/platform/android/platform_view_android_jni_impl.h/0
{ "file_path": "engine/shell/platform/android/platform_view_android_jni_impl.h", "repo_id": "engine", "token_count": 1643 }
315
package io.flutter; import android.content.Context; import org.robolectric.annotation.Implementation; import org.robolectric.annotation.Implements; import org.robolectric.shadows.ShadowContextImpl; @Implements(className = ShadowContextImpl.CLASS_NAME) public class CustomShadowContextImpl extends ShadowContextImpl { public static final String CLASS_NAME = "android.app.ContextImpl"; @Implementation @Override public final Object getSystemService(String name) { if (name == Context.TEXT_SERVICES_MANAGER_SERVICE) { return null; } return super.getSystemService(name); } }
engine/shell/platform/android/test/io/flutter/CustomShadowContextImpl.java/0
{ "file_path": "engine/shell/platform/android/test/io/flutter/CustomShadowContextImpl.java", "repo_id": "engine", "token_count": 189 }
316
package io.flutter.embedding.engine; import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import android.app.Activity; import android.content.Context; import android.content.Intent; import androidx.annotation.NonNull; import androidx.lifecycle.Lifecycle; import androidx.test.ext.junit.runners.AndroidJUnit4; import io.flutter.embedding.android.ExclusiveAppComponent; import io.flutter.embedding.engine.loader.FlutterLoader; import io.flutter.embedding.engine.plugins.FlutterPlugin; import io.flutter.embedding.engine.plugins.activity.ActivityAware; import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding; import io.flutter.plugin.common.PluginRegistry; import io.flutter.plugin.platform.PlatformViewsController; import java.util.concurrent.atomic.AtomicBoolean; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.annotation.Config; // Run with Robolectric so that Log calls don't crash. @Config(manifest = Config.NONE) @RunWith(AndroidJUnit4.class) public class FlutterEngineConnectionRegistryTest { @Test public void itDoesNotRegisterTheSamePluginTwice() { Context context = mock(Context.class); FlutterEngine flutterEngine = mock(FlutterEngine.class); PlatformViewsController platformViewsController = mock(PlatformViewsController.class); when(flutterEngine.getPlatformViewsController()).thenReturn(platformViewsController); FlutterLoader flutterLoader = mock(FlutterLoader.class); FakeFlutterPlugin fakePlugin1 = new FakeFlutterPlugin(); FakeFlutterPlugin fakePlugin2 = new FakeFlutterPlugin(); FlutterEngineConnectionRegistry registry = new FlutterEngineConnectionRegistry(context, flutterEngine, flutterLoader, null); // Verify that the registry doesn't think it contains our plugin yet. assertFalse(registry.has(fakePlugin1.getClass())); // Add our plugin to the registry. registry.add(fakePlugin1); // Verify that the registry now thinks it contains our plugin. assertTrue(registry.has(fakePlugin1.getClass())); assertEquals(1, fakePlugin1.attachmentCallCount); // Add a different instance of the same plugin class. registry.add(fakePlugin2); // Verify that the registry did not detach the 1st plugin, and // it did not attach the 2nd plugin. assertEquals(1, fakePlugin1.attachmentCallCount); assertEquals(0, fakePlugin1.detachmentCallCount); assertEquals(0, fakePlugin2.attachmentCallCount); assertEquals(0, fakePlugin2.detachmentCallCount); } @Test public void activityResultListenerCanBeRemovedFromListener() { Context context = mock(Context.class); FlutterEngine flutterEngine = mock(FlutterEngine.class); PlatformViewsController platformViewsController = mock(PlatformViewsController.class); when(flutterEngine.getPlatformViewsController()).thenReturn(platformViewsController); FlutterLoader flutterLoader = mock(FlutterLoader.class); ExclusiveAppComponent appComponent = mock(ExclusiveAppComponent.class); Activity activity = mock(Activity.class); when(appComponent.getAppComponent()).thenReturn(activity); Intent intent = mock(Intent.class); when(activity.getIntent()).thenReturn(intent); Lifecycle lifecycle = mock(Lifecycle.class); AtomicBoolean isFirstCall = new AtomicBoolean(true); // Set up the environment to get the required internal data FlutterEngineConnectionRegistry registry = new FlutterEngineConnectionRegistry(context, flutterEngine, flutterLoader, null); FakeActivityAwareFlutterPlugin fakePlugin = new FakeActivityAwareFlutterPlugin(); registry.add(fakePlugin); registry.attachToActivity(appComponent, lifecycle); // The binding is now available via `fakePlugin.binding`: Create and add the listeners FakeActivityResultListener listener1 = new FakeActivityResultListener(isFirstCall, fakePlugin.binding); FakeActivityResultListener listener2 = new FakeActivityResultListener(isFirstCall, fakePlugin.binding); fakePlugin.binding.addActivityResultListener(listener1); fakePlugin.binding.addActivityResultListener(listener2); // fire the onActivityResult which should invoke both listeners registry.onActivityResult(0, 0, intent); assertEquals(1, listener1.callCount); assertEquals(1, listener2.callCount); // fire it again to check if the first called listener was removed registry.onActivityResult(0, 0, intent); // The order of the listeners in the HashSet is random: So just check the sum of calls assertEquals(3, listener1.callCount + listener2.callCount); } @Test public void softwareRendering() { Context context = mock(Context.class); FlutterEngine flutterEngine = mock(FlutterEngine.class); PlatformViewsController platformViewsController = mock(PlatformViewsController.class); when(flutterEngine.getPlatformViewsController()).thenReturn(platformViewsController); FlutterLoader flutterLoader = mock(FlutterLoader.class); ExclusiveAppComponent appComponent = mock(ExclusiveAppComponent.class); Activity activity = mock(Activity.class); when(appComponent.getAppComponent()).thenReturn(activity); // Test attachToActivity with an Activity that has no Intent. FlutterEngineConnectionRegistry registry = new FlutterEngineConnectionRegistry(context, flutterEngine, flutterLoader, null); registry.attachToActivity(appComponent, mock(Lifecycle.class)); verify(platformViewsController).setSoftwareRendering(false); Intent intent = mock(Intent.class); when(intent.getBooleanExtra("enable-software-rendering", false)).thenReturn(false); when(activity.getIntent()).thenReturn(intent); registry.attachToActivity(appComponent, mock(Lifecycle.class)); verify(platformViewsController, times(2)).setSoftwareRendering(false); when(intent.getBooleanExtra("enable-software-rendering", false)).thenReturn(true); registry.attachToActivity(appComponent, mock(Lifecycle.class)); verify(platformViewsController).setSoftwareRendering(true); } private static class FakeFlutterPlugin implements FlutterPlugin { public int attachmentCallCount = 0; public int detachmentCallCount = 0; @Override public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) { attachmentCallCount += 1; } @Override public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) { detachmentCallCount += 1; } } private static class FakeActivityAwareFlutterPlugin implements FlutterPlugin, ActivityAware { public ActivityPluginBinding binding; @Override public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) {} @Override public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {} @Override public void onAttachedToActivity(final ActivityPluginBinding binding) { this.binding = binding; } @Override public void onDetachedFromActivityForConfigChanges() {} @Override public void onReattachedToActivityForConfigChanges(final ActivityPluginBinding binding) {} @Override public void onDetachedFromActivity() {} } private static class FakeActivityResultListener implements PluginRegistry.ActivityResultListener { public int callCount = 0; private final AtomicBoolean isFirstCall; private final ActivityPluginBinding binding; public FakeActivityResultListener(AtomicBoolean isFirstCall, ActivityPluginBinding binding) { this.isFirstCall = isFirstCall; this.binding = binding; } @Override public boolean onActivityResult( final int requestCode, final int resultCode, final Intent data) { callCount++; if (isFirstCall.get()) { isFirstCall.set(false); binding.removeActivityResultListener(this); } return false; } } }
engine/shell/platform/android/test/io/flutter/embedding/engine/FlutterEngineConnectionRegistryTest.java/0
{ "file_path": "engine/shell/platform/android/test/io/flutter/embedding/engine/FlutterEngineConnectionRegistryTest.java", "repo_id": "engine", "token_count": 2415 }
317
package io.flutter.embedding.engine.renderer; import static io.flutter.Build.API_LEVELS; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.robolectric.Shadows.shadowOf; import android.annotation.TargetApi; import android.graphics.Canvas; import android.graphics.SurfaceTexture; import android.os.Handler; import android.os.Looper; import android.view.Surface; import androidx.test.ext.junit.runners.AndroidJUnit4; import io.flutter.embedding.engine.FlutterJNI; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(AndroidJUnit4.class) @TargetApi(API_LEVELS.API_26) public final class SurfaceTextureSurfaceProducerTest { private final FlutterJNI fakeJNI = mock(FlutterJNI.class); @Test public void createsSurfaceTextureOfGivenSizeAndResizesWhenRequested() { final FlutterRenderer flutterRenderer = new FlutterRenderer(fakeJNI); // Create a surface and set the initial size. final Handler handler = new Handler(Looper.getMainLooper()); final SurfaceTextureSurfaceProducer producer = new SurfaceTextureSurfaceProducer( 0, handler, fakeJNI, flutterRenderer.registerSurfaceTexture(new SurfaceTexture(0))); final Surface surface = producer.getSurface(); AtomicInteger frames = new AtomicInteger(); producer .getSurfaceTexture() .setOnFrameAvailableListener( (texture) -> { if (texture.isReleased()) { return; } frames.getAndIncrement(); }); producer.setSize(100, 200); // Draw. Canvas canvas = surface.lockHardwareCanvas(); canvas.drawARGB(255, 255, 0, 0); surface.unlockCanvasAndPost(canvas); shadowOf(Looper.getMainLooper()).idle(); assertEquals(frames.get(), 1); // Resize and redraw. producer.setSize(400, 800); canvas = surface.lockHardwareCanvas(); canvas.drawARGB(255, 255, 0, 0); surface.unlockCanvasAndPost(canvas); shadowOf(Looper.getMainLooper()).idle(); assertEquals(frames.get(), 2); // Done. fakeJNI.detachFromNativeAndReleaseResources(); producer.release(); } }
engine/shell/platform/android/test/io/flutter/embedding/engine/renderer/SurfaceTextureSurfaceProducerTest.java/0
{ "file_path": "engine/shell/platform/android/test/io/flutter/embedding/engine/renderer/SurfaceTextureSurfaceProducerTest.java", "repo_id": "engine", "token_count": 830 }
318
package io.flutter.plugin.common; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import androidx.test.ext.junit.runners.AndroidJUnit4; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.HashMap; import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.annotation.Config; @Config(manifest = Config.NONE) @RunWith(AndroidJUnit4.class) public class StandardMethodCodecTest { @Test public void encodeMethodTest() { final Map<String, String> args = new HashMap<>(); args.put("testArg", "testValue"); MethodCall call = new MethodCall("testMethod", args); final ByteBuffer buffer = StandardMethodCodec.INSTANCE.encodeMethodCall(call); assertNotNull(buffer); buffer.flip(); final MethodCall result = StandardMethodCodec.INSTANCE.decodeMethodCall(buffer); assertEquals(call.method, result.method); assertEquals(call.arguments, result.arguments); } @Test public void encodeSuccessEnvelopeTest() { final Map<String, Integer> success = new HashMap<>(); success.put("result", 1); final ByteBuffer buffer = StandardMethodCodec.INSTANCE.encodeSuccessEnvelope(success); assertNotNull(buffer); buffer.flip(); final Object result = StandardMethodCodec.INSTANCE.decodeEnvelope(buffer); assertEquals(success, result); } @Test public void encodeSuccessEnvelopeUnsupportedObjectTest() { final StandardMethodCodecTest joke = new StandardMethodCodecTest(); try { final ByteBuffer buffer = StandardMethodCodec.INSTANCE.encodeSuccessEnvelope(joke); fail("Should have failed to convert unsupported type."); } catch (IllegalArgumentException e) { // pass. } } @Test public void encodeErrorEnvelopeWithNullDetailsTest() { final ByteBuffer buffer = StandardMethodCodec.INSTANCE.encodeErrorEnvelope("code", "error", null); assertNotNull(buffer); buffer.flip(); try { StandardMethodCodec.INSTANCE.decodeEnvelope(buffer); fail("Should have thrown a FlutterException since this is an error envelope."); } catch (FlutterException result) { assertEquals("code", result.code); assertEquals("error", result.getMessage()); assertNull(result.details); } } @Test public void encodeErrorEnvelopeWithThrowableTest() { final Exception e = new IllegalArgumentException("foo"); final ByteBuffer buffer = StandardMethodCodec.INSTANCE.encodeErrorEnvelope("code", e.getMessage(), e); assertNotNull(buffer); buffer.flip(); try { StandardMethodCodec.INSTANCE.decodeEnvelope(buffer); fail("Should have thrown a FlutterException since this is an error envelope."); } catch (FlutterException result) { assertEquals("code", result.code); assertEquals("foo", result.getMessage()); // Must contain part of a stack. String stack = (String) result.details; assertTrue( stack.contains( "at io.flutter.plugin.common.StandardMethodCodecTest.encodeErrorEnvelopeWithThrowableTest(StandardMethodCodecTest.java:")); } } @Test public void encodeErrorEnvelopeWithStacktraceTest() { final Exception e = new IllegalArgumentException("foo"); final ByteBuffer buffer = StandardMethodCodec.INSTANCE.encodeErrorEnvelopeWithStacktrace( "code", e.getMessage(), e, "error stacktrace"); assertNotNull(buffer); buffer.flip(); buffer.order(ByteOrder.nativeOrder()); final byte flag = buffer.get(); final Object code = StandardMessageCodec.INSTANCE.readValue(buffer); final Object message = StandardMessageCodec.INSTANCE.readValue(buffer); final Object details = StandardMessageCodec.INSTANCE.readValue(buffer); final Object stacktrace = StandardMessageCodec.INSTANCE.readValue(buffer); assertEquals("code", (String) code); assertEquals("foo", (String) message); String stack = (String) details; assertTrue( stack.contains( "at io.flutter.plugin.common.StandardMethodCodecTest.encodeErrorEnvelopeWithStacktraceTest(StandardMethodCodecTest.java:")); assertEquals("error stacktrace", (String) stacktrace); } }
engine/shell/platform/android/test/io/flutter/plugin/common/StandardMethodCodecTest.java/0
{ "file_path": "engine/shell/platform/android/test/io/flutter/plugin/common/StandardMethodCodecTest.java", "repo_id": "engine", "token_count": 1493 }
319
// 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 io.flutter.plugin.platform; import static io.flutter.Build.API_LEVELS; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import android.annotation.TargetApi; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import androidx.test.ext.junit.runners.AndroidJUnit4; import java.util.concurrent.Executor; import java.util.function.Consumer; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.annotation.Config; @Config(manifest = Config.NONE) @RunWith(AndroidJUnit4.class) @TargetApi(API_LEVELS.API_28) public class WindowManagerHandlerTest { @Test @Config(minSdk = API_LEVELS.API_30) public void windowManagerHandler_passesCorrectlyToFakeWindowViewGroup() { // Mock the WindowManager and FakeWindowViewGroup that get used by the WindowManagerHandler. WindowManager mockWindowManager = mock(WindowManager.class); SingleViewFakeWindowViewGroup mockSingleViewFakeWindowViewGroup = mock(SingleViewFakeWindowViewGroup.class); View mockView = mock(View.class); ViewGroup.LayoutParams mockLayoutParams = mock(ViewGroup.LayoutParams.class); WindowManagerHandler windowManagerHandler = new WindowManagerHandler(mockWindowManager, mockSingleViewFakeWindowViewGroup); // removeViewImmediate windowManagerHandler.removeViewImmediate(mockView); verify(mockView).clearAnimation(); verify(mockSingleViewFakeWindowViewGroup).removeView(mockView); verifyNoInteractions(mockWindowManager); // addView windowManagerHandler.addView(mockView, mockLayoutParams); verify(mockSingleViewFakeWindowViewGroup).addView(mockView, mockLayoutParams); verifyNoInteractions(mockWindowManager); // updateViewLayout windowManagerHandler.updateViewLayout(mockView, mockLayoutParams); verify(mockSingleViewFakeWindowViewGroup).updateViewLayout(mockView, mockLayoutParams); verifyNoInteractions(mockWindowManager); // removeView windowManagerHandler.updateViewLayout(mockView, mockLayoutParams); verify(mockSingleViewFakeWindowViewGroup).removeView(mockView); verifyNoInteractions(mockWindowManager); } @Test @Config(minSdk = API_LEVELS.API_30) public void windowManagerHandler_logAndReturnEarly_whenFakeWindowViewGroupIsNull() { // Mock the WindowManager and FakeWindowViewGroup that get used by the WindowManagerHandler. WindowManager mockWindowManager = mock(WindowManager.class); View mockView = mock(View.class); ViewGroup.LayoutParams mockLayoutParams = mock(ViewGroup.LayoutParams.class); WindowManagerHandler windowManagerHandler = new WindowManagerHandler(mockWindowManager, null); // removeViewImmediate windowManagerHandler.removeViewImmediate(mockView); verifyNoInteractions(mockView); verifyNoInteractions(mockWindowManager); // addView windowManagerHandler.addView(mockView, mockLayoutParams); verifyNoInteractions(mockWindowManager); // updateViewLayout windowManagerHandler.updateViewLayout(mockView, mockLayoutParams); verifyNoInteractions(mockWindowManager); // removeView windowManagerHandler.updateViewLayout(mockView, mockLayoutParams); verifyNoInteractions(mockWindowManager); } // This section tests that WindowManagerHandler forwards all of the non-special case calls to the // delegate WindowManager. Because this must include some deprecated WindowManager method calls // (because the proxy overrides every method), we suppress deprecation warnings here. @Test @Config(minSdk = API_LEVELS.API_31) @SuppressWarnings("deprecation") public void windowManagerHandler_forwardsAllOtherCallsToDelegate() { // Mock the WindowManager and FakeWindowViewGroup that get used by the WindowManagerHandler. WindowManager mockWindowManager = mock(WindowManager.class); SingleViewFakeWindowViewGroup mockSingleViewFakeWindowViewGroup = mock(SingleViewFakeWindowViewGroup.class); WindowManagerHandler windowManagerHandler = new WindowManagerHandler(mockWindowManager, mockSingleViewFakeWindowViewGroup); // Verify that all other calls get forwarded to the delegate. Executor mockExecutor = mock(Executor.class); @SuppressWarnings("Unchecked cast") Consumer<Boolean> mockListener = (Consumer<Boolean>) mock(Consumer.class); windowManagerHandler.getDefaultDisplay(); verify(mockWindowManager).getDefaultDisplay(); windowManagerHandler.getCurrentWindowMetrics(); verify(mockWindowManager).getCurrentWindowMetrics(); windowManagerHandler.getMaximumWindowMetrics(); verify(mockWindowManager).getMaximumWindowMetrics(); windowManagerHandler.isCrossWindowBlurEnabled(); verify(mockWindowManager).isCrossWindowBlurEnabled(); windowManagerHandler.addCrossWindowBlurEnabledListener(mockListener); verify(mockWindowManager).addCrossWindowBlurEnabledListener(mockListener); windowManagerHandler.addCrossWindowBlurEnabledListener(mockExecutor, mockListener); verify(mockWindowManager).addCrossWindowBlurEnabledListener(mockExecutor, mockListener); windowManagerHandler.removeCrossWindowBlurEnabledListener(mockListener); verify(mockWindowManager).removeCrossWindowBlurEnabledListener(mockListener); } }
engine/shell/platform/android/test/io/flutter/plugin/platform/WindowManagerHandlerTest.java/0
{ "file_path": "engine/shell/platform/android/test/io/flutter/plugin/platform/WindowManagerHandlerTest.java", "repo_id": "engine", "token_count": 1654 }
320
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/android/vsync_waiter_android.h" #include <cmath> #include <utility> #include "flutter/common/task_runners.h" #include "flutter/fml/logging.h" #include "flutter/fml/platform/android/jni_util.h" #include "flutter/fml/platform/android/scoped_java_ref.h" #include "flutter/fml/size.h" #include "flutter/fml/trace_event.h" #include "impeller/toolkit/android/choreographer.h" namespace flutter { static fml::jni::ScopedJavaGlobalRef<jclass>* g_vsync_waiter_class = nullptr; static jmethodID g_async_wait_for_vsync_method_ = nullptr; static std::atomic_uint g_refresh_rate_ = 60; VsyncWaiterAndroid::VsyncWaiterAndroid(const flutter::TaskRunners& task_runners) : VsyncWaiter(task_runners) {} VsyncWaiterAndroid::~VsyncWaiterAndroid() = default; // |VsyncWaiter| void VsyncWaiterAndroid::AwaitVSync() { if (impeller::android::Choreographer::IsAvailableOnPlatform()) { auto* weak_this = new std::weak_ptr<VsyncWaiter>(shared_from_this()); fml::TaskRunner::RunNowOrPostTask( task_runners_.GetUITaskRunner(), [weak_this]() { const auto& choreographer = impeller::android::Choreographer::GetInstance(); choreographer.PostFrameCallback([weak_this](auto time) { auto time_ns = std::chrono::time_point_cast<std::chrono::nanoseconds>(time) .time_since_epoch() .count(); OnVsyncFromNDK(time_ns, weak_this); }); }); } else { // TODO(99798): Remove it when we drop support for API level < 29 and 32-bit // devices. auto* weak_this = new std::weak_ptr<VsyncWaiter>(shared_from_this()); jlong java_baton = reinterpret_cast<jlong>(weak_this); task_runners_.GetPlatformTaskRunner()->PostTask([java_baton]() { JNIEnv* env = fml::jni::AttachCurrentThread(); env->CallStaticVoidMethod(g_vsync_waiter_class->obj(), // g_async_wait_for_vsync_method_, // java_baton // ); }); } } // static void VsyncWaiterAndroid::OnVsyncFromNDK(int64_t frame_nanos, void* data) { auto frame_time = fml::TimePoint::FromEpochDelta( fml::TimeDelta::FromNanoseconds(frame_nanos)); auto now = fml::TimePoint::Now(); if (frame_time > now) { frame_time = now; } auto target_time = frame_time + fml::TimeDelta::FromNanoseconds( 1000000000.0 / g_refresh_rate_); TRACE_EVENT2_INT("flutter", "PlatformVsync", "frame_start_time", frame_time.ToEpochDelta().ToMicroseconds(), "frame_target_time", target_time.ToEpochDelta().ToMicroseconds()); auto* weak_this = reinterpret_cast<std::weak_ptr<VsyncWaiter>*>(data); ConsumePendingCallback(weak_this, frame_time, target_time); } // static void VsyncWaiterAndroid::OnVsyncFromJava(JNIEnv* env, jclass jcaller, jlong frameDelayNanos, jlong refreshPeriodNanos, jlong java_baton) { auto frame_time = fml::TimePoint::Now() - fml::TimeDelta::FromNanoseconds(frameDelayNanos); auto target_time = frame_time + fml::TimeDelta::FromNanoseconds(refreshPeriodNanos); TRACE_EVENT2_INT("flutter", "PlatformVsync", "frame_start_time", frame_time.ToEpochDelta().ToMicroseconds(), "frame_target_time", target_time.ToEpochDelta().ToMicroseconds()); auto* weak_this = reinterpret_cast<std::weak_ptr<VsyncWaiter>*>(java_baton); ConsumePendingCallback(weak_this, frame_time, target_time); } // static void VsyncWaiterAndroid::ConsumePendingCallback( std::weak_ptr<VsyncWaiter>* weak_this, fml::TimePoint frame_start_time, fml::TimePoint frame_target_time) { auto shared_this = weak_this->lock(); delete weak_this; if (shared_this) { shared_this->FireCallback(frame_start_time, frame_target_time); } } // static void VsyncWaiterAndroid::OnUpdateRefreshRate(JNIEnv* env, jclass jcaller, jfloat refresh_rate) { FML_DCHECK(refresh_rate > 0); g_refresh_rate_ = static_cast<uint>(refresh_rate); } // static bool VsyncWaiterAndroid::Register(JNIEnv* env) { static const JNINativeMethod methods[] = { { .name = "nativeOnVsync", .signature = "(JJJ)V", .fnPtr = reinterpret_cast<void*>(&OnVsyncFromJava), }, { .name = "nativeUpdateRefreshRate", .signature = "(F)V", .fnPtr = reinterpret_cast<void*>(&OnUpdateRefreshRate), }}; jclass clazz = env->FindClass("io/flutter/embedding/engine/FlutterJNI"); if (clazz == nullptr) { return false; } g_vsync_waiter_class = new fml::jni::ScopedJavaGlobalRef<jclass>(env, clazz); FML_CHECK(!g_vsync_waiter_class->is_null()); g_async_wait_for_vsync_method_ = env->GetStaticMethodID( g_vsync_waiter_class->obj(), "asyncWaitForVsync", "(J)V"); FML_CHECK(g_async_wait_for_vsync_method_ != nullptr); return env->RegisterNatives(clazz, methods, fml::size(methods)) == 0; } } // namespace flutter
engine/shell/platform/android/vsync_waiter_android.cc/0
{ "file_path": "engine/shell/platform/android/vsync_waiter_android.cc", "repo_id": "engine", "token_count": 2488 }
321
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/common/client_wrapper/include/flutter/encodable_value.h" #include <limits> #include "gtest/gtest.h" namespace flutter { TEST(EncodableValueTest, Null) { EncodableValue value; value.IsNull(); } TEST(EncodableValueTest, Bool) { EncodableValue value(false); EXPECT_FALSE(std::get<bool>(value)); value = true; EXPECT_TRUE(std::get<bool>(value)); } TEST(EncodableValueTest, Int) { EncodableValue value(42); EXPECT_EQ(std::get<int32_t>(value), 42); value = std::numeric_limits<int32_t>::max(); EXPECT_EQ(std::get<int32_t>(value), std::numeric_limits<int32_t>::max()); } // Test the int/long convenience wrapper. TEST(EncodableValueTest, LongValue) { const EncodableValue int_value(std::numeric_limits<int32_t>::max()); EXPECT_EQ(int_value.LongValue(), std::numeric_limits<int32_t>::max()); const EncodableValue long_value(std::numeric_limits<int64_t>::max()); EXPECT_EQ(long_value.LongValue(), std::numeric_limits<int64_t>::max()); } TEST(EncodableValueTest, Long) { EncodableValue value(INT64_C(42)); EXPECT_EQ(std::get<int64_t>(value), 42); value = std::numeric_limits<int64_t>::max(); EXPECT_EQ(std::get<int64_t>(value), std::numeric_limits<int64_t>::max()); } TEST(EncodableValueTest, Double) { EncodableValue value(3.14); EXPECT_EQ(std::get<double>(value), 3.14); value = std::numeric_limits<double>::max(); EXPECT_EQ(std::get<double>(value), std::numeric_limits<double>::max()); } TEST(EncodableValueTest, String) { std::string hello("Hello, world!"); EncodableValue value(hello); EXPECT_EQ(std::get<std::string>(value), hello); value = std::string("Goodbye"); EXPECT_EQ(std::get<std::string>(value), "Goodbye"); } // Explicitly verify that the overrides to prevent char*->bool conversions work. TEST(EncodableValueTest, CString) { const char* hello = "Hello, world!"; EncodableValue value(hello); EXPECT_EQ(std::get<std::string>(value), hello); value = "Goodbye"; EXPECT_EQ(std::get<std::string>(value), "Goodbye"); } TEST(EncodableValueTest, UInt8List) { std::vector<uint8_t> data = {0, 2}; EncodableValue value(data); auto& list_value = std::get<std::vector<uint8_t>>(value); list_value.push_back(std::numeric_limits<uint8_t>::max()); EXPECT_EQ(list_value[0], 0); EXPECT_EQ(list_value[1], 2); ASSERT_EQ(list_value.size(), 3u); EXPECT_EQ(data.size(), 2u); EXPECT_EQ(list_value[2], std::numeric_limits<uint8_t>::max()); } TEST(EncodableValueTest, Int32List) { std::vector<int32_t> data = {-10, 2}; EncodableValue value(data); auto& list_value = std::get<std::vector<int32_t>>(value); list_value.push_back(std::numeric_limits<int32_t>::max()); EXPECT_EQ(list_value[0], -10); EXPECT_EQ(list_value[1], 2); ASSERT_EQ(list_value.size(), 3u); EXPECT_EQ(data.size(), 2u); EXPECT_EQ(list_value[2], std::numeric_limits<int32_t>::max()); } TEST(EncodableValueTest, Int64List) { std::vector<int64_t> data = {-10, 2}; EncodableValue value(data); auto& list_value = std::get<std::vector<int64_t>>(value); list_value.push_back(std::numeric_limits<int64_t>::max()); EXPECT_EQ(list_value[0], -10); EXPECT_EQ(list_value[1], 2); ASSERT_EQ(list_value.size(), 3u); EXPECT_EQ(data.size(), 2u); EXPECT_EQ(list_value[2], std::numeric_limits<int64_t>::max()); } TEST(EncodableValueTest, DoubleList) { std::vector<double> data = {-10.0, 2.0}; EncodableValue value(data); auto& list_value = std::get<std::vector<double>>(value); list_value.push_back(std::numeric_limits<double>::max()); EXPECT_EQ(list_value[0], -10.0); EXPECT_EQ(list_value[1], 2.0); ASSERT_EQ(list_value.size(), 3u); EXPECT_EQ(data.size(), 2u); EXPECT_EQ(list_value[2], std::numeric_limits<double>::max()); } TEST(EncodableValueTest, List) { EncodableList encodables = { EncodableValue(1), EncodableValue(2.0), EncodableValue("Three"), }; EncodableValue value(encodables); auto& list_value = std::get<EncodableList>(value); EXPECT_EQ(std::get<int32_t>(list_value[0]), 1); EXPECT_EQ(std::get<double>(list_value[1]), 2.0); EXPECT_EQ(std::get<std::string>(list_value[2]), "Three"); // Ensure that it's a modifiable copy of the original array. list_value.push_back(EncodableValue(true)); ASSERT_EQ(list_value.size(), 4u); EXPECT_EQ(encodables.size(), 3u); EXPECT_EQ(std::get<bool>(std::get<EncodableList>(value)[3]), true); } TEST(EncodableValueTest, Map) { EncodableMap encodables = { {EncodableValue(), EncodableValue(std::vector<int32_t>{1, 2, 3})}, {EncodableValue(1), EncodableValue(INT64_C(10000))}, {EncodableValue("two"), EncodableValue(7)}, }; EncodableValue value(encodables); auto& map_value = std::get<EncodableMap>(value); EXPECT_EQ( std::holds_alternative<std::vector<int32_t>>(map_value[EncodableValue()]), true); EXPECT_EQ(std::get<int64_t>(map_value[EncodableValue(1)]), INT64_C(10000)); EXPECT_EQ(std::get<int32_t>(map_value[EncodableValue("two")]), 7); // Ensure that it's a modifiable copy of the original map. map_value[EncodableValue(true)] = EncodableValue(false); ASSERT_EQ(map_value.size(), 4u); EXPECT_EQ(encodables.size(), 3u); EXPECT_EQ(std::get<bool>(map_value[EncodableValue(true)]), false); } // Tests that the < operator meets the requirements of using EncodableValue as // a map key. TEST(EncodableValueTest, Comparison) { EncodableList values = { // Null EncodableValue(), // Bool EncodableValue(true), EncodableValue(false), // Int EncodableValue(-7), EncodableValue(0), EncodableValue(100), // Long EncodableValue(INT64_C(-7)), EncodableValue(INT64_C(0)), EncodableValue(INT64_C(100)), // Double EncodableValue(-7.0), EncodableValue(0.0), EncodableValue(100.0), // String EncodableValue("one"), EncodableValue("two"), // ByteList EncodableValue(std::vector<uint8_t>{0, 1}), EncodableValue(std::vector<uint8_t>{0, 10}), // IntList EncodableValue(std::vector<int32_t>{0, 1}), EncodableValue(std::vector<int32_t>{0, 100}), // LongList EncodableValue(std::vector<int64_t>{0, INT64_C(1)}), EncodableValue(std::vector<int64_t>{0, INT64_C(100)}), // DoubleList EncodableValue(std::vector<double>{0, INT64_C(1)}), EncodableValue(std::vector<double>{0, INT64_C(100)}), // List EncodableValue(EncodableList{EncodableValue(), EncodableValue(true)}), EncodableValue(EncodableList{EncodableValue(), EncodableValue(1.0)}), // Map EncodableValue(EncodableMap{{EncodableValue(), EncodableValue(true)}, {EncodableValue(7), EncodableValue(7.0)}}), EncodableValue( EncodableMap{{EncodableValue(), EncodableValue(1.0)}, {EncodableValue("key"), EncodableValue("value")}}), // FloatList EncodableValue(std::vector<float>{0, 1}), EncodableValue(std::vector<float>{0, 100}), }; for (size_t i = 0; i < values.size(); ++i) { const auto& a = values[i]; for (size_t j = 0; j < values.size(); ++j) { const auto& b = values[j]; if (i == j) { // Identical objects should always be equal. EXPECT_FALSE(a < b); EXPECT_FALSE(b < a); } else { // All other comparisons should be consistent, but the direction doesn't // matter. EXPECT_NE(a < b, b < a) << "Indexes: " << i << ", " << j; } } // Copies should always be equal. EncodableValue copy(a); EXPECT_FALSE(a < copy || copy < a); } } // Tests that structures are deep-copied. TEST(EncodableValueTest, DeepCopy) { EncodableList original = { EncodableValue(EncodableMap{ {EncodableValue(), EncodableValue(std::vector<int32_t>{1, 2, 3})}, {EncodableValue(1), EncodableValue(INT64_C(0000))}, {EncodableValue("two"), EncodableValue(7)}, }), EncodableValue(EncodableList{ EncodableValue(), EncodableValue(), EncodableValue( EncodableMap{{EncodableValue("a"), EncodableValue("b")}}), }), }; EncodableValue copy(original); ASSERT_TRUE(std::holds_alternative<EncodableList>(copy)); // Spot-check innermost collection values. auto& root_list = std::get<EncodableList>(copy); auto& first_child = std::get<EncodableMap>(root_list[0]); EXPECT_EQ(std::get<int32_t>(first_child[EncodableValue("two")]), 7); auto& second_child = std::get<EncodableList>(root_list[1]); auto& innermost_map = std::get<EncodableMap>(second_child[2]); EXPECT_EQ(std::get<std::string>(innermost_map[EncodableValue("a")]), "b"); // Modify those values in the original structure. first_child[EncodableValue("two")] = EncodableValue(); innermost_map[EncodableValue("a")] = 99; // Re-check innermost collection values of the original to ensure that they // haven't changed. first_child = std::get<EncodableMap>(original[0]); EXPECT_EQ(std::get<int32_t>(first_child[EncodableValue("two")]), 7); second_child = std::get<EncodableList>(original[1]); innermost_map = std::get<EncodableMap>(second_child[2]); EXPECT_EQ(std::get<std::string>(innermost_map[EncodableValue("a")]), "b"); } // Simple class for testing custom encodable values class TestCustomValue { public: TestCustomValue() : x_(0), y_(0) {} TestCustomValue(int x, int y) : x_(x), y_(y) {} ~TestCustomValue() = default; int x() const { return x_; } int y() const { return y_; } private: int x_; int y_; }; TEST(EncodableValueTest, TypeIndexesCorrect) { // Null EXPECT_EQ(EncodableValue().index(), 0u); // Bool EXPECT_EQ(EncodableValue(true).index(), 1u); // Int32 EXPECT_EQ(EncodableValue(100).index(), 2u); // Int64 EXPECT_EQ(EncodableValue(INT64_C(100)).index(), 3u); // Double EXPECT_EQ(EncodableValue(7.0).index(), 4u); // String EXPECT_EQ(EncodableValue("one").index(), 5u); // ByteList EXPECT_EQ(EncodableValue(std::vector<uint8_t>()).index(), 6u); // IntList EXPECT_EQ(EncodableValue(std::vector<int32_t>()).index(), 7u); // LongList EXPECT_EQ(EncodableValue(std::vector<int64_t>()).index(), 8u); // DoubleList EXPECT_EQ(EncodableValue(std::vector<double>()).index(), 9u); // List EXPECT_EQ(EncodableValue(EncodableList()).index(), 10u); // Map EXPECT_EQ(EncodableValue(EncodableMap()).index(), 11u); // Custom type TestCustomValue customValue; EXPECT_EQ(((EncodableValue)CustomEncodableValue(customValue)).index(), 12u); // FloatList EXPECT_EQ(EncodableValue(std::vector<float>()).index(), 13u); } // namespace flutter } // namespace flutter
engine/shell/platform/common/client_wrapper/encodable_value_unittests.cc/0
{ "file_path": "engine/shell/platform/common/client_wrapper/encodable_value_unittests.cc", "repo_id": "engine", "token_count": 4551 }
322
// 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_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_METHOD_RESULT_H_ #define FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_METHOD_RESULT_H_ #include <string> namespace flutter { class EncodableValue; // Encapsulates a result returned from a MethodCall. Only one method should be // called on any given instance. template <typename T = EncodableValue> class MethodResult { public: MethodResult() = default; virtual ~MethodResult() = default; // Prevent copying. MethodResult(MethodResult const&) = delete; MethodResult& operator=(MethodResult const&) = delete; // Sends a success response, indicating that the call completed successfully // with the given result. void Success(const T& result) { SuccessInternal(&result); } // Sends a success response, indicating that the call completed successfully // with no result. void Success() { SuccessInternal(nullptr); } // Sends an error response, indicating that the call was understood but // handling failed in some way. // // error_code: A string error code describing the error. // error_message: A user-readable error message. // error_details: Arbitrary extra details about the error. void Error(const std::string& error_code, const std::string& error_message, const T& error_details) { ErrorInternal(error_code, error_message, &error_details); } // Sends an error response, indicating that the call was understood but // handling failed in some way. // // error_code: A string error code describing the error. // error_message: A user-readable error message (optional). void Error(const std::string& error_code, const std::string& error_message = "") { ErrorInternal(error_code, error_message, nullptr); } // Sends a not-implemented response, indicating that the method either was not // recognized, or has not been implemented. void NotImplemented() { NotImplementedInternal(); } protected: // Implementation of the public interface, to be provided by subclasses. virtual void SuccessInternal(const T* result) = 0; // Implementation of the public interface, to be provided by subclasses. virtual void ErrorInternal(const std::string& error_code, const std::string& error_message, const T* error_details) = 0; // Implementation of the public interface, to be provided by subclasses. virtual void NotImplementedInternal() = 0; }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_METHOD_RESULT_H_
engine/shell/platform/common/client_wrapper/include/flutter/method_result.h/0
{ "file_path": "engine/shell/platform/common/client_wrapper/include/flutter/method_result.h", "repo_id": "engine", "token_count": 864 }
323
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/common/client_wrapper/include/flutter/standard_method_codec.h" #include "flutter/shell/platform/common/client_wrapper/include/flutter/method_result_functions.h" #include "flutter/shell/platform/common/client_wrapper/testing/test_codec_extensions.h" #include "gtest/gtest.h" namespace flutter { namespace { // Returns true if the given method calls have the same method name, and their // arguments have equivalent values. bool MethodCallsAreEqual(const MethodCall<>& a, const MethodCall<>& b) { if (a.method_name() != b.method_name()) { return false; } // Treat nullptr and Null as equivalent. if ((!a.arguments() || a.arguments()->IsNull()) && (!b.arguments() || b.arguments()->IsNull())) { return true; } // If only one is nullptr, fail early rather than throw below. if (!a.arguments() || !b.arguments()) { return false; } return *a.arguments() == *b.arguments(); } } // namespace TEST(StandardMethodCodec, GetInstanceCachesInstance) { const StandardMethodCodec& codec_a = StandardMethodCodec::GetInstance(nullptr); const StandardMethodCodec& codec_b = StandardMethodCodec::GetInstance(nullptr); EXPECT_EQ(&codec_a, &codec_b); } TEST(StandardMethodCodec, HandlesMethodCallsWithNullArguments) { const StandardMethodCodec& codec = StandardMethodCodec::GetInstance(); MethodCall<> call("hello", nullptr); auto encoded = codec.EncodeMethodCall(call); ASSERT_NE(encoded.get(), nullptr); std::unique_ptr<MethodCall<>> decoded = codec.DecodeMethodCall(*encoded); ASSERT_NE(decoded.get(), nullptr); EXPECT_TRUE(MethodCallsAreEqual(call, *decoded)); } TEST(StandardMethodCodec, HandlesMethodCallsWithArgument) { const StandardMethodCodec& codec = StandardMethodCodec::GetInstance(); MethodCall<> call("hello", std::make_unique<EncodableValue>(EncodableList{ EncodableValue(42), EncodableValue("world"), })); auto encoded = codec.EncodeMethodCall(call); ASSERT_NE(encoded.get(), nullptr); std::unique_ptr<MethodCall<>> decoded = codec.DecodeMethodCall(*encoded); ASSERT_NE(decoded.get(), nullptr); EXPECT_TRUE(MethodCallsAreEqual(call, *decoded)); } TEST(StandardMethodCodec, HandlesSuccessEnvelopesWithNullResult) { const StandardMethodCodec& codec = StandardMethodCodec::GetInstance(); auto encoded = codec.EncodeSuccessEnvelope(); ASSERT_NE(encoded.get(), nullptr); std::vector<uint8_t> bytes = {0x00, 0x00}; EXPECT_EQ(*encoded, bytes); bool decoded_successfully = false; MethodResultFunctions<> result_handler( [&decoded_successfully](const EncodableValue* result) { decoded_successfully = true; EXPECT_EQ(result, nullptr); }, nullptr, nullptr); codec.DecodeAndProcessResponseEnvelope(encoded->data(), encoded->size(), &result_handler); EXPECT_TRUE(decoded_successfully); } TEST(StandardMethodCodec, HandlesSuccessEnvelopesWithResult) { const StandardMethodCodec& codec = StandardMethodCodec::GetInstance(); EncodableValue result(42); auto encoded = codec.EncodeSuccessEnvelope(&result); ASSERT_NE(encoded.get(), nullptr); std::vector<uint8_t> bytes = {0x00, 0x03, 0x2a, 0x00, 0x00, 0x00}; EXPECT_EQ(*encoded, bytes); bool decoded_successfully = false; MethodResultFunctions<> result_handler( [&decoded_successfully](const EncodableValue* result) { decoded_successfully = true; EXPECT_EQ(std::get<int32_t>(*result), 42); }, nullptr, nullptr); codec.DecodeAndProcessResponseEnvelope(encoded->data(), encoded->size(), &result_handler); EXPECT_TRUE(decoded_successfully); } TEST(StandardMethodCodec, HandlesErrorEnvelopesWithNulls) { const StandardMethodCodec& codec = StandardMethodCodec::GetInstance(); auto encoded = codec.EncodeErrorEnvelope("errorCode"); ASSERT_NE(encoded.get(), nullptr); std::vector<uint8_t> bytes = {0x01, 0x07, 0x09, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x43, 0x6f, 0x64, 0x65, 0x00, 0x00}; EXPECT_EQ(*encoded, bytes); bool decoded_successfully = false; MethodResultFunctions<> result_handler( nullptr, [&decoded_successfully](const std::string& code, const std::string& message, const EncodableValue* details) { decoded_successfully = true; EXPECT_EQ(code, "errorCode"); EXPECT_EQ(message, ""); EXPECT_EQ(details, nullptr); }, nullptr); codec.DecodeAndProcessResponseEnvelope(encoded->data(), encoded->size(), &result_handler); EXPECT_TRUE(decoded_successfully); } TEST(StandardMethodCodec, HandlesErrorEnvelopesWithDetails) { const StandardMethodCodec& codec = StandardMethodCodec::GetInstance(); EncodableValue details(EncodableList{ EncodableValue("a"), EncodableValue(42), }); auto encoded = codec.EncodeErrorEnvelope("errorCode", "something failed", &details); ASSERT_NE(encoded.get(), nullptr); std::vector<uint8_t> bytes = { 0x01, 0x07, 0x09, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x43, 0x6f, 0x64, 0x65, 0x07, 0x10, 0x73, 0x6f, 0x6d, 0x65, 0x74, 0x68, 0x69, 0x6e, 0x67, 0x20, 0x66, 0x61, 0x69, 0x6c, 0x65, 0x64, 0x0c, 0x02, 0x07, 0x01, 0x61, 0x03, 0x2a, 0x00, 0x00, 0x00, }; EXPECT_EQ(*encoded, bytes); bool decoded_successfully = false; MethodResultFunctions<> result_handler( nullptr, [&decoded_successfully](const std::string& code, const std::string& message, const EncodableValue* details) { decoded_successfully = true; EXPECT_EQ(code, "errorCode"); EXPECT_EQ(message, "something failed"); const auto* details_list = std::get_if<EncodableList>(details); ASSERT_NE(details_list, nullptr); EXPECT_EQ(std::get<std::string>((*details_list)[0]), "a"); EXPECT_EQ(std::get<int32_t>((*details_list)[1]), 42); }, nullptr); codec.DecodeAndProcessResponseEnvelope(encoded->data(), encoded->size(), &result_handler); EXPECT_TRUE(decoded_successfully); } TEST(StandardMethodCodec, HandlesCustomTypeArguments) { const StandardMethodCodec& codec = StandardMethodCodec::GetInstance( &PointExtensionSerializer::GetInstance()); Point point(7, 9); MethodCall<> call( "hello", std::make_unique<EncodableValue>(CustomEncodableValue(point))); auto encoded = codec.EncodeMethodCall(call); ASSERT_NE(encoded.get(), nullptr); std::unique_ptr<MethodCall<>> decoded = codec.DecodeMethodCall(*encoded); ASSERT_NE(decoded.get(), nullptr); const Point& decoded_point = std::any_cast<Point>( std::get<CustomEncodableValue>(*decoded->arguments())); EXPECT_EQ(point, decoded_point); }; } // namespace flutter
engine/shell/platform/common/client_wrapper/standard_method_codec_unittests.cc/0
{ "file_path": "engine/shell/platform/common/client_wrapper/standard_method_codec_unittests.cc", "repo_id": "engine", "token_count": 2939 }
324
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_COMMON_INCOMING_MESSAGE_DISPATCHER_H_ #define FLUTTER_SHELL_PLATFORM_COMMON_INCOMING_MESSAGE_DISPATCHER_H_ #include <functional> #include <map> #include <set> #include <string> #include <utility> #include "flutter/shell/platform/common/public/flutter_messenger.h" namespace flutter { // Manages per-channel registration of callbacks for handling messages from the // Flutter engine, and dispatching incoming messages to those handlers. class IncomingMessageDispatcher { public: // Creates a new IncomingMessageDispatcher. |messenger| must remain valid as // long as this object exists. explicit IncomingMessageDispatcher(FlutterDesktopMessengerRef messenger); virtual ~IncomingMessageDispatcher(); // Prevent copying. IncomingMessageDispatcher(IncomingMessageDispatcher const&) = delete; IncomingMessageDispatcher& operator=(IncomingMessageDispatcher const&) = delete; // Routes |message| to the registered handler for its channel, if any. // // If input blocking has been enabled on that channel, wraps the call to the // handler with calls to the given callbacks to block and then unblock input. // // If no handler is registered for the message's channel, sends a // NotImplemented response to the engine. void HandleMessage( const FlutterDesktopMessage& message, const std::function<void(void)>& input_block_cb = [] {}, const std::function<void(void)>& input_unblock_cb = [] {}); // Registers a message callback for incoming messages from the Flutter // side on the specified channel. |callback| will be called with the message // and |user_data| any time a message arrives on that channel. // // Replaces any existing callback. Pass a null callback to unregister the // existing callback. void SetMessageCallback(const std::string& channel, FlutterDesktopMessageCallback callback, void* user_data); // Enables input blocking on the given channel name. // // If set, then the parent window should disable input callbacks // while waiting for the handler for messages on that channel to run. void EnableInputBlockingForChannel(const std::string& channel); private: // Handle for interacting with the C messaging API. FlutterDesktopMessengerRef messenger_; // A map from channel names to the FlutterDesktopMessageCallback that should // be called for incoming messages on that channel, along with the void* user // data to pass to it. std::map<std::string, std::pair<FlutterDesktopMessageCallback, void*>> callbacks_; // Channel names for which input blocking should be enabled during the call to // that channel's handler. std::set<std::string> input_blocking_channels_; }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_COMMON_INCOMING_MESSAGE_DISPATCHER_H_
engine/shell/platform/common/incoming_message_dispatcher.h/0
{ "file_path": "engine/shell/platform/common/incoming_message_dispatcher.h", "repo_id": "engine", "token_count": 907 }
325
// 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_SHELL_PLATFORM_COMMON_PUBLIC_FLUTTER_TEXTURE_REGISTRAR_H_ #define FLUTTER_SHELL_PLATFORM_COMMON_PUBLIC_FLUTTER_TEXTURE_REGISTRAR_H_ #include <stddef.h> #include <stdint.h> #include "flutter_export.h" #if defined(__cplusplus) extern "C" { #endif struct FlutterDesktopTextureRegistrar; // Opaque reference to a texture registrar. typedef struct FlutterDesktopTextureRegistrar* FlutterDesktopTextureRegistrarRef; // Possible values for the type specified in FlutterDesktopTextureInfo. // Additional types may be added in the future. typedef enum { // A Pixel buffer-based texture. kFlutterDesktopPixelBufferTexture, // A platform-specific GPU surface-backed texture. kFlutterDesktopGpuSurfaceTexture } FlutterDesktopTextureType; // Supported GPU surface types. typedef enum { // Uninitialized. kFlutterDesktopGpuSurfaceTypeNone, // A DXGI shared texture handle (Windows only). // See // https://docs.microsoft.com/en-us/windows/win32/api/dxgi/nf-dxgi-idxgiresource-getsharedhandle kFlutterDesktopGpuSurfaceTypeDxgiSharedHandle, // A |ID3D11Texture2D| (Windows only). kFlutterDesktopGpuSurfaceTypeD3d11Texture2D } FlutterDesktopGpuSurfaceType; // Supported pixel formats. typedef enum { // Uninitialized. kFlutterDesktopPixelFormatNone, // Represents a 32-bit RGBA color format with 8 bits each for red, green, blue // and alpha. kFlutterDesktopPixelFormatRGBA8888, // Represents a 32-bit BGRA color format with 8 bits each for blue, green, red // and alpha. kFlutterDesktopPixelFormatBGRA8888 } FlutterDesktopPixelFormat; // An image buffer object. typedef struct { // The pixel data buffer. const uint8_t* buffer; // Width of the pixel buffer. size_t width; // Height of the pixel buffer. size_t height; // An optional callback that gets invoked when the |buffer| can be released. void (*release_callback)(void* release_context); // Opaque data passed to |release_callback|. void* release_context; } FlutterDesktopPixelBuffer; // A GPU surface descriptor. typedef struct { // The size of this struct. Must be // sizeof(FlutterDesktopGpuSurfaceDescriptor). size_t struct_size; // The surface handle. The expected type depends on the // |FlutterDesktopGpuSurfaceType|. // // Provide a |ID3D11Texture2D*| when using // |kFlutterDesktopGpuSurfaceTypeD3d11Texture2D| or a |HANDLE| when using // |kFlutterDesktopGpuSurfaceTypeDxgiSharedHandle|. // // The referenced resource needs to stay valid until it has been opened by // Flutter. Consider incrementing the resource's reference count in the // |FlutterDesktopGpuSurfaceTextureCallback| and registering a // |release_callback| for decrementing the reference count once it has been // opened. void* handle; // The physical width. size_t width; // The physical height. size_t height; // The visible width. // It might be less or equal to the physical |width|. size_t visible_width; // The visible height. // It might be less or equal to the physical |height|. size_t visible_height; // The pixel format which might be optional depending on the surface type. FlutterDesktopPixelFormat format; // An optional callback that gets invoked when the |handle| has been opened. void (*release_callback)(void* release_context); // Opaque data passed to |release_callback|. void* release_context; } FlutterDesktopGpuSurfaceDescriptor; // The pixel buffer copy callback definition provided to // the Flutter engine to copy the texture. // It is invoked with the intended surface size specified by |width| and // |height| and the |user_data| held by // |FlutterDesktopPixelBufferTextureConfig|. // // As this is usually called from the render thread, the callee must take // care of proper synchronization. It also needs to be ensured that the // returned |FlutterDesktopPixelBuffer| isn't released prior to unregistering // the corresponding texture. typedef const FlutterDesktopPixelBuffer* ( *FlutterDesktopPixelBufferTextureCallback)(size_t width, size_t height, void* user_data); // The GPU surface callback definition provided to the Flutter engine to obtain // the surface. It is invoked with the intended surface size specified by // |width| and |height| and the |user_data| held by // |FlutterDesktopGpuSurfaceTextureConfig|. typedef const FlutterDesktopGpuSurfaceDescriptor* ( *FlutterDesktopGpuSurfaceTextureCallback)(size_t width, size_t height, void* user_data); // An object used to configure pixel buffer textures. typedef struct { // The callback used by the engine to copy the pixel buffer object. FlutterDesktopPixelBufferTextureCallback callback; // Opaque data that will get passed to the provided |callback|. void* user_data; } FlutterDesktopPixelBufferTextureConfig; // An object used to configure GPU-surface textures. typedef struct { // The size of this struct. Must be // sizeof(FlutterDesktopGpuSurfaceTextureConfig). size_t struct_size; // The concrete surface type (e.g. // |kFlutterDesktopGpuSurfaceTypeDxgiSharedHandle|) FlutterDesktopGpuSurfaceType type; // The callback used by the engine to obtain the surface descriptor. FlutterDesktopGpuSurfaceTextureCallback callback; // Opaque data that will get passed to the provided |callback|. void* user_data; } FlutterDesktopGpuSurfaceTextureConfig; typedef struct { FlutterDesktopTextureType type; union { FlutterDesktopPixelBufferTextureConfig pixel_buffer_config; FlutterDesktopGpuSurfaceTextureConfig gpu_surface_config; }; } FlutterDesktopTextureInfo; // Registers a new texture with the Flutter engine and returns the texture ID. // This function can be called from any thread. FLUTTER_EXPORT int64_t FlutterDesktopTextureRegistrarRegisterExternalTexture( FlutterDesktopTextureRegistrarRef texture_registrar, const FlutterDesktopTextureInfo* info); // Asynchronously unregisters the texture identified by |texture_id| from the // Flutter engine. // An optional |callback| gets invoked upon completion. // This function can be called from any thread. FLUTTER_EXPORT void FlutterDesktopTextureRegistrarUnregisterExternalTexture( FlutterDesktopTextureRegistrarRef texture_registrar, int64_t texture_id, void (*callback)(void* user_data), void* user_data); // Marks that a new texture frame is available for a given |texture_id|. // Returns true on success or false if the specified texture doesn't exist. // This function can be called from any thread. FLUTTER_EXPORT bool FlutterDesktopTextureRegistrarMarkExternalTextureFrameAvailable( FlutterDesktopTextureRegistrarRef texture_registrar, int64_t texture_id); #if defined(__cplusplus) } // extern "C" #endif #endif // FLUTTER_SHELL_PLATFORM_COMMON_PUBLIC_FLUTTER_TEXTURE_REGISTRAR_H_
engine/shell/platform/common/public/flutter_texture_registrar.h/0
{ "file_path": "engine/shell/platform/common/public/flutter_texture_registrar.h", "repo_id": "engine", "token_count": 2247 }
326
// 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_SHELL_PLATFORM_DARWIN_COMMON_AVAILABILITY_VERSION_CHECK_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_AVAILABILITY_VERSION_CHECK_H_ #include <cstdint> #include <optional> #include <tuple> namespace flutter { using ProductVersion = std::tuple<int32_t /* major */, int32_t /* minor */, int32_t /* patch */>; std::optional<ProductVersion> ProductVersionFromSystemVersionPList(); bool IsEncodedVersionLessThanOrSame(uint32_t encoded_lhs, ProductVersion rhs); } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_AVAILABILITY_VERSION_CHECK_H_
engine/shell/platform/darwin/common/availability_version_check.h/0
{ "file_path": "engine/shell/platform/darwin/common/availability_version_check.h", "repo_id": "engine", "token_count": 264 }
327
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "flutter/shell/platform/darwin/common/framework/Headers/FlutterChannels.h" #import "flutter/shell/platform/darwin/ios/flutter_task_queue_dispatch.h" #import <OCMock/OCMock.h> #import <XCTest/XCTest.h> FLUTTER_ASSERT_ARC @interface MockBinaryMessenger : NSObject <FlutterBinaryMessenger> @property(nonatomic, copy) NSString* channel; @property(nonatomic, strong) NSData* message; @property(nonatomic, strong) NSMutableDictionary<NSString*, FlutterBinaryMessageHandler>* handlers; @end @implementation MockBinaryMessenger - (instancetype)init { self = [super init]; if (self) { _handlers = [[NSMutableDictionary<NSString*, FlutterBinaryMessageHandler> alloc] init]; } return self; } - (void)sendOnChannel:(NSString*)channel message:(NSData* _Nullable)message { [self sendOnChannel:channel message:message binaryReply:nil]; } - (void)sendOnChannel:(NSString*)channel message:(NSData* _Nullable)message binaryReply:(FlutterBinaryReply _Nullable)callback { self.channel = channel; self.message = message; } - (FlutterBinaryMessengerConnection)setMessageHandlerOnChannel:(NSString*)channel binaryMessageHandler: (FlutterBinaryMessageHandler _Nullable)handler { [self.handlers setObject:handler forKey:channel]; return 0; } - (void)cleanUpConnection:(FlutterBinaryMessengerConnection)connection { } @end @interface FlutterChannelsTest : XCTestCase @end @implementation FlutterChannelsTest - (void)testMethodInvoke { NSString* channelName = @"foo"; id binaryMessenger = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); id codec = OCMProtocolMock(@protocol(FlutterMethodCodec)); FlutterMethodChannel* channel = [[FlutterMethodChannel alloc] initWithName:channelName binaryMessenger:binaryMessenger codec:codec]; XCTAssertNotNil(channel); NSData* encodedMethodCall = [@"hey" dataUsingEncoding:NSUTF8StringEncoding]; OCMStub([codec encodeMethodCall:[OCMArg any]]).andReturn(encodedMethodCall); [channel invokeMethod:@"foo" arguments:@[ @(1) ]]; OCMVerify([binaryMessenger sendOnChannel:channelName message:encodedMethodCall]); } - (void)testMethodInvokeWithReply { NSString* channelName = @"foo"; id binaryMessenger = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); id codec = OCMProtocolMock(@protocol(FlutterMethodCodec)); FlutterMethodChannel* channel = [[FlutterMethodChannel alloc] initWithName:channelName binaryMessenger:binaryMessenger codec:codec]; XCTAssertNotNil(channel); NSData* encodedMethodCall = [@"hey" dataUsingEncoding:NSUTF8StringEncoding]; OCMStub([codec encodeMethodCall:[OCMArg any]]).andReturn(encodedMethodCall); XCTestExpectation* didCallReply = [self expectationWithDescription:@"didCallReply"]; OCMExpect([binaryMessenger sendOnChannel:channelName message:encodedMethodCall binaryReply:[OCMArg checkWithBlock:^BOOL(id obj) { FlutterBinaryReply reply = obj; reply(nil); return YES; }]]); [channel invokeMethod:@"foo" arguments:@[ @1 ] result:^(id _Nullable result) { [didCallReply fulfill]; XCTAssertEqual(FlutterMethodNotImplemented, result); }]; OCMVerifyAll(binaryMessenger); [self waitForExpectationsWithTimeout:1.0 handler:nil]; } - (void)testMethodMessageHandler { NSString* channelName = @"foo"; id binaryMessenger = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); id codec = OCMProtocolMock(@protocol(FlutterMethodCodec)); FlutterMethodChannel* channel = [[FlutterMethodChannel alloc] initWithName:channelName binaryMessenger:binaryMessenger codec:codec]; XCTAssertNotNil(channel); NSData* encodedMethodCall = [@"hey" dataUsingEncoding:NSUTF8StringEncoding]; OCMStub([codec encodeMethodCall:[OCMArg any]]).andReturn(encodedMethodCall); FlutterMethodCallHandler handler = ^(FlutterMethodCall* _Nonnull call, FlutterResult _Nonnull result) { }; [channel setMethodCallHandler:handler]; OCMVerify([binaryMessenger setMessageHandlerOnChannel:channelName binaryMessageHandler:[OCMArg isNotNil]]); } - (void)testCallMethodHandler { NSString* channelName = @"foo"; MockBinaryMessenger* binaryMessenger = [[MockBinaryMessenger alloc] init]; id codec = OCMProtocolMock(@protocol(FlutterMethodCodec)); FlutterMethodChannel* channel = [[FlutterMethodChannel alloc] initWithName:channelName binaryMessenger:binaryMessenger codec:codec]; XCTAssertNotNil(channel); NSData* encodedMethodCall = [@"encoded" dataUsingEncoding:NSUTF8StringEncoding]; NSData* replyData = [@"reply" dataUsingEncoding:NSUTF8StringEncoding]; NSData* replyEnvelopeData = [@"reply-envelope" dataUsingEncoding:NSUTF8StringEncoding]; FlutterMethodCall* methodCall = [[FlutterMethodCall alloc] init]; OCMStub([codec decodeMethodCall:encodedMethodCall]).andReturn(methodCall); OCMStub([codec encodeSuccessEnvelope:replyData]).andReturn(replyEnvelopeData); XCTestExpectation* didCallHandler = [self expectationWithDescription:@"didCallHandler"]; XCTestExpectation* didCallReply = [self expectationWithDescription:@"didCallReply"]; FlutterMethodCallHandler handler = ^(FlutterMethodCall* _Nonnull call, FlutterResult _Nonnull result) { XCTAssertEqual(methodCall, call); [didCallHandler fulfill]; result(replyData); }; [channel setMethodCallHandler:handler]; binaryMessenger.handlers[channelName](encodedMethodCall, ^(NSData* reply) { [didCallReply fulfill]; XCTAssertEqual(replyEnvelopeData, reply); }); [self waitForExpectationsWithTimeout:1.0 handler:nil]; } - (void)testResize { NSString* channelName = @"flutter/test"; id binaryMessenger = OCMStrictProtocolMock(@protocol(FlutterBinaryMessenger)); id codec = OCMProtocolMock(@protocol(FlutterMethodCodec)); FlutterBasicMessageChannel* channel = [[FlutterBasicMessageChannel alloc] initWithName:channelName binaryMessenger:binaryMessenger codec:codec]; XCTAssertNotNil(channel); // The expected content was created from the following Dart code: // MethodCall call = MethodCall('resize', ['flutter/test',3]); // StandardMethodCodec().encodeMethodCall(call).buffer.asUint8List(); const unsigned char bytes[] = {7, 6, 114, 101, 115, 105, 122, 101, 12, 2, 7, 12, 102, 108, 117, 116, 116, 101, 114, 47, 116, 101, 115, 116, 3, 3, 0, 0, 0}; NSData* expectedMessage = [NSData dataWithBytes:bytes length:sizeof(bytes)]; OCMExpect([binaryMessenger sendOnChannel:@"dev.flutter/channel-buffers" message:expectedMessage]); [channel resizeChannelBuffer:3]; OCMVerifyAll(binaryMessenger); [binaryMessenger stopMocking]; } - (bool)testSetWarnsOnOverflow { NSString* channelName = @"flutter/test"; id binaryMessenger = OCMStrictProtocolMock(@protocol(FlutterBinaryMessenger)); id codec = OCMProtocolMock(@protocol(FlutterMethodCodec)); FlutterBasicMessageChannel* channel = [[FlutterBasicMessageChannel alloc] initWithName:channelName binaryMessenger:binaryMessenger codec:codec]; XCTAssertNotNil(channel); // The expected content was created from the following Dart code: // MethodCall call = MethodCall('overflow',['flutter/test', true]); // StandardMethodCodec().encodeMethodCall(call).buffer.asUint8List(); const unsigned char bytes[] = {7, 8, 111, 118, 101, 114, 102, 108, 111, 119, 12, 2, 7, 12, 102, 108, 117, 116, 116, 101, 114, 47, 116, 101, 115, 116, 1}; NSData* expectedMessage = [NSData dataWithBytes:bytes length:sizeof(bytes)]; OCMExpect([binaryMessenger sendOnChannel:@"dev.flutter/channel-buffers" message:expectedMessage]); [channel setWarnsOnOverflow:NO]; OCMVerifyAll(binaryMessenger); [binaryMessenger stopMocking]; } - (void)testBasicMessageChannelCleanup { NSString* channelName = @"foo"; FlutterBinaryMessengerConnection connection = 123; id binaryMessenger = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); id codec = OCMProtocolMock(@protocol(FlutterMethodCodec)); FlutterBasicMessageChannel* channel = [[FlutterBasicMessageChannel alloc] initWithName:channelName binaryMessenger:binaryMessenger codec:codec]; FlutterMessageHandler handler = ^(id _Nullable message, FlutterReply callback) { }; OCMStub([binaryMessenger setMessageHandlerOnChannel:channelName binaryMessageHandler:[OCMArg any]]) .andReturn(connection); [channel setMessageHandler:handler]; OCMVerify([binaryMessenger setMessageHandlerOnChannel:channelName binaryMessageHandler:[OCMArg isNotNil]]); [channel setMessageHandler:nil]; OCMVerify([binaryMessenger cleanUpConnection:connection]); } - (void)testMethodChannelCleanup { NSString* channelName = @"foo"; FlutterBinaryMessengerConnection connection = 123; id binaryMessenger = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); id codec = OCMProtocolMock(@protocol(FlutterMethodCodec)); FlutterMethodChannel* channel = [[FlutterMethodChannel alloc] initWithName:channelName binaryMessenger:binaryMessenger codec:codec]; XCTAssertNotNil(channel); OCMStub([binaryMessenger setMessageHandlerOnChannel:channelName binaryMessageHandler:[OCMArg any]]) .andReturn(connection); FlutterMethodCallHandler handler = ^(FlutterMethodCall* _Nonnull call, FlutterResult _Nonnull result) { }; [channel setMethodCallHandler:handler]; OCMVerify([binaryMessenger setMessageHandlerOnChannel:channelName binaryMessageHandler:[OCMArg isNotNil]]); [channel setMethodCallHandler:nil]; OCMVerify([binaryMessenger cleanUpConnection:connection]); } - (void)testBasicMessageChannelTaskQueue { NSString* channelName = @"foo"; FlutterBinaryMessengerConnection connection = 123; id binaryMessenger = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); id codec = OCMProtocolMock(@protocol(FlutterMethodCodec)); id taskQueue = OCMProtocolMock(@protocol(FlutterTaskQueueDispatch)); FlutterBasicMessageChannel* channel = [[FlutterBasicMessageChannel alloc] initWithName:channelName binaryMessenger:binaryMessenger codec:codec taskQueue:taskQueue]; FlutterMessageHandler handler = ^(id _Nullable message, FlutterReply callback) { }; OCMStub([binaryMessenger setMessageHandlerOnChannel:channelName binaryMessageHandler:[OCMArg any] taskQueue:taskQueue]) .andReturn(connection); [channel setMessageHandler:handler]; OCMVerify([binaryMessenger setMessageHandlerOnChannel:channelName binaryMessageHandler:[OCMArg isNotNil] taskQueue:taskQueue]); [channel setMessageHandler:nil]; OCMVerify([binaryMessenger cleanUpConnection:connection]); } - (void)testBasicMessageChannelInvokeHandlerAfterChannelReleased { NSString* channelName = @"foo"; __block NSString* handlerMessage; __block FlutterBinaryMessageHandler messageHandler; @autoreleasepool { FlutterBinaryMessengerConnection connection = 123; id binaryMessenger = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); id codec = OCMProtocolMock(@protocol(FlutterMessageCodec)); id taskQueue = OCMProtocolMock(@protocol(FlutterTaskQueueDispatch)); FlutterBasicMessageChannel* channel = [[FlutterBasicMessageChannel alloc] initWithName:channelName binaryMessenger:binaryMessenger codec:codec taskQueue:taskQueue]; FlutterMessageHandler handler = ^(id _Nullable message, FlutterReply callback) { handlerMessage = message; }; OCMStub([binaryMessenger setMessageHandlerOnChannel:channelName binaryMessageHandler:[OCMArg checkWithBlock:^BOOL( FlutterBinaryMessageHandler handler) { messageHandler = handler; return YES; }] taskQueue:taskQueue]) .andReturn(connection); OCMStub([codec decode:[OCMArg any]]).andReturn(@"decoded message"); [channel setMessageHandler:handler]; } // Channel is released, messageHandler should still retain the codec. The codec // internally makes a `decode` call and updates the `handlerMessage` to "decoded message". messageHandler([NSData data], ^(NSData* data){ }); XCTAssertEqualObjects(handlerMessage, @"decoded message"); } - (void)testMethodChannelInvokeHandlerAfterChannelReleased { NSString* channelName = @"foo"; FlutterBinaryMessengerConnection connection = 123; __block FlutterMethodCall* decodedMethodCall; __block FlutterBinaryMessageHandler messageHandler; @autoreleasepool { id binaryMessenger = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); id codec = OCMProtocolMock(@protocol(FlutterMethodCodec)); id taskQueue = OCMProtocolMock(@protocol(FlutterTaskQueueDispatch)); FlutterMethodChannel* channel = [[FlutterMethodChannel alloc] initWithName:channelName binaryMessenger:binaryMessenger codec:codec taskQueue:taskQueue]; FlutterMethodCallHandler handler = ^(FlutterMethodCall* call, FlutterResult result) { decodedMethodCall = call; }; OCMStub([binaryMessenger setMessageHandlerOnChannel:channelName binaryMessageHandler:[OCMArg checkWithBlock:^BOOL( FlutterBinaryMessageHandler handler) { messageHandler = handler; return YES; }] taskQueue:taskQueue]) .andReturn(connection); OCMStub([codec decodeMethodCall:[OCMArg any]]) .andReturn([FlutterMethodCall methodCallWithMethodName:@"decoded method call" arguments:nil]); [channel setMethodCallHandler:handler]; } messageHandler([NSData data], ^(NSData* data){ }); XCTAssertEqualObjects(decodedMethodCall.method, @"decoded method call"); } - (void)testMethodChannelTaskQueue { NSString* channelName = @"foo"; FlutterBinaryMessengerConnection connection = 123; id binaryMessenger = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); id codec = OCMProtocolMock(@protocol(FlutterMethodCodec)); id taskQueue = OCMProtocolMock(@protocol(FlutterTaskQueueDispatch)); FlutterMethodChannel* channel = [[FlutterMethodChannel alloc] initWithName:channelName binaryMessenger:binaryMessenger codec:codec taskQueue:taskQueue]; XCTAssertNotNil(channel); FlutterMethodCallHandler handler = ^(FlutterMethodCall* call, FlutterResult result) { }; OCMStub([binaryMessenger setMessageHandlerOnChannel:channelName binaryMessageHandler:[OCMArg any] taskQueue:taskQueue]) .andReturn(connection); [channel setMethodCallHandler:handler]; OCMVerify([binaryMessenger setMessageHandlerOnChannel:channelName binaryMessageHandler:[OCMArg isNotNil] taskQueue:taskQueue]); [channel setMethodCallHandler:nil]; OCMVerify([binaryMessenger cleanUpConnection:connection]); } - (void)testEventChannelTaskQueue { NSString* channelName = @"foo"; FlutterBinaryMessengerConnection connection = 123; id binaryMessenger = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); id codec = OCMProtocolMock(@protocol(FlutterMethodCodec)); id taskQueue = OCMProtocolMock(@protocol(FlutterTaskQueueDispatch)); id handler = OCMProtocolMock(@protocol(FlutterStreamHandler)); FlutterEventChannel* channel = [[FlutterEventChannel alloc] initWithName:channelName binaryMessenger:binaryMessenger codec:codec taskQueue:taskQueue]; XCTAssertNotNil(channel); OCMStub([binaryMessenger setMessageHandlerOnChannel:channelName binaryMessageHandler:[OCMArg any] taskQueue:taskQueue]) .andReturn(connection); [channel setStreamHandler:handler]; OCMVerify([binaryMessenger setMessageHandlerOnChannel:channelName binaryMessageHandler:[OCMArg isNotNil] taskQueue:taskQueue]); [channel setStreamHandler:nil]; OCMVerify([binaryMessenger cleanUpConnection:connection]); } @end
engine/shell/platform/darwin/common/framework/Source/FlutterChannelsTest.m/0
{ "file_path": "engine/shell/platform/darwin/common/framework/Source/FlutterChannelsTest.m", "repo_id": "engine", "token_count": 8268 }
328
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "flutter/shell/platform/darwin/graphics/FlutterDarwinContextMetalImpeller.h" #include "flutter/common/graphics/persistent_cache.h" #include "flutter/fml/logging.h" #include "flutter/impeller/renderer/backend/metal/context_mtl.h" #include "flutter/shell/common/context_options.h" #import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" #include "impeller/entity/mtl/entity_shaders.h" #include "impeller/entity/mtl/framebuffer_blend_shaders.h" #include "impeller/entity/mtl/modern_shaders.h" #if IMPELLER_ENABLE_3D #include "impeller/scene/shaders/mtl/scene_shaders.h" // nogncheck #endif // IMPELLER_ENABLE_3D FLUTTER_ASSERT_ARC static std::shared_ptr<impeller::ContextMTL> CreateImpellerContext( const std::shared_ptr<const fml::SyncSwitch>& is_gpu_disabled_sync_switch) { std::vector<std::shared_ptr<fml::Mapping>> shader_mappings = { std::make_shared<fml::NonOwnedMapping>(impeller_entity_shaders_data, impeller_entity_shaders_length), #if IMPELLER_ENABLE_3D std::make_shared<fml::NonOwnedMapping>(impeller_scene_shaders_data, impeller_scene_shaders_length), #endif // IMPELLER_ENABLE_3D std::make_shared<fml::NonOwnedMapping>(impeller_modern_shaders_data, impeller_modern_shaders_length), std::make_shared<fml::NonOwnedMapping>(impeller_framebuffer_blend_shaders_data, impeller_framebuffer_blend_shaders_length), }; auto context = impeller::ContextMTL::Create(shader_mappings, is_gpu_disabled_sync_switch, "Impeller Library"); if (!context) { FML_LOG(ERROR) << "Could not create Metal Impeller Context."; return nullptr; } return context; } @implementation FlutterDarwinContextMetalImpeller - (instancetype)init:(const std::shared_ptr<const fml::SyncSwitch>&)is_gpu_disabled_sync_switch { self = [super init]; if (self != nil) { _context = CreateImpellerContext(is_gpu_disabled_sync_switch); id<MTLDevice> device = _context->GetMTLDevice(); if (!device) { FML_DLOG(ERROR) << "Could not acquire Metal device."; return nil; } CVMetalTextureCacheRef textureCache; CVReturn cvReturn = CVMetalTextureCacheCreate(kCFAllocatorDefault, // allocator nil, // cache attributes (nil default) device, // metal device nil, // texture attributes (nil default) &textureCache // [out] cache ); if (cvReturn != kCVReturnSuccess) { FML_DLOG(ERROR) << "Could not create Metal texture cache."; return nil; } _textureCache.Reset(textureCache); } return self; } - (FlutterDarwinExternalTextureMetal*) createExternalTextureWithIdentifier:(int64_t)textureID texture:(NSObject<FlutterTexture>*)texture { return [[FlutterDarwinExternalTextureMetal alloc] initWithTextureCache:_textureCache textureID:textureID texture:texture enableImpeller:YES]; } @end
engine/shell/platform/darwin/graphics/FlutterDarwinContextMetalImpeller.mm/0
{ "file_path": "engine/shell/platform/darwin/graphics/FlutterDarwinContextMetalImpeller.mm", "repo_id": "engine", "token_count": 1777 }
329
// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_HEADERS_FLUTTERVIEWCONTROLLER_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_HEADERS_FLUTTERVIEWCONTROLLER_H_ #import <UIKit/UIKit.h> #include <sys/cdefs.h> #import "FlutterBinaryMessenger.h" #import "FlutterDartProject.h" #import "FlutterEngine.h" #import "FlutterMacros.h" #import "FlutterPlugin.h" #import "FlutterTexture.h" NS_ASSUME_NONNULL_BEGIN @class FlutterEngine; /** * The name used for semantic update notifications via `NSNotificationCenter`. * * The object passed as the sender is the `FlutterViewController` associated * with the update. */ FLUTTER_DARWIN_EXPORT // NOLINTNEXTLINE(readability-identifier-naming) extern NSNotificationName const FlutterSemanticsUpdateNotification; /** * A `UIViewController` implementation for Flutter views. * * Dart execution, channel communication, texture registration, and plugin registration are all * handled by `FlutterEngine`. Calls on this class to those members all proxy through to the * `FlutterEngine` attached FlutterViewController. * * A FlutterViewController can be initialized either with an already-running `FlutterEngine` via the * `initWithEngine:` initializer, or it can be initialized with a `FlutterDartProject` that will be * used to implicitly spin up a new `FlutterEngine`. Creating a `FlutterEngine` before showing a * FlutterViewController can be used to pre-initialize the Dart VM and to prepare the isolate in * order to reduce the latency to the first rendered frame. See * https://flutter.dev/docs/development/add-to-app/performance for more details on loading * latency. * * Holding a `FlutterEngine` independently of FlutterViewControllers can also be used to not to lose * Dart-related state and asynchronous tasks when navigating back and forth between a * FlutterViewController and other `UIViewController`s. */ FLUTTER_DARWIN_EXPORT #ifdef __IPHONE_13_4 @interface FlutterViewController : UIViewController <FlutterTextureRegistry, FlutterPluginRegistry, UIGestureRecognizerDelegate> #else @interface FlutterViewController : UIViewController <FlutterTextureRegistry, FlutterPluginRegistry> #endif /** * Initializes this FlutterViewController with the specified `FlutterEngine`. * * The initialized viewcontroller will attach itself to the engine as part of this process. * * @param engine The `FlutterEngine` instance to attach to. Cannot be nil. * @param nibName The NIB name to initialize this UIViewController with. * @param nibBundle The NIB bundle. */ - (instancetype)initWithEngine:(FlutterEngine*)engine nibName:(nullable NSString*)nibName bundle:(nullable NSBundle*)nibBundle NS_DESIGNATED_INITIALIZER; /** * Initializes a new FlutterViewController and `FlutterEngine` with the specified * `FlutterDartProject`. * * This will implicitly create a new `FlutterEngine` which is retrievable via the `engine` property * after initialization. * * @param project The `FlutterDartProject` to initialize the `FlutterEngine` with. * @param nibName The NIB name to initialize this UIViewController with. * @param nibBundle The NIB bundle. */ - (instancetype)initWithProject:(nullable FlutterDartProject*)project nibName:(nullable NSString*)nibName bundle:(nullable NSBundle*)nibBundle NS_DESIGNATED_INITIALIZER; /** * Initializes a new FlutterViewController and `FlutterEngine` with the specified * `FlutterDartProject` and `initialRoute`. * * This will implicitly create a new `FlutterEngine` which is retrievable via the `engine` property * after initialization. * * @param project The `FlutterDartProject` to initialize the `FlutterEngine` with. * @param initialRoute The initial `Navigator` route to load. * @param nibName The NIB name to initialize this UIViewController with. * @param nibBundle The NIB bundle. */ - (instancetype)initWithProject:(nullable FlutterDartProject*)project initialRoute:(nullable NSString*)initialRoute nibName:(nullable NSString*)nibName bundle:(nullable NSBundle*)nibBundle NS_DESIGNATED_INITIALIZER; /** * Initializer that is called from loading a FlutterViewController from a XIB. * * See also: * https://developer.apple.com/documentation/foundation/nscoding/1416145-initwithcoder?language=objc */ - (instancetype)initWithCoder:(NSCoder*)aDecoder NS_DESIGNATED_INITIALIZER; /** * Registers a callback that will be invoked when the Flutter view has been rendered. * The callback will be fired only once. * * Replaces an existing callback. Use a `nil` callback to unregister the existing one. */ - (void)setFlutterViewDidRenderCallback:(void (^)(void))callback; /** * Returns the file name for the given asset. * The returned file name can be used to access the asset in the application's * main bundle. * * @param asset The name of the asset. The name can be hierarchical. * @return The file name to be used for lookup in the main bundle. */ - (NSString*)lookupKeyForAsset:(NSString*)asset; /** * Returns the file name for the given asset which originates from the specified * package. * The returned file name can be used to access the asset in the application's * main bundle. * * @param asset The name of the asset. The name can be hierarchical. * @param package The name of the package from which the asset originates. * @return The file name to be used for lookup in the main bundle. */ - (NSString*)lookupKeyForAsset:(NSString*)asset fromPackage:(NSString*)package; /** * Deprecated API to set initial route. * * Attempts to set the first route that the Flutter app shows if the Flutter * runtime hasn't yet started. The default is "/". * * This method must be called immediately after `initWithProject` and has no * effect when using `initWithEngine` if the `FlutterEngine` has already been * run. * * Setting this after the Flutter started running has no effect. See `pushRoute` * and `popRoute` to change the route after Flutter started running. * * This is deprecated because it needs to be called at the time of initialization * and thus should just be in the `initWithProject` initializer. If using * `initWithEngine`, the initial route should be set on the engine's * initializer. * * @param route The name of the first route to show. */ - (void)setInitialRoute:(NSString*)route FLUTTER_DEPRECATED("Use FlutterViewController initializer to specify initial route"); /** * Instructs the Flutter Navigator (if any) to go back. */ - (void)popRoute; /** * Instructs the Flutter Navigator (if any) to push a route on to the navigation * stack. * * @param route The name of the route to push to the navigation stack. */ - (void)pushRoute:(NSString*)route; /** * The `FlutterPluginRegistry` used by this FlutterViewController. */ - (id<FlutterPluginRegistry>)pluginRegistry; /** * A wrapper around UIAccessibilityIsVoiceOverRunning(). * * As a C function, UIAccessibilityIsVoiceOverRunning() cannot be mocked in testing. Mock * this class method to testing features depends on UIAccessibilityIsVoiceOverRunning(). */ + (BOOL)isUIAccessibilityIsVoiceOverRunning; /** * True if at least one frame has rendered and the ViewController has appeared. * * This property is reset to false when the ViewController disappears. It is * guaranteed to only alternate between true and false for observers. */ @property(nonatomic, readonly, getter=isDisplayingFlutterUI) BOOL displayingFlutterUI; /** * Specifies the view to use as a splash screen. Flutter's rendering is asynchronous, so the first * frame rendered by the Flutter application might not immediately appear when the Flutter view is * initially placed in the view hierarchy. The splash screen view will be used as * a replacement until the first frame is rendered. * * The view used should be appropriate for multiple sizes; an autoresizing mask to * have a flexible width and height will be applied automatically. * * Set to nil to remove the splash screen view. */ @property(strong, nonatomic, nullable) UIView* splashScreenView; /** * Attempts to set the `splashScreenView` property from the `UILaunchStoryboardName` from the * main bundle's `Info.plist` file. This method will not change the value of `splashScreenView` * if it cannot find a default one from a storyboard or nib. * * @return `YES` if successful, `NO` otherwise. */ - (BOOL)loadDefaultSplashScreenView; /** * Controls whether the created view will be opaque or not. * * Default is `YES`. Note that setting this to `NO` may negatively impact performance * when using hardware acceleration, and toggling this will trigger a re-layout of the * view. */ @property(nonatomic, getter=isViewOpaque) BOOL viewOpaque; /** * The `FlutterEngine` instance for this view controller. This could be the engine this * `FlutterViewController` is initialized with or a new `FlutterEngine` implicitly created if * no engine was supplied during initialization. */ @property(weak, nonatomic, readonly) FlutterEngine* engine; /** * The `FlutterBinaryMessenger` associated with this FlutterViewController (used for communicating * with channels). * * This is just a convenient way to get the |FlutterEngine|'s binary messenger. */ @property(nonatomic, readonly) NSObject<FlutterBinaryMessenger>* binaryMessenger; /** * If the `FlutterViewController` creates a `FlutterEngine`, this property * determines if that `FlutterEngine` has `allowHeadlessExecution` set. * * The intention is that this is used with the XIB. Otherwise, a * `FlutterEngine` can just be sent to the init methods. * * See also: `-[FlutterEngine initWithName:project:allowHeadlessExecution:]` */ @property(nonatomic, readonly) BOOL engineAllowHeadlessExecution; @end NS_ASSUME_NONNULL_END #endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_HEADERS_FLUTTERVIEWCONTROLLER_H_
engine/shell/platform/darwin/ios/framework/Headers/FlutterViewController.h/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Headers/FlutterViewController.h", "repo_id": "engine", "token_count": 2984 }
330
// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTEREMBEDDERKEYRESPONDER_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTEREMBEDDERKEYRESPONDER_H_ #import <Foundation/NSObject.h> #import <UIKit/UIKit.h> #include "fml/memory/weak_ptr.h" #import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterViewController.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyPrimaryResponder.h" #import "flutter/shell/platform/embedder/embedder.h" typedef void (^FlutterSendKeyEvent)(const FlutterKeyEvent& /* event */, _Nullable FlutterKeyEventCallback /* callback */, void* _Nullable /* user_data */); /** * A primary responder of |FlutterKeyboardManager| that handles events by * sending the converted events through a Dart hook to the framework. * * This class interfaces with the HardwareKeyboard API in the framework. */ @interface FlutterEmbedderKeyResponder : NSObject <FlutterKeyPrimaryResponder> /** * Create an instance by specifying the function to send converted events to. * * The |sendEvent| is typically |FlutterEngine|'s |sendKeyEvent|. */ - (nonnull instancetype)initWithSendEvent:(nonnull FlutterSendKeyEvent)sendEvent; @end #endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTEREMBEDDERKEYRESPONDER_H_
engine/shell/platform/darwin/ios/framework/Source/FlutterEmbedderKeyResponder.h/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterEmbedderKeyResponder.h", "repo_id": "engine", "token_count": 562 }
331
// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERKEYBOARDMANAGER_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERKEYBOARDMANAGER_H_ #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyPrimaryResponder.h" #import <Foundation/NSObject.h> #import <UIKit/UIKit.h> #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyPrimaryResponder.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterKeySecondaryResponder.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterUIPressProxy.h" typedef void (^KeyEventCompleteCallback)(bool, FlutterUIPressProxy* _Nonnull) API_AVAILABLE(ios(13.4)); /** * A hub that manages how key events are dispatched to various Flutter key * responders, and propagates it to the superclass if the Flutter key responders * do not handle it. * * This class manages one or more primary responders, as well as zero or more * secondary responders. * * An event that is received by |handlePresses| is first dispatched to *all* * primary responders. Each primary responder responds *asynchronously* with a * boolean, indicating whether it handles the event. * * An event that is not handled by any primary responders is then passed to to * the first secondary responder (in the chronological order of addition), * which responds *synchronously* with a boolean, indicating whether it handles * the event. If not, the event is passed to the next secondary responder, and * so on. * * The event is then handed back to the |completeCallback| from the original * call to |handlePresses| so that it can respond synchronously to the OS if the * event was not handled by the responders. The |completeCallback| is called on * the platform thread because the platform thread is blocked by a nested event * loop while the response from the framework is being collected, and it needs * to be called on the platform thread to unblock the thread by exiting the * nested event loop. * * Preventing primary responders from receiving events is not supported, because * in reality this class only supports two hardcoded responders * (FlutterChannelKeyResponder and FlutterEmbedderKeyResponder), where the only purpose * of supporting two is to maintain the legacy channel API during the * deprecation window, after which the channel responder should be removed, and * only one primary responder will exist. */ @interface FlutterKeyboardManager : NSObject /** * Add a primary responder, which asynchronously decides whether to handle an * event. */ - (void)addPrimaryResponder:(nonnull id<FlutterKeyPrimaryResponder>)responder; /** * Add a secondary responder, which synchronously decides whether to handle an * event in order if no earlier responders handle. */ - (void)addSecondaryResponder:(nonnull id<FlutterKeySecondaryResponder>)responder; /** * Dispatches a key press event to all responders, gathering their responses, * and then calls the |nextAction| if the event was not handled. */ - (void)handlePress:(nonnull FlutterUIPressProxy*)press nextAction:(nonnull void (^)())next API_AVAILABLE(ios(13.4)); @end #endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERKEYBOARDMANAGER_H_
engine/shell/platform/darwin/ios/framework/Source/FlutterKeyboardManager.h/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterKeyboardManager.h", "repo_id": "engine", "token_count": 966 }
332
// 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 <OCMock/OCMock.h> #import <XCTest/XCTest.h> #import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" #import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterPluginAppLifeCycleDelegate.h" FLUTTER_ASSERT_ARC @interface FlutterPluginAppLifeCycleDelegateTest : XCTestCase @end @implementation FlutterPluginAppLifeCycleDelegateTest - (void)testCreate { FlutterPluginAppLifeCycleDelegate* delegate = [[FlutterPluginAppLifeCycleDelegate alloc] init]; XCTAssertNotNil(delegate); } #if not APPLICATION_EXTENSION_API_ONLY - (void)testDidEnterBackground { XCTNSNotificationExpectation* expectation = [[XCTNSNotificationExpectation alloc] initWithName:UIApplicationDidEnterBackgroundNotification]; FlutterPluginAppLifeCycleDelegate* delegate = [[FlutterPluginAppLifeCycleDelegate alloc] init]; id plugin = OCMProtocolMock(@protocol(FlutterPlugin)); [delegate addDelegate:plugin]; [[NSNotificationCenter defaultCenter] postNotificationName:UIApplicationDidEnterBackgroundNotification object:nil]; [self waitForExpectations:@[ expectation ] timeout:5.0]; OCMVerify([plugin applicationDidEnterBackground:[UIApplication sharedApplication]]); } - (void)testWillEnterForeground { XCTNSNotificationExpectation* expectation = [[XCTNSNotificationExpectation alloc] initWithName:UIApplicationWillEnterForegroundNotification]; FlutterPluginAppLifeCycleDelegate* delegate = [[FlutterPluginAppLifeCycleDelegate alloc] init]; id plugin = OCMProtocolMock(@protocol(FlutterPlugin)); [delegate addDelegate:plugin]; [[NSNotificationCenter defaultCenter] postNotificationName:UIApplicationWillEnterForegroundNotification object:nil]; [self waitForExpectations:@[ expectation ] timeout:5.0]; OCMVerify([plugin applicationWillEnterForeground:[UIApplication sharedApplication]]); } - (void)testWillResignActive { XCTNSNotificationExpectation* expectation = [[XCTNSNotificationExpectation alloc] initWithName:UIApplicationWillResignActiveNotification]; FlutterPluginAppLifeCycleDelegate* delegate = [[FlutterPluginAppLifeCycleDelegate alloc] init]; id plugin = OCMProtocolMock(@protocol(FlutterPlugin)); [delegate addDelegate:plugin]; [[NSNotificationCenter defaultCenter] postNotificationName:UIApplicationWillResignActiveNotification object:nil]; [self waitForExpectations:@[ expectation ] timeout:5.0]; OCMVerify([plugin applicationWillResignActive:[UIApplication sharedApplication]]); } - (void)testDidBecomeActive { XCTNSNotificationExpectation* expectation = [[XCTNSNotificationExpectation alloc] initWithName:UIApplicationDidBecomeActiveNotification]; FlutterPluginAppLifeCycleDelegate* delegate = [[FlutterPluginAppLifeCycleDelegate alloc] init]; id plugin = OCMProtocolMock(@protocol(FlutterPlugin)); [delegate addDelegate:plugin]; [[NSNotificationCenter defaultCenter] postNotificationName:UIApplicationDidBecomeActiveNotification object:nil]; [self waitForExpectations:@[ expectation ] timeout:5.0]; OCMVerify([plugin applicationDidBecomeActive:[UIApplication sharedApplication]]); } - (void)testWillTerminate { XCTNSNotificationExpectation* expectation = [[XCTNSNotificationExpectation alloc] initWithName:UIApplicationWillTerminateNotification]; FlutterPluginAppLifeCycleDelegate* delegate = [[FlutterPluginAppLifeCycleDelegate alloc] init]; id plugin = OCMProtocolMock(@protocol(FlutterPlugin)); [delegate addDelegate:plugin]; [[NSNotificationCenter defaultCenter] postNotificationName:UIApplicationWillTerminateNotification object:nil]; [self waitForExpectations:@[ expectation ] timeout:5.0]; OCMVerify([plugin applicationWillTerminate:[UIApplication sharedApplication]]); } #endif @end
engine/shell/platform/darwin/ios/framework/Source/FlutterPluginAppLifeCycleDelegateTest.mm/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterPluginAppLifeCycleDelegateTest.mm", "repo_id": "engine", "token_count": 1348 }
333
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterEngine.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterTextureRegistryRelay.h" #import <OCMock/OCMock.h> #import <XCTest/XCTest.h> #import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" #import "flutter/shell/platform/darwin/common/framework/Headers/FlutterTexture.h" FLUTTER_ASSERT_ARC @interface FlutterTextureRegistryRelayTest : XCTestCase @end @implementation FlutterTextureRegistryRelayTest - (void)testCreate { id textureRegistry = OCMProtocolMock(@protocol(FlutterTextureRegistry)); FlutterTextureRegistryRelay* relay = [[FlutterTextureRegistryRelay alloc] initWithParent:textureRegistry]; XCTAssertNotNil(relay); XCTAssertEqual(textureRegistry, relay.parent); } - (void)testRegisterTexture { id textureRegistry = OCMProtocolMock(@protocol(FlutterTextureRegistry)); FlutterTextureRegistryRelay* relay = [[FlutterTextureRegistryRelay alloc] initWithParent:textureRegistry]; id texture = OCMProtocolMock(@protocol(FlutterTexture)); [relay registerTexture:texture]; OCMVerify([textureRegistry registerTexture:texture]); } - (void)testTextureFrameAvailable { id textureRegistry = OCMProtocolMock(@protocol(FlutterTextureRegistry)); FlutterTextureRegistryRelay* relay = [[FlutterTextureRegistryRelay alloc] initWithParent:textureRegistry]; [relay textureFrameAvailable:0]; OCMVerify([textureRegistry textureFrameAvailable:0]); } - (void)testUnregisterTexture { id textureRegistry = OCMProtocolMock(@protocol(FlutterTextureRegistry)); FlutterTextureRegistryRelay* relay = [[FlutterTextureRegistryRelay alloc] initWithParent:textureRegistry]; [relay unregisterTexture:0]; OCMVerify([textureRegistry unregisterTexture:0]); } - (void)testRetainCycle { __weak FlutterEngine* weakEngine; NSObject<FlutterTextureRegistry>* strongRelay; @autoreleasepool { FlutterDartProject* project = [[FlutterDartProject alloc] init]; FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar" project:project]; strongRelay = [engine textureRegistry]; weakEngine = engine; } XCTAssertNil(weakEngine); XCTAssertNotNil(strongRelay); } @end
engine/shell/platform/darwin/ios/framework/Source/FlutterTextureRegistryRelayTest.mm/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterTextureRegistryRelayTest.mm", "repo_id": "engine", "token_count": 803 }
334
// 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. // These declarations are an amalgamation of different headers whose // symbols exist in IOKit.framework. The headers have been removed // from the iOS SDKs but all the functions are documented here: // * https://developer.apple.com/documentation/iokit/iokitlib_h?language=objc // * https://developer.apple.com/documentation/iokit/iokit_functions?language=objc // * file:///Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks/IOKit.framework/Versions/A/Headers/IOKitLib.h #if FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG || \ FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_PROFILE #ifndef FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_IOKIT_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_IOKIT_H_ #if defined(__cplusplus) extern "C" { #endif // defined(__cplusplus) #include <CoreFoundation/CoreFoundation.h> #include <mach/mach.h> #include <stdint.h> #define IOKIT #include <device/device_types.h> static const char* kIOServicePlane = "IOService"; typedef io_object_t io_registry_entry_t; typedef io_object_t io_service_t; typedef io_object_t io_connect_t; typedef io_object_t io_iterator_t; enum { kIOReturnSuccess = 0, }; extern const mach_port_t kIOMasterPortDefault; kern_return_t IOObjectRetain(io_object_t object); kern_return_t IOObjectRelease(io_object_t object); boolean_t IOObjectConformsTo(io_object_t object, const io_name_t name); uint32_t IOObjectGetKernelRetainCount(io_object_t object); kern_return_t IOObjectGetClass(io_object_t object, io_name_t name); CFStringRef IOObjectCopyClass(io_object_t object); CFStringRef IOObjectCopySuperclassForClass(CFStringRef name); CFStringRef IOObjectCopyBundleIdentifierForClass(CFStringRef name); io_registry_entry_t IORegistryGetRootEntry(mach_port_t master); kern_return_t IORegistryEntryGetName(io_registry_entry_t entry, io_name_t name); kern_return_t IORegistryEntryGetRegistryEntryID(io_registry_entry_t entry, uint64_t* entryID); kern_return_t IORegistryEntryGetPath(io_registry_entry_t entry, const io_name_t plane, io_string_t path); kern_return_t IORegistryEntryGetProperty(io_registry_entry_t entry, const io_name_t name, io_struct_inband_t buffer, uint32_t* size); kern_return_t IORegistryEntryCreateCFProperties( io_registry_entry_t entry, CFMutableDictionaryRef* properties, CFAllocatorRef allocator, uint32_t options); CFTypeRef IORegistryEntryCreateCFProperty(io_registry_entry_t entry, CFStringRef key, CFAllocatorRef allocator, uint32_t options); kern_return_t IORegistryEntrySetCFProperties(io_registry_entry_t entry, CFTypeRef properties); kern_return_t IORegistryCreateIterator(mach_port_t master, const io_name_t plane, uint32_t options, io_iterator_t* it); kern_return_t IORegistryEntryCreateIterator(io_registry_entry_t entry, const io_name_t plane, uint32_t options, io_iterator_t* it); kern_return_t IORegistryEntryGetChildIterator(io_registry_entry_t entry, const io_name_t plane, io_iterator_t* it); kern_return_t IORegistryEntryGetParentIterator(io_registry_entry_t entry, const io_name_t plane, io_iterator_t* it); io_object_t IOIteratorNext(io_iterator_t it); boolean_t IOIteratorIsValid(io_iterator_t it); void IOIteratorReset(io_iterator_t it); CFMutableDictionaryRef IOServiceMatching(const char* name) CF_RETURNS_RETAINED; CFMutableDictionaryRef IOServiceNameMatching(const char* name) CF_RETURNS_RETAINED; io_service_t IOServiceGetMatchingService( mach_port_t master, CFDictionaryRef matching CF_RELEASES_ARGUMENT); kern_return_t IOServiceGetMatchingServices( mach_port_t master, CFDictionaryRef matching CF_RELEASES_ARGUMENT, io_iterator_t* it); #if __cplusplus } #endif // __cplusplus #endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_IOKIT_H_ #endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_IOKIT_H_ // defined(FLUTTER_RUNTIME_MODE_PROFILE)
engine/shell/platform/darwin/ios/framework/Source/IOKit.h/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Source/IOKit.h", "repo_id": "engine", "token_count": 2385 }
335
// 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 <UIKit/UIKit.h> #import "flutter/shell/platform/darwin/ios/framework/Source/accessibility_bridge.h" #import "flutter/shell/platform/darwin/ios/framework/Source/accessibility_text_entry.h" static const UIAccessibilityTraits kUIAccessibilityTraitUndocumentedEmptyLine = 0x800000000000; @implementation FlutterInactiveTextInput { } @synthesize tokenizer = _tokenizer; @synthesize beginningOfDocument = _beginningOfDocument; @synthesize endOfDocument = _endOfDocument; - (void)dealloc { [_text release]; [_markedText release]; [_markedTextRange release]; [_selectedTextRange release]; [_markedTextStyle release]; [super dealloc]; } - (BOOL)hasText { return self.text.length > 0; } - (NSString*)textInRange:(UITextRange*)range { if (!range) { return nil; } NSAssert([range isKindOfClass:[FlutterTextRange class]], @"Expected a FlutterTextRange for range (got %@).", [range class]); NSRange textRange = ((FlutterTextRange*)range).range; NSAssert(textRange.location != NSNotFound, @"Expected a valid text range."); return [self.text substringWithRange:textRange]; } - (void)replaceRange:(UITextRange*)range withText:(NSString*)text { // This method is required but not called by accessibility API for // features we are using it for. It may need to be implemented if // requirements change. } - (void)setMarkedText:(NSString*)markedText selectedRange:(NSRange)markedSelectedRange { // This method is required but not called by accessibility API for // features we are using it for. It may need to be implemented if // requirements change. } - (void)unmarkText { // This method is required but not called by accessibility API for // features we are using it for. It may need to be implemented if // requirements change. } - (UITextRange*)textRangeFromPosition:(UITextPosition*)fromPosition toPosition:(UITextPosition*)toPosition { NSUInteger fromIndex = ((FlutterTextPosition*)fromPosition).index; NSUInteger toIndex = ((FlutterTextPosition*)toPosition).index; return [FlutterTextRange rangeWithNSRange:NSMakeRange(fromIndex, toIndex - fromIndex)]; } - (UITextPosition*)positionFromPosition:(UITextPosition*)position offset:(NSInteger)offset { // This method is required but not called by accessibility API for // features we are using it for. It may need to be implemented if // requirements change. return nil; } - (UITextPosition*)positionFromPosition:(UITextPosition*)position inDirection:(UITextLayoutDirection)direction offset:(NSInteger)offset { // This method is required but not called by accessibility API for // features we are using it for. It may need to be implemented if // requirements change. return nil; } - (NSComparisonResult)comparePosition:(UITextPosition*)position toPosition:(UITextPosition*)other { // This method is required but not called by accessibility API for // features we are using it for. It may need to be implemented if // requirements change. return NSOrderedSame; } - (NSInteger)offsetFromPosition:(UITextPosition*)from toPosition:(UITextPosition*)toPosition { // This method is required but not called by accessibility API for // features we are using it for. It may need to be implemented if // requirements change. return 0; } - (UITextPosition*)positionWithinRange:(UITextRange*)range farthestInDirection:(UITextLayoutDirection)direction { // This method is required but not called by accessibility API for // features we are using it for. It may need to be implemented if // requirements change. return nil; } - (UITextRange*)characterRangeByExtendingPosition:(UITextPosition*)position inDirection:(UITextLayoutDirection)direction { // This method is required but not called by accessibility API for // features we are using it for. It may need to be implemented if // requirements change. return nil; } - (UITextWritingDirection)baseWritingDirectionForPosition:(UITextPosition*)position inDirection:(UITextStorageDirection)direction { // Not editable. Does not apply. return UITextWritingDirectionNatural; } - (void)setBaseWritingDirection:(UITextWritingDirection)writingDirection forRange:(UITextRange*)range { // Not editable. Does not apply. } - (CGRect)firstRectForRange:(UITextRange*)range { // This method is required but not called by accessibility API for // features we are using it for. It may need to be implemented if // requirements change. return CGRectZero; } - (CGRect)caretRectForPosition:(UITextPosition*)position { // This method is required but not called by accessibility API for // features we are using it for. It may need to be implemented if // requirements change. return CGRectZero; } - (UITextPosition*)closestPositionToPoint:(CGPoint)point { // This method is required but not called by accessibility API for // features we are using it for. It may need to be implemented if // requirements change. return nil; } - (UITextPosition*)closestPositionToPoint:(CGPoint)point withinRange:(UITextRange*)range { // This method is required but not called by accessibility API for // features we are using it for. It may need to be implemented if // requirements change. return nil; } - (NSArray*)selectionRectsForRange:(UITextRange*)range { // This method is required but not called by accessibility API for // features we are using it for. It may need to be implemented if // requirements change. return @[]; } - (UITextRange*)characterRangeAtPoint:(CGPoint)point { // This method is required but not called by accessibility API for // features we are using it for. It may need to be implemented if // requirements change. return nil; } - (void)insertText:(NSString*)text { // This method is required but not called by accessibility API for // features we are using it for. It may need to be implemented if // requirements change. } - (void)deleteBackward { // This method is required but not called by accessibility API for // features we are using it for. It may need to be implemented if // requirements change. } @end @implementation TextInputSemanticsObject { FlutterInactiveTextInput* _inactive_text_input; } - (instancetype)initWithBridge:(fml::WeakPtr<flutter::AccessibilityBridgeIos>)bridge uid:(int32_t)uid { self = [super initWithBridge:bridge uid:uid]; if (self) { _inactive_text_input = [[FlutterInactiveTextInput alloc] init]; } return self; } - (void)dealloc { [_inactive_text_input release]; [super dealloc]; } #pragma mark - SemanticsObject overrides - (void)setSemanticsNode:(const flutter::SemanticsNode*)node { [super setSemanticsNode:node]; _inactive_text_input.text = @(node->value.data()); FlutterTextInputView* textInput = (FlutterTextInputView*)[self bridge]->textInputView(); if ([self node].HasFlag(flutter::SemanticsFlags::kIsFocused)) { textInput.backingTextInputAccessibilityObject = self; // The text input view must have a non-trivial size for the accessibility // system to send text editing events. textInput.frame = CGRectMake(0.0, 0.0, 1.0, 1.0); } else if (textInput.backingTextInputAccessibilityObject == self) { textInput.backingTextInputAccessibilityObject = nil; } } #pragma mark - UIAccessibility overrides /** * The UITextInput whose accessibility properties we present to UIKit as * substitutes for Flutter's text field properties. * * When the field is currently focused (i.e. it is being edited), we use * the FlutterTextInputView used by FlutterTextInputPlugin. Otherwise, * we use an FlutterInactiveTextInput. */ - (UIView<UITextInput>*)textInputSurrogate { if ([self node].HasFlag(flutter::SemanticsFlags::kIsFocused)) { return [self bridge]->textInputView(); } else { return _inactive_text_input; } } - (UIView*)textInputView { return [self textInputSurrogate]; } - (void)accessibilityElementDidBecomeFocused { if (![self isAccessibilityBridgeAlive]) { return; } [[self textInputSurrogate] accessibilityElementDidBecomeFocused]; [super accessibilityElementDidBecomeFocused]; } - (void)accessibilityElementDidLoseFocus { if (![self isAccessibilityBridgeAlive]) { return; } [[self textInputSurrogate] accessibilityElementDidLoseFocus]; [super accessibilityElementDidLoseFocus]; } - (BOOL)accessibilityElementIsFocused { if (![self isAccessibilityBridgeAlive]) { return false; } return [self node].HasFlag(flutter::SemanticsFlags::kIsFocused); } - (BOOL)accessibilityActivate { if (![self isAccessibilityBridgeAlive]) { return false; } return [[self textInputSurrogate] accessibilityActivate]; } - (NSString*)accessibilityLabel { if (![self isAccessibilityBridgeAlive]) { return nil; } NSString* label = [super accessibilityLabel]; if (label != nil) { return label; } return [self textInputSurrogate].accessibilityLabel; } - (NSString*)accessibilityHint { if (![self isAccessibilityBridgeAlive]) { return nil; } NSString* hint = [super accessibilityHint]; if (hint != nil) { return hint; } return [self textInputSurrogate].accessibilityHint; } - (NSString*)accessibilityValue { if (![self isAccessibilityBridgeAlive]) { return nil; } NSString* value = [super accessibilityValue]; if (value != nil) { return value; } return [self textInputSurrogate].accessibilityValue; } - (UIAccessibilityTraits)accessibilityTraits { if (![self isAccessibilityBridgeAlive]) { return 0; } // Adding UIAccessibilityTraitKeyboardKey to the trait list so that iOS treats it like // a keyboard entry control, thus adding support for text editing features, such as // pinch to select text, and up/down fling to move cursor. UIAccessibilityTraits results = [super accessibilityTraits] | [self textInputSurrogate].accessibilityTraits | UIAccessibilityTraitKeyboardKey; // We remove an undocumented flag to get rid of a bug where single-tapping // a text input field incorrectly says "empty line". // See also: https://github.com/flutter/flutter/issues/52487 return results & (~kUIAccessibilityTraitUndocumentedEmptyLine); } #pragma mark - UITextInput overrides - (NSString*)textInRange:(UITextRange*)range { return [[self textInputSurrogate] textInRange:range]; } - (void)replaceRange:(UITextRange*)range withText:(NSString*)text { return [[self textInputSurrogate] replaceRange:range withText:text]; } - (BOOL)shouldChangeTextInRange:(UITextRange*)range replacementText:(NSString*)text { return [[self textInputSurrogate] shouldChangeTextInRange:range replacementText:text]; } - (UITextRange*)selectedTextRange { return [[self textInputSurrogate] selectedTextRange]; } - (void)setSelectedTextRange:(UITextRange*)range { [[self textInputSurrogate] setSelectedTextRange:range]; } - (UITextRange*)markedTextRange { return [[self textInputSurrogate] markedTextRange]; } - (NSDictionary*)markedTextStyle { return [[self textInputSurrogate] markedTextStyle]; } - (void)setMarkedTextStyle:(NSDictionary*)style { [[self textInputSurrogate] setMarkedTextStyle:style]; } - (void)setMarkedText:(NSString*)markedText selectedRange:(NSRange)selectedRange { [[self textInputSurrogate] setMarkedText:markedText selectedRange:selectedRange]; } - (void)unmarkText { [[self textInputSurrogate] unmarkText]; } - (UITextStorageDirection)selectionAffinity { return [[self textInputSurrogate] selectionAffinity]; } - (UITextPosition*)beginningOfDocument { return [[self textInputSurrogate] beginningOfDocument]; } - (UITextPosition*)endOfDocument { return [[self textInputSurrogate] endOfDocument]; } - (id<UITextInputDelegate>)inputDelegate { return [[self textInputSurrogate] inputDelegate]; } - (void)setInputDelegate:(id<UITextInputDelegate>)delegate { [[self textInputSurrogate] setInputDelegate:delegate]; } - (id<UITextInputTokenizer>)tokenizer { return [[self textInputSurrogate] tokenizer]; } - (UITextRange*)textRangeFromPosition:(UITextPosition*)fromPosition toPosition:(UITextPosition*)toPosition { return [[self textInputSurrogate] textRangeFromPosition:fromPosition toPosition:toPosition]; } - (UITextPosition*)positionFromPosition:(UITextPosition*)position offset:(NSInteger)offset { return [[self textInputSurrogate] positionFromPosition:position offset:offset]; } - (UITextPosition*)positionFromPosition:(UITextPosition*)position inDirection:(UITextLayoutDirection)direction offset:(NSInteger)offset { return [[self textInputSurrogate] positionFromPosition:position inDirection:direction offset:offset]; } - (NSComparisonResult)comparePosition:(UITextPosition*)position toPosition:(UITextPosition*)other { return [[self textInputSurrogate] comparePosition:position toPosition:other]; } - (NSInteger)offsetFromPosition:(UITextPosition*)from toPosition:(UITextPosition*)toPosition { return [[self textInputSurrogate] offsetFromPosition:from toPosition:toPosition]; } - (UITextPosition*)positionWithinRange:(UITextRange*)range farthestInDirection:(UITextLayoutDirection)direction { return [[self textInputSurrogate] positionWithinRange:range farthestInDirection:direction]; } - (UITextRange*)characterRangeByExtendingPosition:(UITextPosition*)position inDirection:(UITextLayoutDirection)direction { return [[self textInputSurrogate] characterRangeByExtendingPosition:position inDirection:direction]; } - (UITextWritingDirection)baseWritingDirectionForPosition:(UITextPosition*)position inDirection:(UITextStorageDirection)direction { return [[self textInputSurrogate] baseWritingDirectionForPosition:position inDirection:direction]; } - (void)setBaseWritingDirection:(UITextWritingDirection)writingDirection forRange:(UITextRange*)range { [[self textInputSurrogate] setBaseWritingDirection:writingDirection forRange:range]; } - (CGRect)firstRectForRange:(UITextRange*)range { return [[self textInputSurrogate] firstRectForRange:range]; } - (CGRect)caretRectForPosition:(UITextPosition*)position { return [[self textInputSurrogate] caretRectForPosition:position]; } - (UITextPosition*)closestPositionToPoint:(CGPoint)point { return [[self textInputSurrogate] closestPositionToPoint:point]; } - (UITextPosition*)closestPositionToPoint:(CGPoint)point withinRange:(UITextRange*)range { return [[self textInputSurrogate] closestPositionToPoint:point withinRange:range]; } - (NSArray*)selectionRectsForRange:(UITextRange*)range { return [[self textInputSurrogate] selectionRectsForRange:range]; } - (UITextRange*)characterRangeAtPoint:(CGPoint)point { return [[self textInputSurrogate] characterRangeAtPoint:point]; } - (void)insertText:(NSString*)text { [[self textInputSurrogate] insertText:text]; } - (void)deleteBackward { [[self textInputSurrogate] deleteBackward]; } #pragma mark - UIKeyInput overrides - (BOOL)hasText { return [[self textInputSurrogate] hasText]; } @end
engine/shell/platform/darwin/ios/framework/Source/accessibility_text_entry.mm/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Source/accessibility_text_entry.mm", "repo_id": "engine", "token_count": 5227 }
336
// 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_SHELL_PLATFORM_DARWIN_IOS_IOS_CONTEXT_METAL_SKIA_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_IOS_CONTEXT_METAL_SKIA_H_ #include <Metal/Metal.h> #include "flutter/fml/macros.h" #include "flutter/fml/platform/darwin/cf_utils.h" #include "flutter/fml/platform/darwin/scoped_nsobject.h" #import "flutter/shell/platform/darwin/graphics/FlutterDarwinContextMetalSkia.h" #import "flutter/shell/platform/darwin/ios/ios_context.h" #include "third_party/skia/include/gpu/GrDirectContext.h" namespace flutter { class IOSContextMetalSkia final : public IOSContext { public: explicit IOSContextMetalSkia(MsaaSampleCount msaa_samples); ~IOSContextMetalSkia(); fml::scoped_nsobject<FlutterDarwinContextMetalSkia> GetDarwinContext() const; // |IOSContext| IOSRenderingBackend GetBackend() const override; // |IOSContext| sk_sp<GrDirectContext> GetMainContext() const override; sk_sp<GrDirectContext> GetResourceContext() const; private: fml::scoped_nsobject<FlutterDarwinContextMetalSkia> darwin_context_metal_; // |IOSContext| sk_sp<GrDirectContext> CreateResourceContext() override; // |IOSContext| std::unique_ptr<GLContextResult> MakeCurrent() override; // |IOSContext| std::unique_ptr<Texture> CreateExternalTexture( int64_t texture_id, fml::scoped_nsobject<NSObject<FlutterTexture>> texture) override; FML_DISALLOW_COPY_AND_ASSIGN(IOSContextMetalSkia); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_IOS_CONTEXT_METAL_SKIA_H_
engine/shell/platform/darwin/ios/ios_context_metal_skia.h/0
{ "file_path": "engine/shell/platform/darwin/ios/ios_context_metal_skia.h", "repo_id": "engine", "token_count": 624 }
337
// 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_SHELL_PLATFORM_DARWIN_IOS_PLATFORM_MESSAGE_HANDLER_IOS_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_PLATFORM_MESSAGE_HANDLER_IOS_H_ #include <unordered_map> #include "flutter/common/task_runners.h" #include "flutter/fml/platform/darwin/scoped_block.h" #include "flutter/fml/platform/darwin/scoped_nsobject.h" #include "flutter/shell/common/platform_message_handler.h" #import "flutter/shell/platform/darwin/common/framework/Headers/FlutterBinaryMessenger.h" #import "flutter/shell/platform/darwin/ios/flutter_task_queue_dispatch.h" namespace flutter { class PlatformMessageHandlerIos : public PlatformMessageHandler { public: static NSObject<FlutterTaskQueue>* MakeBackgroundTaskQueue(); explicit PlatformMessageHandlerIos(fml::RefPtr<fml::TaskRunner> platform_task_runner); void HandlePlatformMessage(std::unique_ptr<PlatformMessage> message) override; bool DoesHandlePlatformMessageOnPlatformThread() const override; void InvokePlatformMessageResponseCallback(int response_id, std::unique_ptr<fml::Mapping> mapping) override; void InvokePlatformMessageEmptyResponseCallback(int response_id) override; void SetMessageHandler(const std::string& channel, FlutterBinaryMessageHandler handler, NSObject<FlutterTaskQueue>* task_queue); struct HandlerInfo { fml::scoped_nsprotocol<NSObject<FlutterTaskQueueDispatch>*> task_queue; fml::ScopedBlock<FlutterBinaryMessageHandler> handler; }; private: std::unordered_map<std::string, HandlerInfo> message_handlers_; const fml::RefPtr<fml::TaskRunner> platform_task_runner_; std::mutex message_handlers_mutex_; FML_DISALLOW_COPY_AND_ASSIGN(PlatformMessageHandlerIos); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_PLATFORM_MESSAGE_HANDLER_IOS_H_
engine/shell/platform/darwin/ios/platform_message_handler_ios.h/0
{ "file_path": "engine/shell/platform/darwin/ios/platform_message_handler_ios.h", "repo_id": "engine", "token_count": 742 }
338
// 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_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_HEADERS_FLUTTERVIEWCONTROLLER_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_HEADERS_FLUTTERVIEWCONTROLLER_H_ #import <Cocoa/Cocoa.h> #import "FlutterEngine.h" #import "FlutterMacros.h" #import "FlutterPlatformViews.h" #import "FlutterPluginRegistrarMacOS.h" /** * Values for the `mouseTrackingMode` property. */ typedef NS_ENUM(NSInteger, FlutterMouseTrackingMode) { // Hover events will never be sent to Flutter. kFlutterMouseTrackingModeNone = 0, // NOLINTNEXTLINE(readability-identifier-naming) FlutterMouseTrackingModeNone __attribute__((deprecated)) = kFlutterMouseTrackingModeNone, // Hover events will be sent to Flutter when the view is in the key window. kFlutterMouseTrackingModeInKeyWindow = 1, // NOLINTNEXTLINE(readability-identifier-naming) FlutterMouseTrackingModeInKeyWindow __attribute__((deprecated)) = kFlutterMouseTrackingModeInKeyWindow, // Hover events will be sent to Flutter when the view is in the active app. kFlutterMouseTrackingModeInActiveApp = 2, // NOLINTNEXTLINE(readability-identifier-naming) FlutterMouseTrackingModeInActiveApp __attribute__((deprecated)) = kFlutterMouseTrackingModeInActiveApp, // Hover events will be sent to Flutter regardless of window and app focus. kFlutterMouseTrackingModeAlways = 3, // NOLINTNEXTLINE(readability-identifier-naming) FlutterMouseTrackingModeAlways __attribute__((deprecated)) = kFlutterMouseTrackingModeAlways, }; /** * Controls a view that displays Flutter content and manages input. * * A FlutterViewController works with a FlutterEngine. Upon creation, the view * controller is always added to an engine, either a given engine, or it implicitly * creates an engine and add itself to that engine. * * The FlutterEngine assigns each view controller attached to it a unique ID. * Each view controller corresponds to a view, and the ID is used by the framework * to specify which view to operate. * * A FlutterViewController can also be unattached to an engine after it is manually * unset from the engine, or transiently during the initialization process. * An unattached view controller is invalid. Whether the view controller is attached * can be queried using FlutterViewController#attached. * * The FlutterViewController strongly references the FlutterEngine, while * the engine weakly the view controller. When a FlutterViewController is deallocated, * it automatically removes itself from its attached engine. When a FlutterEngine * has no FlutterViewControllers attached, it might shut down itself or not depending * on its configuration. */ FLUTTER_DARWIN_EXPORT @interface FlutterViewController : NSViewController <FlutterPluginRegistry> /** * The Flutter engine associated with this view controller. */ @property(nonatomic, nonnull, readonly) FlutterEngine* engine; /** * The style of mouse tracking to use for the view. Defaults to * FlutterMouseTrackingModeInKeyWindow. */ @property(nonatomic) FlutterMouseTrackingMode mouseTrackingMode; /** * Initializes a controller that will run the given project. * * In this initializer, this controller creates an engine, and is attached to * that engine as the default controller. In this way, this controller can not * be set to other engines. This initializer is suitable for the first Flutter * view controller of the app. To use the controller with an existing engine, * use initWithEngine:nibName:bundle: instead. * * @param project The project to run in this view controller. If nil, a default `FlutterDartProject` * will be used. */ - (nonnull instancetype)initWithProject:(nullable FlutterDartProject*)project NS_DESIGNATED_INITIALIZER; - (nonnull instancetype)initWithNibName:(nullable NSString*)nibNameOrNil bundle:(nullable NSBundle*)nibBundleOrNil NS_DESIGNATED_INITIALIZER; - (nonnull instancetype)initWithCoder:(nonnull NSCoder*)nibNameOrNil NS_DESIGNATED_INITIALIZER; /** * Initializes this FlutterViewController with an existing `FlutterEngine`. * * The initialized view controller will add itself to the engine as part of this process. * * This initializer is suitable for both the first Flutter view controller and * the following ones of the app. * * @param engine The `FlutterEngine` instance to attach to. Cannot be nil. * @param nibName The NIB name to initialize this controller with. * @param nibBundle The NIB bundle. */ - (nonnull instancetype)initWithEngine:(nonnull FlutterEngine*)engine nibName:(nullable NSString*)nibName bundle:(nullable NSBundle*)nibBundle NS_DESIGNATED_INITIALIZER; /** * Return YES if the view controller is attached to an engine. */ - (BOOL)attached; /** * Invoked by the engine right before the engine is restarted. * * This should reset states to as if the application has just started. It * usually indicates a hot restart (Shift-R in Flutter CLI.) */ - (void)onPreEngineRestart; /** * Returns the file name for the given asset. * The returned file name can be used to access the asset in the application's * main bundle. * * @param asset The name of the asset. The name can be hierarchical. * @return The file name to be used for lookup in the main bundle. */ - (nonnull NSString*)lookupKeyForAsset:(nonnull NSString*)asset; /** * Returns the file name for the given asset which originates from the specified * package. * The returned file name can be used to access the asset in the application's * main bundle. * * @param asset The name of the asset. The name can be hierarchical. * @param package The name of the package from which the asset originates. * @return The file name to be used for lookup in the main bundle. */ - (nonnull NSString*)lookupKeyForAsset:(nonnull NSString*)asset fromPackage:(nonnull NSString*)package; /** * The contentView (FlutterView)'s background color is set to black during * its instantiation. * * The containing layer's color can be set to the NSColor provided to this method. * * For example, the background may be set after the FlutterViewController * is instantiated in MainFlutterWindow.swift in the Flutter project. * ```swift * import Cocoa * import FlutterMacOS * * class MainFlutterWindow: NSWindow { * override func awakeFromNib() { * let flutterViewController = FlutterViewController() * * // The background color of the window and `FlutterViewController` * // are retained separately. * // * // In this example, both the MainFlutterWindow and FlutterViewController's * // FlutterView's backgroundColor are set to clear to achieve a fully * // transparent effect. * // * // If the window's background color is not set, it will use the system * // default. * // * // If the `FlutterView`'s color is not set via `FlutterViewController.setBackgroundColor` * // it's default will be black. * self.backgroundColor = NSColor.clear * flutterViewController.backgroundColor = NSColor.clear * * let windowFrame = self.frame * self.contentViewController = flutterViewController * self.setFrame(windowFrame, display: true) * * RegisterGeneratedPlugins(registry: flutterViewController) * * super.awakeFromNib() * } * } * ``` */ @property(readwrite, nonatomic, nullable, copy) NSColor* backgroundColor; @end #endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_HEADERS_FLUTTERVIEWCONTROLLER_H_
engine/shell/platform/darwin/macos/framework/Headers/FlutterViewController.h/0
{ "file_path": "engine/shell/platform/darwin/macos/framework/Headers/FlutterViewController.h", "repo_id": "engine", "token_count": 2369 }
339
// 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_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERCOMPOSITOR_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERCOMPOSITOR_H_ #include <functional> #include <list> #include "flutter/fml/macros.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterPlatformViewController.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterTimeConverter.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewProvider.h" #include "flutter/shell/platform/embedder/embedder.h" @class FlutterMutatorView; namespace flutter { class PlatformViewLayer; typedef std::pair<PlatformViewLayer, size_t> PlatformViewLayerWithIndex; // FlutterCompositor creates and manages the backing stores used for // rendering Flutter content and presents Flutter content and Platform views. // Platform views are not yet supported. // // TODO(cbracken): refactor for testability. https://github.com/flutter/flutter/issues/137648 class FlutterCompositor { public: // Create a FlutterCompositor with a view provider. // // The view_provider is used to query FlutterViews from view IDs, // which are used for presenting and creating backing stores. // It must not be null, and is typically FlutterViewEngineProvider. explicit FlutterCompositor(id<FlutterViewProvider> view_provider, FlutterTimeConverter* time_converter, FlutterPlatformViewController* platform_views_controller); ~FlutterCompositor() = default; // Creates a backing store and saves updates the backing_store_out data with // the new FlutterBackingStore data. // // If the backing store is being requested for the first time for a given // frame, this compositor does not create a new backing store but rather // returns the backing store associated with the FlutterView's // FlutterSurfaceManager. // // Any additional state allocated for the backing store and saved as // user_data in the backing store must be collected in the backing_store's // destruction_callback field which will be called when the embedder collects // the backing store. bool CreateBackingStore(const FlutterBackingStoreConfig* config, FlutterBackingStore* backing_store_out); // Presents the FlutterLayers by updating the FlutterView specified by // `view_id` using the layer content. Sets frame_started_ to false. bool Present(FlutterViewId view_id, const FlutterLayer** layers, size_t layers_count); private: void PresentPlatformViews(FlutterView* default_base_view, const std::vector<PlatformViewLayerWithIndex>& platform_views_layers); // Presents the platform view layer represented by `layer`. `layer_index` is // used to position the layer in the z-axis. If the layer does not have a // superview, it will become subview of `default_base_view`. FlutterMutatorView* PresentPlatformView(FlutterView* default_base_view, const PlatformViewLayer& layer, size_t index); // Where the compositor can query FlutterViews. Must not be null. id<FlutterViewProvider> const view_provider_; // Converts between engine time and core animation media time. FlutterTimeConverter* const time_converter_; // The controller used to manage creation and deletion of platform views. const FlutterPlatformViewController* platform_view_controller_; // Platform view to FlutterMutatorView that contains it. NSMapTable<NSView*, FlutterMutatorView*>* mutator_views_; FML_DISALLOW_COPY_AND_ASSIGN(FlutterCompositor); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERCOMPOSITOR_H_
engine/shell/platform/darwin/macos/framework/Source/FlutterCompositor.h/0
{ "file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterCompositor.h", "repo_id": "engine", "token_count": 1296 }
340
// 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_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTEREXTERNALTEXTURE_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTEREXTERNALTEXTURE_H_ #import <Foundation/Foundation.h> #import "flutter/shell/platform/darwin/graphics/FlutterDarwinContextMetalSkia.h" #include "flutter/shell/platform/embedder/embedder.h" /** * Embedding side texture wrappers for Metal external textures. * Used to bridge FlutterTexture object and handle the texture copy request the * Flutter engine. */ @interface FlutterExternalTexture : NSObject /** * Initializes a texture adapter with |texture|. */ - (nonnull instancetype)initWithFlutterTexture:(nonnull id<FlutterTexture>)texture darwinMetalContext:(nonnull FlutterDarwinContextMetalSkia*)context; /** * Returns the ID for the FlutterExternalTexture instance. */ - (int64_t)textureID; /** * Accepts texture buffer copy request from the Flutter engine. * When the user side marks the textureID as available, the Flutter engine will * callback to this method and ask for populate the |metalTexture| object, * such as the texture type and the format of the pixel buffer and the texture object. */ - (BOOL)populateTexture:(nonnull FlutterMetalExternalTexture*)metalTexture; @end #endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTEREXTERNALTEXTURE_H_
engine/shell/platform/darwin/macos/framework/Source/FlutterExternalTexture.h/0
{ "file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterExternalTexture.h", "repo_id": "engine", "token_count": 492 }
341
// 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_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERPLATFORMNODEDELEGATEMAC_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERPLATFORMNODEDELEGATEMAC_H_ #import <Cocoa/Cocoa.h> #import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterViewController.h" #include "flutter/fml/macros.h" #include "flutter/shell/platform/common/accessibility_bridge.h" #include "flutter/shell/platform/common/flutter_platform_node_delegate.h" #include "flutter/shell/platform/embedder/embedder.h" namespace flutter { //------------------------------------------------------------------------------ /// The macOS implementation of FlutterPlatformNodeDelegate. This class uses /// AXPlatformNodeMac to manage the macOS-specific accessibility objects. class FlutterPlatformNodeDelegateMac : public FlutterPlatformNodeDelegate { public: FlutterPlatformNodeDelegateMac(std::weak_ptr<AccessibilityBridge> bridge, __weak FlutterViewController* view_controller); virtual ~FlutterPlatformNodeDelegateMac(); void Init(std::weak_ptr<OwnerBridge> bridge, ui::AXNode* node) override; //--------------------------------------------------------------------------- /// @brief Gets the live region text of this node in UTF-8 format. This /// is useful to determine the changes in between semantics /// updates when generating accessibility events. std::string GetLiveRegionText() const; // |ui::AXPlatformNodeDelegate| gfx::NativeViewAccessible GetNativeViewAccessible() override; // |ui::AXPlatformNodeDelegate| gfx::NativeViewAccessible GetNSWindow() override; // |FlutterPlatformNodeDelegate| gfx::NativeViewAccessible GetParent() override; // |FlutterPlatformNodeDelegate| gfx::Rect GetBoundsRect( const ui::AXCoordinateSystem coordinate_system, const ui::AXClippingBehavior clipping_behavior, ui::AXOffscreenResult* offscreen_result) const override; private: ui::AXPlatformNode* ax_platform_node_; std::weak_ptr<AccessibilityBridge> bridge_; __weak FlutterViewController* view_controller_; gfx::RectF ConvertBoundsFromLocalToScreen( const gfx::RectF& local_bounds) const; gfx::RectF ConvertBoundsFromScreenToGlobal( const gfx::RectF& window_bounds) const; FML_DISALLOW_COPY_AND_ASSIGN(FlutterPlatformNodeDelegateMac); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERPLATFORMNODEDELEGATEMAC_H_
engine/shell/platform/darwin/macos/framework/Source/FlutterPlatformNodeDelegateMac.h/0
{ "file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterPlatformNodeDelegateMac.h", "repo_id": "engine", "token_count": 880 }
342
// 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_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERTEXTINPUTSEMANTICSOBJECT_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERTEXTINPUTSEMANTICSOBJECT_H_ #import <Cocoa/Cocoa.h> #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterPlatformNodeDelegateMac.h" #include "flutter/fml/macros.h" #include "flutter/third_party/accessibility/ax/platform/ax_platform_node_base.h" @class FlutterTextField; @class FlutterTextInputPlugin; namespace flutter { //------------------------------------------------------------------------------ /// The ax platform node for a text field. class FlutterTextPlatformNode : public ui::AXPlatformNodeBase { public: //--------------------------------------------------------------------------- /// @brief Creates a FlutterTextPlatformNode that uses a /// FlutterTextField as its NativeViewAccessible. /// @param[in] delegate The delegate that provides accessibility /// data. /// @param[in] view_controller The view_controller that is used for querying /// the information about FlutterView and /// FlutterTextInputPlugin. explicit FlutterTextPlatformNode(FlutterPlatformNodeDelegate* delegate, __weak FlutterViewController* view_controller); ~FlutterTextPlatformNode() override; //------------------------------------------------------------------------------ /// @brief Gets the frame of this platform node relative to the view of /// FlutterViewController. This is used by the FlutterTextField to get its /// frame rect because the FlutterTextField is a subview of the /// FlutterViewController.view. NSRect GetFrame(); // |ui::AXPlatformNodeBase| gfx::NativeViewAccessible GetNativeViewAccessible() override; private: FlutterTextField* appkit_text_field_; __weak FlutterViewController* view_controller_; //------------------------------------------------------------------------------ /// @brief Ensures the FlutterTextField is attached to the FlutterView. This /// method returns true if the text field is succesfully attached. If /// this method returns false, that means the FlutterTextField could not /// be attached to the FlutterView. This can happen when the FlutterEngine /// does not have a FlutterViewController or the FlutterView is not loaded /// yet. bool EnsureAttachedToView(); //------------------------------------------------------------------------------ /// @brief Detaches the FlutterTextField from the FlutterView if it is not /// already detached. void EnsureDetachedFromView(); FML_DISALLOW_COPY_AND_ASSIGN(FlutterTextPlatformNode); }; } // namespace flutter /** * An NSTextField implementation that represents the NativeViewAccessible for the * FlutterTextPlatformNode * * The NSAccessibility protocol does not provide full support for text editing. This * appkit text field is used to get around this problem. The FlutterTextPlatformNode * creates a hidden FlutterTextField, since VoiceOver only provides text editing * announcements for NSTextField subclasses. * * All of the text editing events in this native text field are redirected to the * FlutterTextInputPlugin. */ @interface FlutterTextField : NSTextField /** * Initializes a FlutterTextField that uses the FlutterTextInputPlugin as its field editor. * The text field redirects all of the text editing events to the FlutterTextInputPlugin. */ - (instancetype)initWithPlatformNode:(flutter::FlutterTextPlatformNode*)node fieldEditor:(FlutterTextInputPlugin*)plugin; /** * Updates the string value and the selection of this text field. * * Calling this method is necessary for macOS to get notified about string and selection * changes. */ - (void)updateString:(NSString*)string withSelection:(NSRange)selection; /** * Makes the field editor (plugin) current editor for this TextField, meaning * that the text field will start getting editing events. */ - (void)startEditing; @end #endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERTEXTINPUTSEMANTICSOBJECT_H_
engine/shell/platform/darwin/macos/framework/Source/FlutterTextInputSemanticsObject.h/0
{ "file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterTextInputSemanticsObject.h", "repo_id": "engine", "token_count": 1356 }
343
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterViewController.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h" #include <Carbon/Carbon.h> #import <objc/message.h> #import "flutter/shell/platform/darwin/common/framework/Headers/FlutterChannels.h" #import "flutter/shell/platform/darwin/common/framework/Headers/FlutterCodecs.h" #import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterEngine.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyPrimaryResponder.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardManager.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterRenderer.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputSemanticsObject.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterView.h" #import "flutter/shell/platform/embedder/embedder.h" namespace { using flutter::KeyboardLayoutNotifier; using flutter::LayoutClue; // Use different device ID for mouse and pan/zoom events, since we can't differentiate the actual // device (mouse v.s. trackpad). static constexpr int32_t kMousePointerDeviceId = 0; static constexpr int32_t kPointerPanZoomDeviceId = 1; // A trackpad touch following inertial scrolling should cause an inertia cancel // event to be issued. Use a window of 50 milliseconds after the scroll to account // for delays in event propagation observed in macOS Ventura. static constexpr double kTrackpadTouchInertiaCancelWindowMs = 0.050; /** * State tracking for mouse events, to adapt between the events coming from the system and the * events that the embedding API expects. */ struct MouseState { /** * The currently pressed buttons, as represented in FlutterPointerEvent. */ int64_t buttons = 0; /** * The accumulated gesture pan. */ CGFloat delta_x = 0; CGFloat delta_y = 0; /** * The accumulated gesture zoom scale. */ CGFloat scale = 0; /** * The accumulated gesture rotation. */ CGFloat rotation = 0; /** * Whether or not a kAdd event has been sent (or sent again since the last kRemove if tracking is * enabled). Used to determine whether to send a kAdd event before sending an incoming mouse * event, since Flutter expects pointers to be added before events are sent for them. */ bool flutter_state_is_added = false; /** * Whether or not a kDown has been sent since the last kAdd/kUp. */ bool flutter_state_is_down = false; /** * Whether or not mouseExited: was received while a button was down. Cocoa's behavior when * dragging out of a tracked area is to send an exit, then keep sending drag events until the last * button is released. Flutter doesn't expect to receive events after a kRemove, so the kRemove * for the exit needs to be delayed until after the last mouse button is released. If cursor * returns back to the window while still dragging, the flag is cleared in mouseEntered:. */ bool has_pending_exit = false; /* * Whether or not a kPanZoomStart has been sent since the last kAdd/kPanZoomEnd. */ bool flutter_state_is_pan_zoom_started = false; /** * State of pan gesture. */ NSEventPhase pan_gesture_phase = NSEventPhaseNone; /** * State of scale gesture. */ NSEventPhase scale_gesture_phase = NSEventPhaseNone; /** * State of rotate gesture. */ NSEventPhase rotate_gesture_phase = NSEventPhaseNone; /** * Time of last scroll momentum event. */ NSTimeInterval last_scroll_momentum_changed_time = 0; /** * Resets all gesture state to default values. */ void GestureReset() { delta_x = 0; delta_y = 0; scale = 0; rotation = 0; flutter_state_is_pan_zoom_started = false; pan_gesture_phase = NSEventPhaseNone; scale_gesture_phase = NSEventPhaseNone; rotate_gesture_phase = NSEventPhaseNone; } /** * Resets all state to default values. */ void Reset() { flutter_state_is_added = false; flutter_state_is_down = false; has_pending_exit = false; buttons = 0; GestureReset(); } }; /** * Returns the current Unicode layout data (kTISPropertyUnicodeKeyLayoutData). * * To use the returned data, convert it to CFDataRef first, finds its bytes * with CFDataGetBytePtr, then reinterpret it into const UCKeyboardLayout*. * It's returned in NSData* to enable auto reference count. */ NSData* currentKeyboardLayoutData() { TISInputSourceRef source = TISCopyCurrentKeyboardInputSource(); CFTypeRef layout_data = TISGetInputSourceProperty(source, kTISPropertyUnicodeKeyLayoutData); if (layout_data == nil) { CFRelease(source); // TISGetInputSourceProperty returns null with Japanese keyboard layout. // Using TISCopyCurrentKeyboardLayoutInputSource to fix NULL return. // https://github.com/microsoft/node-native-keymap/blob/5f0699ded00179410a14c0e1b0e089fe4df8e130/src/keyboard_mac.mm#L91 source = TISCopyCurrentKeyboardLayoutInputSource(); layout_data = TISGetInputSourceProperty(source, kTISPropertyUnicodeKeyLayoutData); } return (__bridge_transfer NSData*)CFRetain(layout_data); } } // namespace #pragma mark - Private interface declaration. /** * FlutterViewWrapper is a convenience class that wraps a FlutterView and provides * a mechanism to attach AppKit views such as FlutterTextField without affecting * the accessibility subtree of the wrapped FlutterView itself. * * The FlutterViewController uses this class to create its content view. When * any of the accessibility services (e.g. VoiceOver) is turned on, the accessibility * bridge creates FlutterTextFields that interact with the service. The bridge has to * attach the FlutterTextField somewhere in the view hierarchy in order for the * FlutterTextField to interact correctly with VoiceOver. Those FlutterTextFields * will be attached to this view so that they won't affect the accessibility subtree * of FlutterView. */ @interface FlutterViewWrapper : NSView - (void)setBackgroundColor:(NSColor*)color; @end /** * Private interface declaration for FlutterViewController. */ @interface FlutterViewController () <FlutterViewDelegate> /** * The tracking area used to generate hover events, if enabled. */ @property(nonatomic) NSTrackingArea* trackingArea; /** * The current state of the mouse and the sent mouse events. */ @property(nonatomic) MouseState mouseState; /** * Event monitor for keyUp events. */ @property(nonatomic) id keyUpMonitor; /** * Pointer to a keyboard manager, a hub that manages how key events are * dispatched to various Flutter key responders, and whether the event is * propagated to the next NSResponder. */ @property(nonatomic, readonly, nonnull) FlutterKeyboardManager* keyboardManager; @property(nonatomic) KeyboardLayoutNotifier keyboardLayoutNotifier; @property(nonatomic) NSData* keyboardLayoutData; /** * Starts running |engine|, including any initial setup. */ - (BOOL)launchEngine; /** * Updates |trackingArea| for the current tracking settings, creating it with * the correct mode if tracking is enabled, or removing it if not. */ - (void)configureTrackingArea; /** * Creates and registers keyboard related components. */ - (void)initializeKeyboard; /** * Calls dispatchMouseEvent:phase: with a phase determined by self.mouseState. * * mouseState.buttons should be updated before calling this method. */ - (void)dispatchMouseEvent:(nonnull NSEvent*)event; /** * Calls dispatchMouseEvent:phase: with a phase determined by event.phase. */ - (void)dispatchGestureEvent:(nonnull NSEvent*)event; /** * Converts |event| to a FlutterPointerEvent with the given phase, and sends it to the engine. */ - (void)dispatchMouseEvent:(nonnull NSEvent*)event phase:(FlutterPointerPhase)phase; /** * Called when the active keyboard input source changes. * * Input sources may be simple keyboard layouts, or more complex input methods involving an IME, * such as Chinese, Japanese, and Korean. */ - (void)onKeyboardLayoutChanged; @end #pragma mark - Private dependant functions namespace { void OnKeyboardLayoutChanged(CFNotificationCenterRef center, void* observer, CFStringRef name, const void* object, CFDictionaryRef userInfo) { FlutterViewController* controller = (__bridge FlutterViewController*)observer; if (controller != nil) { [controller onKeyboardLayoutChanged]; } } } // namespace #pragma mark - FlutterViewWrapper implementation. @implementation FlutterViewWrapper { FlutterView* _flutterView; __weak FlutterViewController* _controller; } - (instancetype)initWithFlutterView:(FlutterView*)view controller:(FlutterViewController*)controller { self = [super initWithFrame:NSZeroRect]; if (self) { _flutterView = view; _controller = controller; view.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable; [self addSubview:view]; } return self; } - (void)setBackgroundColor:(NSColor*)color { [_flutterView setBackgroundColor:color]; } - (BOOL)performKeyEquivalent:(NSEvent*)event { // Do not intercept the event if flutterView is not first responder, otherwise this would // interfere with TextInputPlugin, which also handles key equivalents. // // Also do not intercept the event if key equivalent is a product of an event being // redispatched by the TextInputPlugin, in which case it needs to bubble up so that menus // can handle key equivalents. if (self.window.firstResponder != _flutterView || [_controller isDispatchingKeyEvent:event]) { return [super performKeyEquivalent:event]; } [_flutterView keyDown:event]; return YES; } - (NSArray*)accessibilityChildren { return @[ _flutterView ]; } - (void)mouseDown:(NSEvent*)event { // Work around an AppKit bug where mouseDown/mouseUp are not called on the view controller if the // view is the content view of an NSPopover AND macOS's Reduced Transparency accessibility setting // is enabled. // // This simply calls mouseDown on the next responder in the responder chain as the default // implementation on NSResponder is documented to do. // // See: https://github.com/flutter/flutter/issues/115015 // See: http://www.openradar.me/FB12050037 // See: https://developer.apple.com/documentation/appkit/nsresponder/1524634-mousedown [self.nextResponder mouseDown:event]; } - (void)mouseUp:(NSEvent*)event { // Work around an AppKit bug where mouseDown/mouseUp are not called on the view controller if the // view is the content view of an NSPopover AND macOS's Reduced Transparency accessibility setting // is enabled. // // This simply calls mouseUp on the next responder in the responder chain as the default // implementation on NSResponder is documented to do. // // See: https://github.com/flutter/flutter/issues/115015 // See: http://www.openradar.me/FB12050037 // See: https://developer.apple.com/documentation/appkit/nsresponder/1535349-mouseup [self.nextResponder mouseUp:event]; } @end #pragma mark - FlutterViewController implementation. @implementation FlutterViewController { // The project to run in this controller's engine. FlutterDartProject* _project; std::shared_ptr<flutter::AccessibilityBridgeMac> _bridge; FlutterViewId _id; // FlutterViewController does not actually uses the synchronizer, but only // passes it to FlutterView. FlutterThreadSynchronizer* _threadSynchronizer; } @synthesize viewId = _viewId; @dynamic accessibilityBridge; /** * Performs initialization that's common between the different init paths. */ static void CommonInit(FlutterViewController* controller, FlutterEngine* engine) { if (!engine) { engine = [[FlutterEngine alloc] initWithName:@"io.flutter" project:controller->_project allowHeadlessExecution:NO]; } NSCAssert(controller.engine == nil, @"The FlutterViewController is unexpectedly attached to " @"engine %@ before initialization.", controller.engine); [engine addViewController:controller]; NSCAssert(controller.engine != nil, @"The FlutterViewController unexpectedly stays unattached after initialization. " @"In unit tests, this is likely because either the FlutterViewController or " @"the FlutterEngine is mocked. Please subclass these classes instead.", controller.engine, controller.viewId); controller->_mouseTrackingMode = kFlutterMouseTrackingModeInKeyWindow; controller->_textInputPlugin = [[FlutterTextInputPlugin alloc] initWithViewController:controller]; [controller initializeKeyboard]; [controller notifySemanticsEnabledChanged]; // macOS fires this message when changing IMEs. CFNotificationCenterRef cfCenter = CFNotificationCenterGetDistributedCenter(); __weak FlutterViewController* weakSelf = controller; CFNotificationCenterAddObserver(cfCenter, (__bridge void*)weakSelf, OnKeyboardLayoutChanged, kTISNotifySelectedKeyboardInputSourceChanged, NULL, CFNotificationSuspensionBehaviorDeliverImmediately); } - (instancetype)initWithCoder:(NSCoder*)coder { self = [super initWithCoder:coder]; NSAssert(self, @"Super init cannot be nil"); CommonInit(self, nil); return self; } - (instancetype)initWithNibName:(NSString*)nibNameOrNil bundle:(NSBundle*)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; NSAssert(self, @"Super init cannot be nil"); CommonInit(self, nil); return self; } - (instancetype)initWithProject:(nullable FlutterDartProject*)project { self = [super initWithNibName:nil bundle:nil]; NSAssert(self, @"Super init cannot be nil"); _project = project; CommonInit(self, nil); return self; } - (instancetype)initWithEngine:(nonnull FlutterEngine*)engine nibName:(nullable NSString*)nibName bundle:(nullable NSBundle*)nibBundle { NSAssert(engine != nil, @"Engine is required"); self = [super initWithNibName:nibName bundle:nibBundle]; if (self) { CommonInit(self, engine); } return self; } - (BOOL)isDispatchingKeyEvent:(NSEvent*)event { return [_keyboardManager isDispatchingKeyEvent:event]; } - (void)loadView { FlutterView* flutterView; id<MTLDevice> device = _engine.renderer.device; id<MTLCommandQueue> commandQueue = _engine.renderer.commandQueue; if (!device || !commandQueue) { NSLog(@"Unable to create FlutterView; no MTLDevice or MTLCommandQueue available."); return; } flutterView = [self createFlutterViewWithMTLDevice:device commandQueue:commandQueue]; if (_backgroundColor != nil) { [flutterView setBackgroundColor:_backgroundColor]; } FlutterViewWrapper* wrapperView = [[FlutterViewWrapper alloc] initWithFlutterView:flutterView controller:self]; self.view = wrapperView; _flutterView = flutterView; } - (void)viewDidLoad { [self configureTrackingArea]; [self.view setAllowedTouchTypes:NSTouchTypeMaskIndirect]; [self.view setWantsRestingTouches:YES]; [_engine viewControllerViewDidLoad:self]; } - (void)viewWillAppear { [super viewWillAppear]; if (!_engine.running) { [self launchEngine]; } [self listenForMetaModifiedKeyUpEvents]; } - (void)viewWillDisappear { // Per Apple's documentation, it is discouraged to call removeMonitor: in dealloc, and it's // recommended to be called earlier in the lifecycle. [NSEvent removeMonitor:_keyUpMonitor]; _keyUpMonitor = nil; } - (void)dealloc { if ([self attached]) { [_engine removeViewController:self]; } CFNotificationCenterRef cfCenter = CFNotificationCenterGetDistributedCenter(); CFNotificationCenterRemoveEveryObserver(cfCenter, (__bridge void*)self); } #pragma mark - Public methods - (void)setMouseTrackingMode:(FlutterMouseTrackingMode)mode { if (_mouseTrackingMode == mode) { return; } _mouseTrackingMode = mode; [self configureTrackingArea]; } - (void)setBackgroundColor:(NSColor*)color { _backgroundColor = color; [_flutterView setBackgroundColor:_backgroundColor]; } - (FlutterViewId)viewId { NSAssert([self attached], @"This view controller is not attached."); return _viewId; } - (void)onPreEngineRestart { [self initializeKeyboard]; } - (void)notifySemanticsEnabledChanged { BOOL mySemanticsEnabled = !!_bridge; BOOL newSemanticsEnabled = _engine.semanticsEnabled; if (newSemanticsEnabled == mySemanticsEnabled) { return; } if (newSemanticsEnabled) { _bridge = [self createAccessibilityBridgeWithEngine:_engine]; } else { // Remove the accessibility children from flutter view before resetting the bridge. _flutterView.accessibilityChildren = nil; _bridge.reset(); } NSAssert(newSemanticsEnabled == !!_bridge, @"Failed to update semantics for the view."); } - (std::weak_ptr<flutter::AccessibilityBridgeMac>)accessibilityBridge { return _bridge; } - (void)setUpWithEngine:(FlutterEngine*)engine viewId:(FlutterViewId)viewId threadSynchronizer:(FlutterThreadSynchronizer*)threadSynchronizer { NSAssert(_engine == nil, @"Already attached to an engine %@.", _engine); _engine = engine; _viewId = viewId; _threadSynchronizer = threadSynchronizer; [_threadSynchronizer registerView:_viewId]; } - (void)detachFromEngine { NSAssert(_engine != nil, @"Not attached to any engine."); [_threadSynchronizer deregisterView:_viewId]; _threadSynchronizer = nil; _engine = nil; } - (BOOL)attached { return _engine != nil; } - (void)updateSemantics:(const FlutterSemanticsUpdate2*)update { NSAssert(_engine.semanticsEnabled, @"Semantics must be enabled."); if (!_engine.semanticsEnabled) { return; } for (size_t i = 0; i < update->node_count; i++) { const FlutterSemanticsNode2* node = update->nodes[i]; _bridge->AddFlutterSemanticsNodeUpdate(*node); } for (size_t i = 0; i < update->custom_action_count; i++) { const FlutterSemanticsCustomAction2* action = update->custom_actions[i]; _bridge->AddFlutterSemanticsCustomActionUpdate(*action); } _bridge->CommitUpdates(); // Accessibility tree can only be used when the view is loaded. if (!self.viewLoaded) { return; } // Attaches the accessibility root to the flutter view. auto root = _bridge->GetFlutterPlatformNodeDelegateFromID(0).lock(); if (root) { if ([self.flutterView.accessibilityChildren count] == 0) { NSAccessibilityElement* native_root = root->GetNativeViewAccessible(); self.flutterView.accessibilityChildren = @[ native_root ]; } } else { self.flutterView.accessibilityChildren = nil; } } #pragma mark - Private methods - (BOOL)launchEngine { if (![_engine runWithEntrypoint:nil]) { return NO; } return YES; } // macOS does not call keyUp: on a key while the command key is pressed. This results in a loss // of a key event once the modified key is released. This method registers the // ViewController as a listener for a keyUp event before it's handled by NSApplication, and should // NOT modify the event to avoid any unexpected behavior. - (void)listenForMetaModifiedKeyUpEvents { if (_keyUpMonitor != nil) { // It is possible for [NSViewController viewWillAppear] to be invoked multiple times // in a row. https://github.com/flutter/flutter/issues/105963 return; } FlutterViewController* __weak weakSelf = self; _keyUpMonitor = [NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskKeyUp handler:^NSEvent*(NSEvent* event) { // Intercept keyUp only for events triggered on the current // view or textInputPlugin. NSResponder* firstResponder = [[event window] firstResponder]; if (weakSelf.viewLoaded && weakSelf.flutterView && (firstResponder == weakSelf.flutterView || firstResponder == weakSelf.textInputPlugin) && ([event modifierFlags] & NSEventModifierFlagCommand) && ([event type] == NSEventTypeKeyUp)) { [weakSelf keyUp:event]; } return event; }]; } - (void)configureTrackingArea { if (!self.viewLoaded) { // The viewDidLoad will call configureTrackingArea again when // the view is actually loaded. return; } if (_mouseTrackingMode != kFlutterMouseTrackingModeNone && self.flutterView) { NSTrackingAreaOptions options = NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved | NSTrackingInVisibleRect | NSTrackingEnabledDuringMouseDrag; switch (_mouseTrackingMode) { case kFlutterMouseTrackingModeInKeyWindow: options |= NSTrackingActiveInKeyWindow; break; case kFlutterMouseTrackingModeInActiveApp: options |= NSTrackingActiveInActiveApp; break; case kFlutterMouseTrackingModeAlways: options |= NSTrackingActiveAlways; break; default: NSLog(@"Error: Unrecognized mouse tracking mode: %ld", _mouseTrackingMode); return; } _trackingArea = [[NSTrackingArea alloc] initWithRect:NSZeroRect options:options owner:self userInfo:nil]; [self.flutterView addTrackingArea:_trackingArea]; } else if (_trackingArea) { [self.flutterView removeTrackingArea:_trackingArea]; _trackingArea = nil; } } - (void)initializeKeyboard { // TODO(goderbauer): Seperate keyboard/textinput stuff into ViewController specific and Engine // global parts. Move the global parts to FlutterEngine. _keyboardManager = [[FlutterKeyboardManager alloc] initWithViewDelegate:self]; } - (void)dispatchMouseEvent:(nonnull NSEvent*)event { FlutterPointerPhase phase = _mouseState.buttons == 0 ? (_mouseState.flutter_state_is_down ? kUp : kHover) : (_mouseState.flutter_state_is_down ? kMove : kDown); [self dispatchMouseEvent:event phase:phase]; } - (void)dispatchGestureEvent:(nonnull NSEvent*)event { if (event.phase == NSEventPhaseBegan || event.phase == NSEventPhaseMayBegin) { [self dispatchMouseEvent:event phase:kPanZoomStart]; } else if (event.phase == NSEventPhaseChanged) { [self dispatchMouseEvent:event phase:kPanZoomUpdate]; } else if (event.phase == NSEventPhaseEnded || event.phase == NSEventPhaseCancelled) { [self dispatchMouseEvent:event phase:kPanZoomEnd]; } else if (event.phase == NSEventPhaseNone && event.momentumPhase == NSEventPhaseNone) { [self dispatchMouseEvent:event phase:kHover]; } else { // Waiting until the first momentum change event is a workaround for an issue where // touchesBegan: is called unexpectedly while in low power mode within the interval between // momentum start and the first momentum change. if (event.momentumPhase == NSEventPhaseChanged) { _mouseState.last_scroll_momentum_changed_time = event.timestamp; } // Skip momentum update events, the framework will generate scroll momentum. NSAssert(event.momentumPhase != NSEventPhaseNone, @"Received gesture event with unexpected phase"); } } - (void)dispatchMouseEvent:(NSEvent*)event phase:(FlutterPointerPhase)phase { NSAssert(self.viewLoaded, @"View must be loaded before it handles the mouse event"); // There are edge cases where the system will deliver enter out of order relative to other // events (e.g., drag out and back in, release, then click; mouseDown: will be called before // mouseEntered:). Discard those events, since the add will already have been synthesized. if (_mouseState.flutter_state_is_added && phase == kAdd) { return; } // Multiple gesture recognizers could be active at once, we can't send multiple kPanZoomStart. // For example: rotation and magnification. if (phase == kPanZoomStart || phase == kPanZoomEnd) { if (event.type == NSEventTypeScrollWheel) { _mouseState.pan_gesture_phase = event.phase; } else if (event.type == NSEventTypeMagnify) { _mouseState.scale_gesture_phase = event.phase; } else if (event.type == NSEventTypeRotate) { _mouseState.rotate_gesture_phase = event.phase; } } if (phase == kPanZoomStart) { if (event.type == NSEventTypeScrollWheel) { // Ensure scroll inertia cancel event is not sent afterwards. _mouseState.last_scroll_momentum_changed_time = 0; } if (_mouseState.flutter_state_is_pan_zoom_started) { // Already started on a previous gesture type return; } _mouseState.flutter_state_is_pan_zoom_started = true; } if (phase == kPanZoomEnd) { if (!_mouseState.flutter_state_is_pan_zoom_started) { // NSEventPhaseCancelled is sometimes received at incorrect times in the state // machine, just ignore it here if it doesn't make sense // (we have no active gesture to cancel). NSAssert(event.phase == NSEventPhaseCancelled, @"Received gesture event with unexpected phase"); return; } // NSEventPhase values are powers of two, we can use this to inspect merged phases. NSEventPhase all_gestures_fields = _mouseState.pan_gesture_phase | _mouseState.scale_gesture_phase | _mouseState.rotate_gesture_phase; NSEventPhase active_mask = NSEventPhaseBegan | NSEventPhaseChanged; if ((all_gestures_fields & active_mask) != 0) { // Even though this gesture type ended, a different type is still active. return; } } // If a pointer added event hasn't been sent, synthesize one using this event for the basic // information. if (!_mouseState.flutter_state_is_added && phase != kAdd) { // Only the values extracted for use in flutterEvent below matter, the rest are dummy values. NSEvent* addEvent = [NSEvent enterExitEventWithType:NSEventTypeMouseEntered location:event.locationInWindow modifierFlags:0 timestamp:event.timestamp windowNumber:event.windowNumber context:nil eventNumber:0 trackingNumber:0 userData:NULL]; [self dispatchMouseEvent:addEvent phase:kAdd]; } NSPoint locationInView = [self.flutterView convertPoint:event.locationInWindow fromView:nil]; NSPoint locationInBackingCoordinates = [self.flutterView convertPointToBacking:locationInView]; int32_t device = kMousePointerDeviceId; FlutterPointerDeviceKind deviceKind = kFlutterPointerDeviceKindMouse; if (phase == kPanZoomStart || phase == kPanZoomUpdate || phase == kPanZoomEnd) { device = kPointerPanZoomDeviceId; deviceKind = kFlutterPointerDeviceKindTrackpad; } FlutterPointerEvent flutterEvent = { .struct_size = sizeof(flutterEvent), .phase = phase, .timestamp = static_cast<size_t>(event.timestamp * USEC_PER_SEC), .x = locationInBackingCoordinates.x, .y = -locationInBackingCoordinates.y, // convertPointToBacking makes this negative. .device = device, .device_kind = deviceKind, // If a click triggered a synthesized kAdd, don't pass the buttons in that event. .buttons = phase == kAdd ? 0 : _mouseState.buttons, .view_id = static_cast<FlutterViewId>(_viewId), }; if (phase == kPanZoomUpdate) { if (event.type == NSEventTypeScrollWheel) { _mouseState.delta_x += event.scrollingDeltaX * self.flutterView.layer.contentsScale; _mouseState.delta_y += event.scrollingDeltaY * self.flutterView.layer.contentsScale; } else if (event.type == NSEventTypeMagnify) { _mouseState.scale += event.magnification; } else if (event.type == NSEventTypeRotate) { _mouseState.rotation += event.rotation * (-M_PI / 180.0); } flutterEvent.pan_x = _mouseState.delta_x; flutterEvent.pan_y = _mouseState.delta_y; // Scale value needs to be normalized to range 0->infinity. flutterEvent.scale = pow(2.0, _mouseState.scale); flutterEvent.rotation = _mouseState.rotation; } else if (phase == kPanZoomEnd) { _mouseState.GestureReset(); } else if (phase != kPanZoomStart && event.type == NSEventTypeScrollWheel) { flutterEvent.signal_kind = kFlutterPointerSignalKindScroll; double pixelsPerLine = 1.0; if (!event.hasPreciseScrollingDeltas) { // The scrollingDelta needs to be multiplied by the line height. // CGEventSourceGetPixelsPerLine() will return 10, which will result in // scrolling that is noticeably slower than in other applications. // Using 40.0 as the multiplier to match Chromium. // See https://source.chromium.org/chromium/chromium/src/+/main:ui/events/cocoa/events_mac.mm pixelsPerLine = 40.0; } double scaleFactor = self.flutterView.layer.contentsScale; // When mouse input is received while shift is pressed (regardless of // any other pressed keys), Mac automatically flips the axis. Other // platforms do not do this, so we flip it back to normalize the input // received by the framework. The keyboard+mouse-scroll mechanism is exposed // in the ScrollBehavior of the framework so developers can customize the // behavior. // At time of change, Apple does not expose any other type of API or signal // that the X/Y axes have been flipped. double scaledDeltaX = -event.scrollingDeltaX * pixelsPerLine * scaleFactor; double scaledDeltaY = -event.scrollingDeltaY * pixelsPerLine * scaleFactor; if (event.modifierFlags & NSShiftKeyMask) { flutterEvent.scroll_delta_x = scaledDeltaY; flutterEvent.scroll_delta_y = scaledDeltaX; } else { flutterEvent.scroll_delta_x = scaledDeltaX; flutterEvent.scroll_delta_y = scaledDeltaY; } } [_keyboardManager syncModifiersIfNeeded:event.modifierFlags timestamp:event.timestamp]; [_engine sendPointerEvent:flutterEvent]; // Update tracking of state as reported to Flutter. if (phase == kDown) { _mouseState.flutter_state_is_down = true; } else if (phase == kUp) { _mouseState.flutter_state_is_down = false; if (_mouseState.has_pending_exit) { [self dispatchMouseEvent:event phase:kRemove]; _mouseState.has_pending_exit = false; } } else if (phase == kAdd) { _mouseState.flutter_state_is_added = true; } else if (phase == kRemove) { _mouseState.Reset(); } } - (void)onAccessibilityStatusChanged:(BOOL)enabled { if (!enabled && self.viewLoaded && [_textInputPlugin isFirstResponder]) { // Normally TextInputPlugin, when editing, is child of FlutterViewWrapper. // When accessiblity is enabled the TextInputPlugin gets added as an indirect // child to FlutterTextField. When disabling the plugin needs to be reparented // back. [self.view addSubview:_textInputPlugin]; } } - (std::shared_ptr<flutter::AccessibilityBridgeMac>)createAccessibilityBridgeWithEngine: (nonnull FlutterEngine*)engine { return std::make_shared<flutter::AccessibilityBridgeMac>(engine, self); } - (nonnull FlutterView*)createFlutterViewWithMTLDevice:(id<MTLDevice>)device commandQueue:(id<MTLCommandQueue>)commandQueue { return [[FlutterView alloc] initWithMTLDevice:device commandQueue:commandQueue delegate:self threadSynchronizer:_threadSynchronizer viewId:_viewId]; } - (void)onKeyboardLayoutChanged { _keyboardLayoutData = nil; if (_keyboardLayoutNotifier != nil) { _keyboardLayoutNotifier(); } } - (NSString*)lookupKeyForAsset:(NSString*)asset { return [FlutterDartProject lookupKeyForAsset:asset]; } - (NSString*)lookupKeyForAsset:(NSString*)asset fromPackage:(NSString*)package { return [FlutterDartProject lookupKeyForAsset:asset fromPackage:package]; } #pragma mark - FlutterViewDelegate /** * Responds to view reshape by notifying the engine of the change in dimensions. */ - (void)viewDidReshape:(NSView*)view { FML_DCHECK(view == _flutterView); [_engine updateWindowMetricsForViewController:self]; } - (BOOL)viewShouldAcceptFirstResponder:(NSView*)view { FML_DCHECK(view == _flutterView); // Only allow FlutterView to become first responder if TextInputPlugin is // not active. Otherwise a mouse event inside FlutterView would cause the // TextInputPlugin to lose first responder status. return !_textInputPlugin.isFirstResponder; } #pragma mark - FlutterPluginRegistry - (id<FlutterPluginRegistrar>)registrarForPlugin:(NSString*)pluginName { return [_engine registrarForPlugin:pluginName]; } - (NSObject*)valuePublishedByPlugin:(NSString*)pluginKey { return [_engine valuePublishedByPlugin:pluginKey]; } #pragma mark - FlutterKeyboardViewDelegate - (void)sendKeyEvent:(const FlutterKeyEvent&)event callback:(nullable FlutterKeyEventCallback)callback userData:(nullable void*)userData { [_engine sendKeyEvent:event callback:callback userData:userData]; } - (id<FlutterBinaryMessenger>)getBinaryMessenger { return _engine.binaryMessenger; } - (BOOL)onTextInputKeyEvent:(nonnull NSEvent*)event { return [_textInputPlugin handleKeyEvent:event]; } - (void)subscribeToKeyboardLayoutChange:(nullable KeyboardLayoutNotifier)callback { _keyboardLayoutNotifier = callback; } - (LayoutClue)lookUpLayoutForKeyCode:(uint16_t)keyCode shift:(BOOL)shift { if (_keyboardLayoutData == nil) { _keyboardLayoutData = currentKeyboardLayoutData(); } const UCKeyboardLayout* layout = reinterpret_cast<const UCKeyboardLayout*>( CFDataGetBytePtr((__bridge CFDataRef)_keyboardLayoutData)); UInt32 deadKeyState = 0; UniCharCount stringLength = 0; UniChar resultChar; UInt32 modifierState = ((shift ? shiftKey : 0) >> 8) & 0xFF; UInt32 keyboardType = LMGetKbdLast(); bool isDeadKey = false; OSStatus status = UCKeyTranslate(layout, keyCode, kUCKeyActionDown, modifierState, keyboardType, kUCKeyTranslateNoDeadKeysBit, &deadKeyState, 1, &stringLength, &resultChar); // For dead keys, press the same key again to get the printable representation of the key. if (status == noErr && stringLength == 0 && deadKeyState != 0) { isDeadKey = true; status = UCKeyTranslate(layout, keyCode, kUCKeyActionDown, modifierState, keyboardType, kUCKeyTranslateNoDeadKeysBit, &deadKeyState, 1, &stringLength, &resultChar); } if (status == noErr && stringLength == 1 && !std::iscntrl(resultChar)) { return LayoutClue{resultChar, isDeadKey}; } return LayoutClue{0, false}; } - (nonnull NSDictionary*)getPressedState { return [_keyboardManager getPressedState]; } #pragma mark - NSResponder - (BOOL)acceptsFirstResponder { return YES; } - (void)keyDown:(NSEvent*)event { [_keyboardManager handleEvent:event]; } - (void)keyUp:(NSEvent*)event { [_keyboardManager handleEvent:event]; } - (void)flagsChanged:(NSEvent*)event { [_keyboardManager handleEvent:event]; } - (void)mouseEntered:(NSEvent*)event { if (_mouseState.has_pending_exit) { _mouseState.has_pending_exit = false; } else { [self dispatchMouseEvent:event phase:kAdd]; } } - (void)mouseExited:(NSEvent*)event { if (_mouseState.buttons != 0) { _mouseState.has_pending_exit = true; return; } [self dispatchMouseEvent:event phase:kRemove]; } - (void)mouseDown:(NSEvent*)event { _mouseState.buttons |= kFlutterPointerButtonMousePrimary; [self dispatchMouseEvent:event]; } - (void)mouseUp:(NSEvent*)event { _mouseState.buttons &= ~static_cast<uint64_t>(kFlutterPointerButtonMousePrimary); [self dispatchMouseEvent:event]; } - (void)mouseDragged:(NSEvent*)event { [self dispatchMouseEvent:event]; } - (void)rightMouseDown:(NSEvent*)event { _mouseState.buttons |= kFlutterPointerButtonMouseSecondary; [self dispatchMouseEvent:event]; } - (void)rightMouseUp:(NSEvent*)event { _mouseState.buttons &= ~static_cast<uint64_t>(kFlutterPointerButtonMouseSecondary); [self dispatchMouseEvent:event]; } - (void)rightMouseDragged:(NSEvent*)event { [self dispatchMouseEvent:event]; } - (void)otherMouseDown:(NSEvent*)event { _mouseState.buttons |= (1 << event.buttonNumber); [self dispatchMouseEvent:event]; } - (void)otherMouseUp:(NSEvent*)event { _mouseState.buttons &= ~static_cast<uint64_t>(1 << event.buttonNumber); [self dispatchMouseEvent:event]; } - (void)otherMouseDragged:(NSEvent*)event { [self dispatchMouseEvent:event]; } - (void)mouseMoved:(NSEvent*)event { [self dispatchMouseEvent:event]; } - (void)scrollWheel:(NSEvent*)event { [self dispatchGestureEvent:event]; } - (void)magnifyWithEvent:(NSEvent*)event { [self dispatchGestureEvent:event]; } - (void)rotateWithEvent:(NSEvent*)event { [self dispatchGestureEvent:event]; } - (void)swipeWithEvent:(NSEvent*)event { // Not needed, it's handled by scrollWheel. } - (void)touchesBeganWithEvent:(NSEvent*)event { NSTouch* touch = event.allTouches.anyObject; if (touch != nil) { if ((event.timestamp - _mouseState.last_scroll_momentum_changed_time) < kTrackpadTouchInertiaCancelWindowMs) { // The trackpad has been touched following a scroll momentum event. // A scroll inertia cancel message should be sent to the framework. NSPoint locationInView = [self.flutterView convertPoint:event.locationInWindow fromView:nil]; NSPoint locationInBackingCoordinates = [self.flutterView convertPointToBacking:locationInView]; FlutterPointerEvent flutterEvent = { .struct_size = sizeof(flutterEvent), .timestamp = static_cast<size_t>(event.timestamp * USEC_PER_SEC), .x = locationInBackingCoordinates.x, .y = -locationInBackingCoordinates.y, // convertPointToBacking makes this negative. .device = kPointerPanZoomDeviceId, .signal_kind = kFlutterPointerSignalKindScrollInertiaCancel, .device_kind = kFlutterPointerDeviceKindTrackpad, .view_id = static_cast<FlutterViewId>(_viewId), }; [_engine sendPointerEvent:flutterEvent]; // Ensure no further scroll inertia cancel event will be sent. _mouseState.last_scroll_momentum_changed_time = 0; } } } @end
engine/shell/platform/darwin/macos/framework/Source/FlutterViewController.mm/0
{ "file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterViewController.mm", "repo_id": "engine", "token_count": 14158 }
344
// 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 'dart:typed_data'; import 'dart:ui'; @pragma('vm:external-name', 'SignalNativeTest') external void signalNativeTest(); void main() { } /// Notifies the test of a string value. /// /// This is used to notify the native side of the test of a string value from /// the Dart fixture under test. @pragma('vm:external-name', 'NotifyStringValue') external void notifyStringValue(String s); @pragma('vm:entry-point') void executableNameNotNull() { notifyStringValue(Platform.executable); } @pragma('vm:entry-point') void canLogToStdout() { // Emit hello world message to output then signal the test. print('Hello logging'); signalNativeTest(); } @pragma('vm:entry-point') void canCompositePlatformViews() { PlatformDispatcher.instance.onBeginFrame = (Duration duration) { SceneBuilder builder = SceneBuilder(); builder.addPicture(Offset(1.0, 1.0), _createSimplePicture()); builder.pushOffset(1.0, 2.0); builder.addPlatformView(42, width: 123.0, height: 456.0); builder.addPicture(Offset(1.0, 1.0), _createSimplePicture()); builder.pop(); // offset PlatformDispatcher.instance.views.first.render(builder.build()); }; PlatformDispatcher.instance.scheduleFrame(); } /// Returns a [Picture] of a simple black square. Picture _createSimplePicture() { Paint blackPaint = Paint(); PictureRecorder baseRecorder = PictureRecorder(); Canvas canvas = Canvas(baseRecorder); canvas.drawRect(Rect.fromLTRB(0.0, 0.0, 1000.0, 1000.0), blackPaint); return baseRecorder.endRecording(); } @pragma('vm:entry-point') void nativeCallback() { signalNativeTest(); } @pragma('vm:entry-point') void backgroundTest() { PlatformDispatcher.instance.views.first.render(SceneBuilder().build()); signalNativeTest(); // should look black } @pragma('vm:entry-point') void sendFooMessage() { PlatformDispatcher.instance.sendPlatformMessage('foo', null, (ByteData? result) {}); }
engine/shell/platform/darwin/macos/framework/Source/fixtures/flutter_desktop_test.dart/0
{ "file_path": "engine/shell/platform/darwin/macos/framework/Source/fixtures/flutter_desktop_test.dart", "repo_id": "engine", "token_count": 680 }
345
// 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_SHELL_PLATFORM_EMBEDDER_EMBEDDER_EXTERNAL_TEXTURE_RESOLVER_H_ #define FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_EXTERNAL_TEXTURE_RESOLVER_H_ #include <memory> #include "flutter/common/graphics/texture.h" #ifdef SHELL_ENABLE_GL #include "flutter/shell/platform/embedder/embedder_external_texture_gl.h" #endif #ifdef SHELL_ENABLE_METAL #include "flutter/shell/platform/embedder/embedder_external_texture_metal.h" #endif namespace flutter { class EmbedderExternalTextureResolver { public: EmbedderExternalTextureResolver() = default; ~EmbedderExternalTextureResolver() = default; #ifdef SHELL_ENABLE_GL explicit EmbedderExternalTextureResolver( EmbedderExternalTextureGL::ExternalTextureCallback gl_callback); #endif #ifdef SHELL_ENABLE_METAL explicit EmbedderExternalTextureResolver( EmbedderExternalTextureMetal::ExternalTextureCallback metal_callback); #endif std::unique_ptr<Texture> ResolveExternalTexture(int64_t texture_id); bool SupportsExternalTextures(); private: #ifdef SHELL_ENABLE_GL EmbedderExternalTextureGL::ExternalTextureCallback gl_callback_; #endif #ifdef SHELL_ENABLE_METAL EmbedderExternalTextureMetal::ExternalTextureCallback metal_callback_; #endif FML_DISALLOW_COPY_AND_ASSIGN(EmbedderExternalTextureResolver); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_EXTERNAL_TEXTURE_RESOLVER_H_
engine/shell/platform/embedder/embedder_external_texture_resolver.h/0
{ "file_path": "engine/shell/platform/embedder/embedder_external_texture_resolver.h", "repo_id": "engine", "token_count": 531 }
346
// 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_SHELL_PLATFORM_EMBEDDER_EMBEDDER_RENDER_TARGET_IMPELLER_H_ #define FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_RENDER_TARGET_IMPELLER_H_ #include "flutter/shell/platform/embedder/embedder_render_target.h" namespace flutter { class EmbedderRenderTargetImpeller final : public EmbedderRenderTarget { public: EmbedderRenderTargetImpeller( FlutterBackingStore backing_store, std::shared_ptr<impeller::AiksContext> aiks_context, std::unique_ptr<impeller::RenderTarget> impeller_target, fml::closure on_release, fml::closure framebuffer_destruction_callback); // |EmbedderRenderTarget| ~EmbedderRenderTargetImpeller() override; // |EmbedderRenderTarget| sk_sp<SkSurface> GetSkiaSurface() const override; // |EmbedderRenderTarget| impeller::RenderTarget* GetImpellerRenderTarget() const override; // |EmbedderRenderTarget| std::shared_ptr<impeller::AiksContext> GetAiksContext() const override; // |EmbedderRenderTarget| SkISize GetRenderTargetSize() const override; private: std::shared_ptr<impeller::AiksContext> aiks_context_; std::unique_ptr<impeller::RenderTarget> impeller_target_; fml::closure framebuffer_destruction_callback_; FML_DISALLOW_COPY_AND_ASSIGN(EmbedderRenderTargetImpeller); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_RENDER_TARGET_IMPELLER_H_
engine/shell/platform/embedder/embedder_render_target_impeller.h/0
{ "file_path": "engine/shell/platform/embedder/embedder_render_target_impeller.h", "repo_id": "engine", "token_count": 563 }
347
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/embedder/embedder_surface_software.h" #include <utility> #include "flutter/fml/trace_event.h" #include "third_party/skia/include/core/SkColorSpace.h" #include "third_party/skia/include/core/SkImageInfo.h" #include "third_party/skia/include/core/SkSurface.h" #include "third_party/skia/include/gpu/GrDirectContext.h" namespace flutter { EmbedderSurfaceSoftware::EmbedderSurfaceSoftware( SoftwareDispatchTable software_dispatch_table, std::shared_ptr<EmbedderExternalViewEmbedder> external_view_embedder) : software_dispatch_table_(std::move(software_dispatch_table)), external_view_embedder_(std::move(external_view_embedder)) { if (!software_dispatch_table_.software_present_backing_store) { return; } valid_ = true; } EmbedderSurfaceSoftware::~EmbedderSurfaceSoftware() = default; // |EmbedderSurface| bool EmbedderSurfaceSoftware::IsValid() const { return valid_; } // |EmbedderSurface| std::unique_ptr<Surface> EmbedderSurfaceSoftware::CreateGPUSurface() { if (!IsValid()) { return nullptr; } const bool render_to_surface = !external_view_embedder_; auto surface = std::make_unique<GPUSurfaceSoftware>(this, render_to_surface); if (!surface->IsValid()) { return nullptr; } return surface; } // |EmbedderSurface| sk_sp<GrDirectContext> EmbedderSurfaceSoftware::CreateResourceContext() const { return nullptr; } // |GPUSurfaceSoftwareDelegate| sk_sp<SkSurface> EmbedderSurfaceSoftware::AcquireBackingStore( const SkISize& size) { TRACE_EVENT0("flutter", "EmbedderSurfaceSoftware::AcquireBackingStore"); if (!IsValid()) { FML_LOG(ERROR) << "Could not acquire backing store for the software surface."; return nullptr; } if (sk_surface_ != nullptr && SkISize::Make(sk_surface_->width(), sk_surface_->height()) == size) { // The old and new surface sizes are the same. Nothing to do here. return sk_surface_; } SkImageInfo info = SkImageInfo::MakeN32( size.fWidth, size.fHeight, kPremul_SkAlphaType, SkColorSpace::MakeSRGB()); sk_surface_ = SkSurfaces::Raster(info, nullptr); if (sk_surface_ == nullptr) { FML_LOG(ERROR) << "Could not create backing store for software rendering."; return nullptr; } return sk_surface_; } // |GPUSurfaceSoftwareDelegate| bool EmbedderSurfaceSoftware::PresentBackingStore( sk_sp<SkSurface> backing_store) { if (!IsValid()) { FML_LOG(ERROR) << "Tried to present an invalid software surface."; return false; } SkPixmap pixmap; if (!backing_store->peekPixels(&pixmap)) { FML_LOG(ERROR) << "Could not peek the pixels of the backing store."; return false; } // Some basic sanity checking. uint64_t expected_pixmap_data_size = pixmap.width() * pixmap.height() * 4; const size_t pixmap_size = pixmap.computeByteSize(); if (expected_pixmap_data_size != pixmap_size) { FML_LOG(ERROR) << "Software backing store had unexpected size."; return false; } return software_dispatch_table_.software_present_backing_store( pixmap.addr(), // pixmap.rowBytes(), // pixmap.height() // ); } } // namespace flutter
engine/shell/platform/embedder/embedder_surface_software.cc/0
{ "file_path": "engine/shell/platform/embedder/embedder_surface_software.cc", "repo_id": "engine", "token_count": 1199 }
348
// 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_SHELL_PLATFORM_EMBEDDER_PIXEL_FORMATS_H_ #define FLUTTER_SHELL_PLATFORM_EMBEDDER_PIXEL_FORMATS_H_ #include <optional> #include "flutter/shell/common/rasterizer.h" #include "flutter/shell/platform/embedder/embedder.h" std::optional<SkColorType> getSkColorType(FlutterSoftwarePixelFormat pixfmt); std::optional<SkColorInfo> getSkColorInfo(FlutterSoftwarePixelFormat pixfmt); #endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_PIXEL_FORMATS_H_
engine/shell/platform/embedder/pixel_formats.h/0
{ "file_path": "engine/shell/platform/embedder/pixel_formats.h", "repo_id": "engine", "token_count": 224 }
349
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/embedder/tests/embedder_test_backingstore_producer.h" #include "flutter/fml/logging.h" #include "flutter/shell/platform/embedder/pixel_formats.h" #include "third_party/skia/include/core/SkColorSpace.h" #include "third_party/skia/include/core/SkColorType.h" #include "third_party/skia/include/core/SkImageInfo.h" #include "third_party/skia/include/core/SkSize.h" #include "third_party/skia/include/core/SkSurface.h" #include "third_party/skia/include/gpu/GpuTypes.h" #include "third_party/skia/include/gpu/GrBackendSurface.h" #include "third_party/skia/include/gpu/ganesh/SkSurfaceGanesh.h" #include "third_party/skia/include/gpu/ganesh/gl/GrGLBackendSurface.h" #include "third_party/skia/include/gpu/gl/GrGLTypes.h" #include "third_party/skia/include/gpu/vk/GrVkTypes.h" #include <cstdlib> #include <memory> #include <utility> #ifdef SHELL_ENABLE_VULKAN #include "third_party/skia/include/gpu/ganesh/vk/GrVkBackendSurface.h" #endif // SHELL_ENABLE_VULKAN // TODO(zanderso): https://github.com/flutter/flutter/issues/127701 // NOLINTBEGIN(bugprone-unchecked-optional-access) namespace flutter { namespace testing { EmbedderTestBackingStoreProducer::EmbedderTestBackingStoreProducer( sk_sp<GrDirectContext> context, RenderTargetType type, FlutterSoftwarePixelFormat software_pixfmt) : context_(std::move(context)), type_(type), software_pixfmt_(software_pixfmt) #ifdef SHELL_ENABLE_METAL , test_metal_context_(std::make_unique<TestMetalContext>()) #endif #ifdef SHELL_ENABLE_VULKAN , test_vulkan_context_(nullptr) #endif { if (type == RenderTargetType::kSoftwareBuffer && software_pixfmt_ != kFlutterSoftwarePixelFormatNative32) { FML_LOG(ERROR) << "Expected pixel format to be the default " "(kFlutterSoftwarePixelFormatNative32) when" "backing store producer should produce deprecated v1 " "software backing " "stores."; std::abort(); }; } EmbedderTestBackingStoreProducer::~EmbedderTestBackingStoreProducer() = default; bool EmbedderTestBackingStoreProducer::Create( const FlutterBackingStoreConfig* config, FlutterBackingStore* renderer_out) { switch (type_) { case RenderTargetType::kSoftwareBuffer: return CreateSoftware(config, renderer_out); case RenderTargetType::kSoftwareBuffer2: return CreateSoftware2(config, renderer_out); #ifdef SHELL_ENABLE_GL case RenderTargetType::kOpenGLTexture: return CreateTexture(config, renderer_out); case RenderTargetType::kOpenGLFramebuffer: return CreateFramebuffer(config, renderer_out); #endif #ifdef SHELL_ENABLE_METAL case RenderTargetType::kMetalTexture: return CreateMTLTexture(config, renderer_out); #endif #ifdef SHELL_ENABLE_VULKAN case RenderTargetType::kVulkanImage: return CreateVulkanImage(config, renderer_out); #endif default: return false; } } bool EmbedderTestBackingStoreProducer::CreateFramebuffer( const FlutterBackingStoreConfig* config, FlutterBackingStore* backing_store_out) { #ifdef SHELL_ENABLE_GL const auto image_info = SkImageInfo::MakeN32Premul(config->size.width, config->size.height); auto surface = SkSurfaces::RenderTarget(context_.get(), // context skgpu::Budgeted::kNo, // budgeted image_info, // image info 1, // sample count kBottomLeft_GrSurfaceOrigin, // surface origin nullptr, // surface properties false // mipmaps ); if (!surface) { FML_LOG(ERROR) << "Could not create render target for compositor layer."; return false; } GrBackendRenderTarget render_target = SkSurfaces::GetBackendRenderTarget( surface.get(), SkSurfaces::BackendHandleAccess::kDiscardWrite); if (!render_target.isValid()) { FML_LOG(ERROR) << "Backend render target was invalid."; return false; } GrGLFramebufferInfo framebuffer_info = {}; if (!GrBackendRenderTargets::GetGLFramebufferInfo(render_target, &framebuffer_info)) { FML_LOG(ERROR) << "Could not access backend framebuffer info."; return false; } backing_store_out->type = kFlutterBackingStoreTypeOpenGL; backing_store_out->user_data = surface.get(); backing_store_out->open_gl.type = kFlutterOpenGLTargetTypeFramebuffer; backing_store_out->open_gl.framebuffer.target = framebuffer_info.fFormat; backing_store_out->open_gl.framebuffer.name = framebuffer_info.fFBOID; // The balancing unref is in the destruction callback. surface->ref(); backing_store_out->open_gl.framebuffer.user_data = surface.get(); backing_store_out->open_gl.framebuffer.destruction_callback = [](void* user_data) { reinterpret_cast<SkSurface*>(user_data)->unref(); }; return true; #else return false; #endif } bool EmbedderTestBackingStoreProducer::CreateTexture( const FlutterBackingStoreConfig* config, FlutterBackingStore* backing_store_out) { #ifdef SHELL_ENABLE_GL const auto image_info = SkImageInfo::MakeN32Premul(config->size.width, config->size.height); auto surface = SkSurfaces::RenderTarget(context_.get(), // context skgpu::Budgeted::kNo, // budgeted image_info, // image info 1, // sample count kBottomLeft_GrSurfaceOrigin, // surface origin nullptr, // surface properties false // mipmaps ); if (!surface) { FML_LOG(ERROR) << "Could not create render target for compositor layer."; return false; } GrBackendTexture render_texture = SkSurfaces::GetBackendTexture( surface.get(), SkSurfaces::BackendHandleAccess::kDiscardWrite); if (!render_texture.isValid()) { FML_LOG(ERROR) << "Backend render texture was invalid."; return false; } GrGLTextureInfo texture_info = {}; if (!GrBackendTextures::GetGLTextureInfo(render_texture, &texture_info)) { FML_LOG(ERROR) << "Could not access backend texture info."; return false; } backing_store_out->type = kFlutterBackingStoreTypeOpenGL; backing_store_out->user_data = surface.get(); backing_store_out->open_gl.type = kFlutterOpenGLTargetTypeTexture; backing_store_out->open_gl.texture.target = texture_info.fTarget; backing_store_out->open_gl.texture.name = texture_info.fID; backing_store_out->open_gl.texture.format = texture_info.fFormat; // The balancing unref is in the destruction callback. surface->ref(); backing_store_out->open_gl.texture.user_data = surface.get(); backing_store_out->open_gl.texture.destruction_callback = [](void* user_data) { reinterpret_cast<SkSurface*>(user_data)->unref(); }; return true; #else return false; #endif } bool EmbedderTestBackingStoreProducer::CreateSoftware( const FlutterBackingStoreConfig* config, FlutterBackingStore* backing_store_out) { auto surface = SkSurfaces::Raster( SkImageInfo::MakeN32Premul(config->size.width, config->size.height)); if (!surface) { FML_LOG(ERROR) << "Could not create the render target for compositor layer."; return false; } SkPixmap pixmap; if (!surface->peekPixels(&pixmap)) { FML_LOG(ERROR) << "Could not peek pixels of pixmap."; return false; } backing_store_out->type = kFlutterBackingStoreTypeSoftware; backing_store_out->user_data = surface.get(); backing_store_out->software.allocation = pixmap.addr(); backing_store_out->software.row_bytes = pixmap.rowBytes(); backing_store_out->software.height = pixmap.height(); // The balancing unref is in the destruction callback. surface->ref(); backing_store_out->software.user_data = surface.get(); backing_store_out->software.destruction_callback = [](void* user_data) { reinterpret_cast<SkSurface*>(user_data)->unref(); }; return true; } bool EmbedderTestBackingStoreProducer::CreateSoftware2( const FlutterBackingStoreConfig* config, FlutterBackingStore* backing_store_out) { const auto color_info = getSkColorInfo(software_pixfmt_); if (!color_info) { return false; } auto surface = SkSurfaces::Raster(SkImageInfo::Make( SkISize::Make(config->size.width, config->size.height), *color_info)); if (!surface) { FML_LOG(ERROR) << "Could not create the render target for compositor layer."; return false; } SkPixmap pixmap; if (!surface->peekPixels(&pixmap)) { FML_LOG(ERROR) << "Could not peek pixels of pixmap."; return false; } backing_store_out->type = kFlutterBackingStoreTypeSoftware2; backing_store_out->user_data = surface.get(); backing_store_out->software2.struct_size = sizeof(FlutterSoftwareBackingStore2); backing_store_out->software2.user_data = surface.get(); backing_store_out->software2.allocation = pixmap.writable_addr(); backing_store_out->software2.row_bytes = pixmap.rowBytes(); backing_store_out->software2.height = pixmap.height(); // The balancing unref is in the destruction callback. surface->ref(); backing_store_out->software2.user_data = surface.get(); backing_store_out->software2.destruction_callback = [](void* user_data) { reinterpret_cast<SkSurface*>(user_data)->unref(); }; backing_store_out->software2.pixel_format = software_pixfmt_; return true; } bool EmbedderTestBackingStoreProducer::CreateMTLTexture( const FlutterBackingStoreConfig* config, FlutterBackingStore* backing_store_out) { #ifdef SHELL_ENABLE_METAL // TODO(gw280): Use SkSurfaces::RenderTarget instead of generating our // own MTLTexture and wrapping it. auto surface_size = SkISize::Make(config->size.width, config->size.height); auto texture_info = test_metal_context_->CreateMetalTexture(surface_size); GrMtlTextureInfo skia_texture_info; skia_texture_info.fTexture.reset(SkCFSafeRetain(texture_info.texture)); GrBackendTexture backend_texture(surface_size.width(), surface_size.height(), skgpu::Mipmapped::kNo, skia_texture_info); sk_sp<SkSurface> surface = SkSurfaces::WrapBackendTexture( context_.get(), backend_texture, kTopLeft_GrSurfaceOrigin, 1, kBGRA_8888_SkColorType, nullptr, nullptr); if (!surface) { FML_LOG(ERROR) << "Could not create Skia surface from a Metal texture."; return false; } backing_store_out->type = kFlutterBackingStoreTypeMetal; backing_store_out->user_data = surface.get(); backing_store_out->metal.texture.texture = texture_info.texture; // The balancing unref is in the destruction callback. surface->ref(); backing_store_out->metal.struct_size = sizeof(FlutterMetalBackingStore); backing_store_out->metal.texture.user_data = surface.get(); backing_store_out->metal.texture.destruction_callback = [](void* user_data) { reinterpret_cast<SkSurface*>(user_data)->unref(); }; return true; #else return false; #endif } bool EmbedderTestBackingStoreProducer::CreateVulkanImage( const FlutterBackingStoreConfig* config, FlutterBackingStore* backing_store_out) { #ifdef SHELL_ENABLE_VULKAN if (!test_vulkan_context_) { test_vulkan_context_ = fml::MakeRefCounted<TestVulkanContext>(); } auto surface_size = SkISize::Make(config->size.width, config->size.height); TestVulkanImage* test_image = new TestVulkanImage( std::move(test_vulkan_context_->CreateImage(surface_size).value())); GrVkImageInfo image_info = { .fImage = test_image->GetImage(), .fImageTiling = VK_IMAGE_TILING_OPTIMAL, .fImageLayout = VK_IMAGE_LAYOUT_UNDEFINED, .fFormat = VK_FORMAT_R8G8B8A8_UNORM, .fImageUsageFlags = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, .fSampleCount = 1, .fLevelCount = 1, }; auto backend_texture = GrBackendTextures::MakeVk( surface_size.width(), surface_size.height(), image_info); SkSurfaceProps surface_properties(0, kUnknown_SkPixelGeometry); SkSurfaces::TextureReleaseProc release_vktexture = [](void* user_data) { delete reinterpret_cast<TestVulkanImage*>(user_data); }; sk_sp<SkSurface> surface = SkSurfaces::WrapBackendTexture( context_.get(), // context backend_texture, // back-end texture kTopLeft_GrSurfaceOrigin, // surface origin 1, // sample count kRGBA_8888_SkColorType, // color type SkColorSpace::MakeSRGB(), // color space &surface_properties, // surface properties release_vktexture, // texture release proc test_image // release context ); if (!surface) { FML_LOG(ERROR) << "Could not create Skia surface from Vulkan image."; return false; } backing_store_out->type = kFlutterBackingStoreTypeVulkan; FlutterVulkanImage* image = new FlutterVulkanImage(); image->image = reinterpret_cast<uint64_t>(image_info.fImage); image->format = VK_FORMAT_R8G8B8A8_UNORM; backing_store_out->vulkan.image = image; // Collect all allocated resources in the destruction_callback. { UserData* user_data = new UserData(); user_data->image = image; user_data->surface = surface.get(); backing_store_out->user_data = user_data; backing_store_out->vulkan.user_data = user_data; backing_store_out->vulkan.destruction_callback = [](void* user_data) { UserData* d = reinterpret_cast<UserData*>(user_data); d->surface->unref(); delete d->image; delete d; }; // The balancing unref is in the destruction callback. surface->ref(); } return true; #else return false; #endif } } // namespace testing } // namespace flutter // NOLINTEND(bugprone-unchecked-optional-access)
engine/shell/platform/embedder/tests/embedder_test_backingstore_producer.cc/0
{ "file_path": "engine/shell/platform/embedder/tests/embedder_test_backingstore_producer.cc", "repo_id": "engine", "token_count": 5650 }
350
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/embedder/tests/embedder_test_context_metal.h" #include <memory> #include <utility> #include "embedder.h" #include "flutter/fml/logging.h" #include "flutter/shell/platform/embedder/tests/embedder_test_compositor_metal.h" namespace flutter { namespace testing { EmbedderTestContextMetal::EmbedderTestContextMetal(std::string assets_path) : EmbedderTestContext(std::move(assets_path)) { metal_context_ = std::make_unique<TestMetalContext>(); } EmbedderTestContextMetal::~EmbedderTestContextMetal() {} void EmbedderTestContextMetal::SetupSurface(SkISize surface_size) { FML_CHECK(surface_size_.isEmpty()); surface_size_ = surface_size; metal_surface_ = TestMetalSurface::Create(*metal_context_, surface_size_); } size_t EmbedderTestContextMetal::GetSurfacePresentCount() const { return present_count_; } EmbedderTestContextType EmbedderTestContextMetal::GetContextType() const { return EmbedderTestContextType::kMetalContext; } void EmbedderTestContextMetal::SetupCompositor() { FML_CHECK(!compositor_) << "Already set up a compositor in this context."; FML_CHECK(metal_surface_) << "Set up the Metal surface before setting up a compositor."; compositor_ = std::make_unique<EmbedderTestCompositorMetal>( surface_size_, metal_surface_->GetGrContext()); } TestMetalContext* EmbedderTestContextMetal::GetTestMetalContext() { return metal_context_.get(); } TestMetalSurface* EmbedderTestContextMetal::GetTestMetalSurface() { return metal_surface_.get(); } void EmbedderTestContextMetal::SetPresentCallback( PresentCallback present_callback) { present_callback_ = std::move(present_callback); } bool EmbedderTestContextMetal::Present(int64_t texture_id) { FireRootSurfacePresentCallbackIfPresent( [&]() { return metal_surface_->GetRasterSurfaceSnapshot(); }); present_count_++; if (present_callback_ != nullptr) { return present_callback_(texture_id); } return metal_context_->Present(texture_id); } void EmbedderTestContextMetal::SetExternalTextureCallback( TestExternalTextureCallback external_texture_frame_callback) { external_texture_frame_callback_ = std::move(external_texture_frame_callback); } bool EmbedderTestContextMetal::PopulateExternalTexture( int64_t texture_id, size_t w, size_t h, FlutterMetalExternalTexture* output) { if (external_texture_frame_callback_ != nullptr) { return external_texture_frame_callback_(texture_id, w, h, output); } else { return false; } } void EmbedderTestContextMetal::SetNextDrawableCallback( NextDrawableCallback next_drawable_callback) { next_drawable_callback_ = std::move(next_drawable_callback); } FlutterMetalTexture EmbedderTestContextMetal::GetNextDrawable( const FlutterFrameInfo* frame_info) { if (next_drawable_callback_ != nullptr) { return next_drawable_callback_(frame_info); } auto texture_info = metal_surface_->GetTextureInfo(); FlutterMetalTexture texture = {}; texture.struct_size = sizeof(FlutterMetalTexture); texture.texture_id = texture_info.texture_id; texture.texture = reinterpret_cast<FlutterMetalTextureHandle>(texture_info.texture); return texture; } } // namespace testing } // namespace flutter
engine/shell/platform/embedder/tests/embedder_test_context_metal.cc/0
{ "file_path": "engine/shell/platform/embedder/tests/embedder_test_context_metal.cc", "repo_id": "engine", "token_count": 1099 }
351
# 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. name: zircon environment: sdk: '>=3.2.0-0 <4.0.0' # Uncomment block for local testing # dependencies: # zircon_ffi: # path: ../zircon_ffi # dev_dependencies: # test: ^1.17.10 # block end
engine/shell/platform/fuchsia/dart-pkg/zircon/pubspec.yaml/0
{ "file_path": "engine/shell/platform/fuchsia/dart-pkg/zircon/pubspec.yaml", "repo_id": "engine", "token_count": 140 }
352
// 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 "channel.h" #include "flutter/fml/logging.h" #include "flutter/fml/macros.h" #include <cstdlib> #include <vector> #include <lib/zx/channel.h> #include <zircon/types.h> static zircon_dart_handle_t* MakeHandle(zx_handle_t handle) { zircon_dart_handle_t* result = static_cast<zircon_dart_handle_t*>(malloc(sizeof(zircon_dart_handle_t))); result->handle = handle; return result; } zircon_dart_handle_pair_t* zircon_dart_channel_create(uint32_t options) { zx_handle_t out0 = 0, out1 = 0; zx_status_t status = zx_channel_create(options, &out0, &out1); if (status != ZX_OK) { return nullptr; } else { zircon_dart_handle_pair_t* result = static_cast<zircon_dart_handle_pair_t*>( malloc(sizeof(zircon_dart_handle_pair_t))); result->left = MakeHandle(out0); result->right = MakeHandle(out1); return result; } } int32_t zircon_dart_channel_write(zircon_dart_handle_t* handle, zircon_dart_byte_array_t* bytes, zircon_dart_handle_list_t* handles) { if (!handle || (handle->handle == ZX_HANDLE_INVALID)) { return ZX_ERR_BAD_HANDLE; } std::vector<zx_handle_t> zx_handles; std::vector<zircon_dart_handle_t*> handle_data = *reinterpret_cast<std::vector<zircon_dart_handle_t*>*>(handles->data); for (auto handle_ptr : handle_data) { zx_handles.push_back(handle_ptr->handle); } zx_status_t status = zx_channel_write(handle->handle, 0, bytes->data, bytes->length, zx_handles.data(), zx_handles.size()); // Handles are always consumed. for (auto handle_ptr : handle_data) { handle_ptr->handle = ZX_HANDLE_INVALID; } return status; }
engine/shell/platform/fuchsia/dart-pkg/zircon_ffi/channel.cc/0
{ "file_path": "engine/shell/platform/fuchsia/dart-pkg/zircon_ffi/channel.cc", "repo_id": "engine", "token_count": 837 }
353
// 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 "builtin_libraries.h" #include <lib/fdio/namespace.h> #include <lib/zx/channel.h> #include <optional> #include "dart-pkg/fuchsia/sdk_ext/fuchsia.h" #include "flutter/fml/logging.h" #include "runtime/dart/utils/inlines.h" #include "third_party/dart/runtime/bin/io_natives.h" #include "third_party/dart/runtime/include/dart_api.h" #include "third_party/tonic/converter/dart_converter.h" #include "third_party/tonic/dart_microtask_queue.h" #include "third_party/tonic/logging/dart_error.h" #include "logging.h" using tonic::ToDart; namespace dart_runner { namespace { #define REGISTER_FUNCTION(name, count) {#name, name, count}, #define DECLARE_FUNCTION(name, count) \ extern void name(Dart_NativeArguments args); #define BUILTIN_NATIVE_LIST(V) \ V(Logger_PrintString, 1) \ V(ScheduleMicrotask, 1) BUILTIN_NATIVE_LIST(DECLARE_FUNCTION); const struct NativeEntry { const char* name; Dart_NativeFunction function; int argument_count; } kBuiltinEntries[] = {BUILTIN_NATIVE_LIST(REGISTER_FUNCTION)}; Dart_NativeFunction BuiltinNativeLookup(Dart_Handle name, int argument_count, bool* auto_setup_scope) { const char* function_name = nullptr; Dart_Handle result = Dart_StringToCString(name, &function_name); if (Dart_IsError(result)) { Dart_PropagateError(result); } FML_DCHECK(function_name != nullptr); FML_DCHECK(auto_setup_scope != nullptr); *auto_setup_scope = true; size_t num_entries = dart_utils::ArraySize(kBuiltinEntries); for (size_t i = 0; i < num_entries; i++) { const NativeEntry& entry = kBuiltinEntries[i]; if (!strcmp(function_name, entry.name) && (entry.argument_count == argument_count)) { return entry.function; } } return nullptr; } const uint8_t* BuiltinNativeSymbol(Dart_NativeFunction native_function) { size_t num_entries = dart_utils::ArraySize(kBuiltinEntries); for (size_t i = 0; i < num_entries; i++) { const NativeEntry& entry = kBuiltinEntries[i]; if (entry.function == native_function) return reinterpret_cast<const uint8_t*>(entry.name); } return nullptr; } void Logger_PrintString(Dart_NativeArguments args) { intptr_t length = 0; uint8_t* chars = nullptr; Dart_Handle str = Dart_GetNativeArgument(args, 0); Dart_Handle result = Dart_StringToUTF8(str, &chars, &length); if (Dart_IsError(result)) { Dart_PropagateError(result); } else { fwrite(chars, 1, length, stdout); fputc('\n', stdout); fflush(stdout); } } void ScheduleMicrotask(Dart_NativeArguments args) { Dart_Handle closure = Dart_GetNativeArgument(args, 0); if (tonic::CheckAndHandleError(closure) || !Dart_IsClosure(closure)) return; tonic::DartMicrotaskQueue::GetForCurrentThread()->ScheduleMicrotask(closure); } } // namespace void InitBuiltinLibrariesForIsolate(const std::string& script_uri, fdio_ns_t* namespc, int stdoutfd, int stderrfd, zx::channel directory_request, bool service_isolate) { // dart:fuchsia -------------------------------------------------------------- // dart runner doesn't care about scenic view ref. if (!service_isolate) { fuchsia::dart::Initialize(std::move(directory_request), std::nullopt); } // dart:fuchsia.builtin ------------------------------------------------------ Dart_Handle builtin_lib = Dart_LookupLibrary(ToDart("dart:fuchsia.builtin")); FML_CHECK(!tonic::CheckAndHandleError(builtin_lib)); Dart_Handle result = Dart_SetNativeResolver(builtin_lib, BuiltinNativeLookup, BuiltinNativeSymbol); FML_CHECK(!tonic::CheckAndHandleError(result)); // dart:io ------------------------------------------------------------------- Dart_Handle io_lib = Dart_LookupLibrary(ToDart("dart:io")); FML_CHECK(!tonic::CheckAndHandleError(io_lib)); result = Dart_SetNativeResolver(io_lib, dart::bin::IONativeLookup, dart::bin::IONativeSymbol); FML_CHECK(!tonic::CheckAndHandleError(result)); // dart:zircon --------------------------------------------------------------- Dart_Handle zircon_lib = Dart_LookupLibrary(ToDart("dart:zircon")); FML_CHECK(!tonic::CheckAndHandleError(zircon_lib)); // NativeResolver already set by fuchsia::dart::Initialize(). // Core libraries ------------------------------------------------------------ Dart_Handle async_lib = Dart_LookupLibrary(ToDart("dart:async")); FML_CHECK(!tonic::CheckAndHandleError(async_lib)); Dart_Handle core_lib = Dart_LookupLibrary(ToDart("dart:core")); FML_CHECK(!tonic::CheckAndHandleError(core_lib)); Dart_Handle internal_lib = Dart_LookupLibrary(ToDart("dart:_internal")); FML_CHECK(!tonic::CheckAndHandleError(internal_lib)); Dart_Handle isolate_lib = Dart_LookupLibrary(ToDart("dart:isolate")); FML_CHECK(!tonic::CheckAndHandleError(isolate_lib)); #if !defined(AOT_RUNTIME) // AOT: These steps already happened at compile time in gen_snapshot. // We need to ensure that all the scripts loaded so far are finalized // as we are about to invoke some Dart code below to set up closures. result = Dart_FinalizeLoading(false); FML_CHECK(!tonic::CheckAndHandleError(result)); #endif // Setup the internal library's 'internalPrint' function. Dart_Handle print = Dart_Invoke(builtin_lib, ToDart("_getPrintClosure"), 0, nullptr); FML_CHECK(!tonic::CheckAndHandleError(print)); result = Dart_SetField(internal_lib, ToDart("_printClosure"), print); FML_CHECK(!tonic::CheckAndHandleError(result)); // Set up the 'scheduleImmediate' closure. Dart_Handle schedule_immediate_closure; if (service_isolate) { // Running on dart::ThreadPool. schedule_immediate_closure = Dart_Invoke( isolate_lib, ToDart("_getIsolateScheduleImmediateClosure"), 0, nullptr); } else { // Running on async::Loop. schedule_immediate_closure = Dart_Invoke( builtin_lib, ToDart("_getScheduleMicrotaskClosure"), 0, nullptr); } FML_CHECK(!tonic::CheckAndHandleError(schedule_immediate_closure)); Dart_Handle schedule_args[1]; schedule_args[0] = schedule_immediate_closure; result = Dart_Invoke(async_lib, ToDart("_setScheduleImmediateClosure"), 1, schedule_args); FML_CHECK(!tonic::CheckAndHandleError(result)); // Set up the namespace in dart:io. Dart_Handle namespace_type = Dart_GetNonNullableType(io_lib, ToDart("_Namespace"), 0, nullptr); FML_CHECK(!tonic::CheckAndHandleError(namespace_type)); Dart_Handle namespace_args[1]; namespace_args[0] = ToDart(reinterpret_cast<intptr_t>(namespc)); result = Dart_Invoke(namespace_type, ToDart("_setupNamespace"), 1, namespace_args); FML_CHECK(!tonic::CheckAndHandleError(result)); // Set up the namespace in dart:zircon. namespace_type = Dart_GetNonNullableType(zircon_lib, ToDart("_Namespace"), 0, nullptr); FML_CHECK(!tonic::CheckAndHandleError(namespace_type)); result = Dart_SetField(namespace_type, ToDart("_namespace"), ToDart(reinterpret_cast<intptr_t>(namespc))); FML_CHECK(!tonic::CheckAndHandleError(result)); // Set up stdout and stderr. Dart_Handle stdio_args[3]; stdio_args[0] = Dart_NewInteger(0); stdio_args[1] = Dart_NewInteger(stdoutfd); stdio_args[2] = Dart_NewInteger(stderrfd); result = Dart_Invoke(io_lib, ToDart("_setStdioFDs"), 3, stdio_args); FML_CHECK(!tonic::CheckAndHandleError(result)); // Disable some dart:io operations. Dart_Handle embedder_config_type = Dart_GetNonNullableType(io_lib, ToDart("_EmbedderConfig"), 0, nullptr); FML_CHECK(!tonic::CheckAndHandleError(embedder_config_type)); result = Dart_SetField(embedder_config_type, ToDart("_mayExit"), Dart_False()); FML_CHECK(!tonic::CheckAndHandleError(result)); // Set the script location. result = Dart_SetField(builtin_lib, ToDart("_rawScript"), ToDart(script_uri)); FML_CHECK(!tonic::CheckAndHandleError(result)); // Setup the uriBase with the base uri of the fidl app. Dart_Handle uri_base = Dart_Invoke(io_lib, ToDart("_getUriBaseClosure"), 0, nullptr); FML_CHECK(!tonic::CheckAndHandleError(uri_base)); result = Dart_SetField(core_lib, ToDart("_uriBaseClosure"), uri_base); FML_CHECK(!tonic::CheckAndHandleError(result)); Dart_Handle setup_hooks = ToDart("_setupHooks"); result = Dart_Invoke(builtin_lib, setup_hooks, 0, nullptr); FML_CHECK(!tonic::CheckAndHandleError(result)); result = Dart_Invoke(io_lib, setup_hooks, 0, nullptr); FML_CHECK(!tonic::CheckAndHandleError(result)); result = Dart_Invoke(isolate_lib, setup_hooks, 0, nullptr); FML_CHECK(!tonic::CheckAndHandleError(result)); } } // namespace dart_runner
engine/shell/platform/fuchsia/dart_runner/builtin_libraries.cc/0
{ "file_path": "engine/shell/platform/fuchsia/dart_runner/builtin_libraries.cc", "repo_id": "engine", "token_count": 3448 }
354
// 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. library dart.test; const MAX_STRING_LENGTH uint64 = 32; @discoverable closed protocol Echo { /// Returns the input. strict EchoString(struct { value string:<MAX_STRING_LENGTH, optional>; }) -> (struct { response string:<MAX_STRING_LENGTH, optional>; }); };
engine/shell/platform/fuchsia/dart_runner/fidl/echo.fidl/0
{ "file_path": "engine/shell/platform/fuchsia/dart_runner/fidl/echo.fidl", "repo_id": "engine", "token_count": 155 }
355
# dart_aot_runner Contains the integration test for the Dart AOT runner. ### Running Tests <!-- TODO(erkln): Replace steps once test runner script is updated to run Dart runner tests --> #### Setup emulator and PM serve ``` fx set terminal.qemu-x64 ffx emu start --headless fx serve ``` #### Prepare build files and build binary ``` $ENGINE_DIR/flutter/tools/gn --fuchsia --no-lto --runtime-mode=profile ninja -C $ENGINE_DIR/out/fuchsia_profile_x64 flutter/shell/platform/fuchsia fuchsia_tests ``` #### Publish files to PM ``` $FUCHSIA_DIR/.jiri_root/bin/ffx repository publish $FUCHSIA_DIR/$(cat $FUCHSIA_DIR/.fx-build-dir)/amber-files --package-archive $ENGINE_DIR/out/fuchsia_profile_x64/dart-aot-runner-integration-test-0.far $FUCHSIA_DIR/.jiri_root/bin/ffx repository publish $FUCHSIA_DIR/$(cat $FUCHSIA_DIR/.fx-build-dir)/amber-files --package-archive $ENGINE_DIR/out/fuchsia_profile_x64/oot_dart_aot_runner-0.far $FUCHSIA_DIR/.jiri_root/bin/ffx repository publish $FUCHSIA_DIR/$(cat $FUCHSIA_DIR/.fx-build-dir)/amber-files --package-archive $ENGINE_DIR/out/fuchsia_profile_x64/gen/flutter/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_echo_server/dart_aot_echo_server/dart_aot_echo_server.far ``` #### Run test ``` ffx test run "fuchsia-pkg://fuchsia.com/dart-aot-runner-integration-test#meta/dart-aot-runner-integration-test.cm" ``` ## Notes The `profile` runtime should be used when running the `dart_aot_runner` integration test. Snapshots will fail to generate or generate incorrectly if the wrong runtime is used.
engine/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_aot_runner/README.md/0
{ "file_path": "engine/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_aot_runner/README.md", "repo_id": "engine", "token_count": 574 }
356
// 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 "external_view_embedder.h" #include <algorithm> #include <cstdint> #include "flutter/fml/trace_event.h" #include "third_party/skia/include/core/SkPicture.h" #include "third_party/skia/include/core/SkSurface.h" #include "third_party/skia/include/gpu/GrDirectContext.h" #include "third_party/skia/include/gpu/GrRecordingContext.h" namespace flutter_runner { namespace { void AttachClipTransformChild( FlatlandConnection* flatland, ExternalViewEmbedder::ClipTransform* parent_clip_transform, const fuchsia::ui::composition::TransformId& child_transform_id) { flatland->flatland()->AddChild(parent_clip_transform->transform_id, child_transform_id); parent_clip_transform->children.push_back(child_transform_id); } void DetachClipTransformChildren( FlatlandConnection* flatland, ExternalViewEmbedder::ClipTransform* clip_transform) { for (auto& child : clip_transform->children) { flatland->flatland()->RemoveChild(clip_transform->transform_id, child); } clip_transform->children.clear(); } } // namespace ExternalViewEmbedder::ExternalViewEmbedder( fuchsia::ui::views::ViewCreationToken view_creation_token, fuchsia::ui::views::ViewIdentityOnCreation view_identity, fuchsia::ui::composition::ViewBoundProtocols view_protocols, fidl::InterfaceRequest<fuchsia::ui::composition::ParentViewportWatcher> parent_viewport_watcher_request, std::shared_ptr<FlatlandConnection> flatland, std::shared_ptr<SurfaceProducer> surface_producer, bool intercept_all_input) : flatland_(flatland), surface_producer_(surface_producer) { flatland_->flatland()->CreateView2( std::move(view_creation_token), std::move(view_identity), std::move(view_protocols), std::move(parent_viewport_watcher_request)); root_transform_id_ = flatland_->NextTransformId(); flatland_->flatland()->CreateTransform(root_transform_id_); flatland_->flatland()->SetRootTransform(root_transform_id_); if (intercept_all_input) { input_interceptor_transform_ = flatland_->NextTransformId(); flatland_->flatland()->CreateTransform(*input_interceptor_transform_); flatland_->flatland()->SetInfiniteHitRegion( *input_interceptor_transform_, fuchsia::ui::composition::HitTestInteraction::SEMANTICALLY_INVISIBLE); flatland_->flatland()->AddChild(root_transform_id_, *input_interceptor_transform_); child_transforms_.emplace_back(*input_interceptor_transform_); } } ExternalViewEmbedder::~ExternalViewEmbedder() = default; flutter::DlCanvas* ExternalViewEmbedder::GetRootCanvas() { auto found = frame_layers_.find(kRootLayerId); if (found == frame_layers_.end()) { FML_LOG(WARNING) << "No root canvas could be found. This is extremely unlikely and " "indicates that the external view embedder did not receive the " "notification to begin the frame."; return nullptr; } return found->second.canvas_spy->GetSpyingCanvas(); } void ExternalViewEmbedder::PrerollCompositeEmbeddedView( int64_t view_id, std::unique_ptr<flutter::EmbeddedViewParams> params) { zx_handle_t handle = static_cast<zx_handle_t>(view_id); FML_CHECK(frame_layers_.count(handle) == 0); frame_layers_.emplace(std::make_pair( EmbedderLayerId{handle}, EmbedderLayer(frame_size_, *params, flutter::RTreeFactory()))); frame_composition_order_.push_back(handle); } flutter::DlCanvas* ExternalViewEmbedder::CompositeEmbeddedView( int64_t view_id) { zx_handle_t handle = static_cast<zx_handle_t>(view_id); auto found = frame_layers_.find(handle); FML_CHECK(found != frame_layers_.end()); return found->second.canvas_spy->GetSpyingCanvas(); } flutter::PostPrerollResult ExternalViewEmbedder::PostPrerollAction( const fml::RefPtr<fml::RasterThreadMerger>& raster_thread_merger) { return flutter::PostPrerollResult::kSuccess; } void ExternalViewEmbedder::BeginFrame( GrDirectContext* context, const fml::RefPtr<fml::RasterThreadMerger>& raster_thread_merger) {} // |ExternalViewEmbedder| void ExternalViewEmbedder::PrepareFlutterView(int64_t flutter_view_id, SkISize frame_size, double device_pixel_ratio) { // Reset for new view. Reset(); frame_size_ = frame_size; frame_dpr_ = device_pixel_ratio; // Create the root layer. frame_layers_.emplace(std::make_pair( kRootLayerId, EmbedderLayer(frame_size, std::nullopt, flutter::RTreeFactory()))); frame_composition_order_.push_back(kRootLayerId); } void ExternalViewEmbedder::EndFrame( bool should_resubmit_frame, const fml::RefPtr<fml::RasterThreadMerger>& raster_thread_merger) { TRACE_EVENT0("flutter", "ExternalViewEmbedder::EndFrame"); } void ExternalViewEmbedder::SubmitFlutterView( GrDirectContext* context, const std::shared_ptr<impeller::AiksContext>& aiks_context, std::unique_ptr<flutter::SurfaceFrame> frame) { TRACE_EVENT0("flutter", "ExternalViewEmbedder::SubmitFlutterView"); std::vector<std::unique_ptr<SurfaceProducerSurface>> frame_surfaces; std::unordered_map<EmbedderLayerId, size_t> frame_surface_indices; // Create surfaces for the frame and associate them with layer IDs. { TRACE_EVENT0("flutter", "CreateSurfaces"); for (const auto& layer : frame_layers_) { if (!layer.second.canvas_spy->DidDrawIntoCanvas()) { continue; } auto surface = surface_producer_->ProduceSurface(layer.second.surface_size); if (!surface) { const std::string layer_id_str = layer.first.has_value() ? std::to_string(layer.first.value()) : "Background"; FML_LOG(ERROR) << "Failed to create surface for layer " << layer_id_str << "; size (" << layer.second.surface_size.width() << ", " << layer.second.surface_size.height() << ")"; FML_DCHECK(false); continue; } // If we receive an unitialized surface, we need to first create flatland // resource. if (surface->GetImageId() == 0) { auto image_id = flatland_->NextContentId().value; const auto& size = surface->GetSize(); fuchsia::ui::composition::ImageProperties image_properties; image_properties.set_size({static_cast<uint32_t>(size.width()), static_cast<uint32_t>(size.height())}); flatland_->flatland()->CreateImage( {image_id}, surface->GetBufferCollectionImportToken(), 0, std::move(image_properties)); surface->SetImageId(image_id); surface->SetReleaseImageCallback([flatland = flatland_, image_id]() { flatland->flatland()->ReleaseImage({image_id}); }); } // Enqueue fences for the next present. flatland_->EnqueueAcquireFence(surface->GetAcquireFence()); flatland_->EnqueueReleaseFence(surface->GetReleaseFence()); frame_surface_indices.emplace( std::make_pair(layer.first, frame_surfaces.size())); frame_surfaces.emplace_back(std::move(surface)); } } // Finish recording SkPictures. { TRACE_EVENT0("flutter", "FinishRecordingPictures"); for (const auto& surface_index : frame_surface_indices) { const auto& layer = frame_layers_.find(surface_index.first); FML_CHECK(layer != frame_layers_.end()); layer->second.picture = layer->second.recorder->finishRecordingAsPicture(); FML_CHECK(layer->second.picture != nullptr); } } // Submit layers and platform views to Scenic in composition order. { TRACE_EVENT0("flutter", "SubmitLayers"); // First re-scale everything according to the DPR. const float inv_dpr = 1.0f / frame_dpr_; flatland_->flatland()->SetScale(root_transform_id_, {inv_dpr, inv_dpr}); size_t layer_index = 0; for (const auto& layer_id : frame_composition_order_) { const auto& layer = frame_layers_.find(layer_id); FML_CHECK(layer != frame_layers_.end()); // Draw the PlatformView associated with each layer first. if (layer_id.has_value()) { FML_CHECK(layer->second.embedded_view_params.has_value()); auto& view_params = layer->second.embedded_view_params.value(); // Get the View structure corresponding to the platform view. auto found = views_.find(layer_id.value()); FML_CHECK(found != views_.end()) << "No View for layer_id = " << layer_id.value() << ". This typically indicates that the Dart code in " "Fuchsia's fuchsia_scenic_flutter library failed to create " "the platform view, leading to a crash later down the road in " "the Flutter Engine code that tries to find that platform view. " "Check the Flutter Framework for changes to PlatformView that " "might have caused a regression."; auto& viewport = found->second; // Compute mutators, and size for the platform view. const ViewMutators view_mutators = ParseMutatorStack(view_params.mutatorsStack()); const SkSize view_size = view_params.sizePoints(); // Verify that we're unpacking the mutators' transform matrix correctly. // Use built-in get method for SkMatrix to get values, see: // https://source.corp.google.com/piper///depot/google3/third_party/skia/HEAD/include/core/SkMatrix.h;l=391 for (int index = 0; index < 9; index++) { const SkScalar mutators_transform_value = view_mutators.total_transform.get(index); const SkScalar params_transform_value = view_params.transformMatrix().get(index); if (!SkScalarNearlyEqual(mutators_transform_value, params_transform_value, 0.0005f)) { FML_LOG(ERROR) << "Assertion failed: view_mutators.total_transform[" << index << "] (" << mutators_transform_value << ") != view_params.transformMatrix()[" << index << "] (" << params_transform_value << "). This likely means there is a bug with the " << "logic for parsing embedded views' transform matrices."; } } if (viewport.pending_create_viewport_callback) { if (view_size.fWidth && view_size.fHeight) { viewport.pending_create_viewport_callback( view_size, viewport.pending_occlusion_hint); viewport.size = view_size; viewport.occlusion_hint = viewport.pending_occlusion_hint; } else { FML_DLOG(WARNING) << "Failed to create viewport because width or height is zero."; } } // Set transform for the viewport. if (view_mutators.transform != viewport.mutators.transform) { flatland_->flatland()->SetTranslation( viewport.transform_id, {static_cast<int32_t>(view_mutators.transform.getTranslateX()), static_cast<int32_t>(view_mutators.transform.getTranslateY())}); flatland_->flatland()->SetScale( viewport.transform_id, {view_mutators.transform.getScaleX(), view_mutators.transform.getScaleY()}); viewport.mutators.transform = view_mutators.transform; } // Set clip regions. if (view_mutators.clips != viewport.mutators.clips) { // Expand the clip_transforms array to fit any new transforms. while (viewport.clip_transforms.size() < view_mutators.clips.size()) { ClipTransform clip_transform; clip_transform.transform_id = flatland_->NextTransformId(); flatland_->flatland()->CreateTransform(clip_transform.transform_id); viewport.clip_transforms.emplace_back(std::move(clip_transform)); } FML_CHECK(viewport.clip_transforms.size() >= view_mutators.clips.size()); // Adjust and re-parent all clip transforms. for (auto& clip_transform : viewport.clip_transforms) { DetachClipTransformChildren(flatland_.get(), &clip_transform); } for (size_t c = 0; c < view_mutators.clips.size(); c++) { const SkMatrix& clip_matrix = view_mutators.clips[c].transform; const SkRect& clip_rect = view_mutators.clips[c].rect; flatland_->flatland()->SetTranslation( viewport.clip_transforms[c].transform_id, {static_cast<int32_t>(clip_matrix.getTranslateX()), static_cast<int32_t>(clip_matrix.getTranslateY())}); flatland_->flatland()->SetScale( viewport.clip_transforms[c].transform_id, {clip_matrix.getScaleX(), clip_matrix.getScaleY()}); fuchsia::math::Rect rect = { static_cast<int32_t>(clip_rect.x()), static_cast<int32_t>(clip_rect.y()), static_cast<int32_t>(clip_rect.width()), static_cast<int32_t>(clip_rect.height())}; flatland_->flatland()->SetClipBoundary( viewport.clip_transforms[c].transform_id, std::make_unique<fuchsia::math::Rect>(std::move(rect))); const auto child_transform_id = c != (view_mutators.clips.size() - 1) ? viewport.clip_transforms[c + 1].transform_id : viewport.transform_id; AttachClipTransformChild(flatland_.get(), &(viewport.clip_transforms[c]), child_transform_id); } viewport.mutators.clips = view_mutators.clips; } // Set opacity. if (view_mutators.opacity != viewport.mutators.opacity) { flatland_->flatland()->SetOpacity(viewport.transform_id, view_mutators.opacity); viewport.mutators.opacity = view_mutators.opacity; } // Set size and occlusion hint. if (view_size != viewport.size || viewport.pending_occlusion_hint != viewport.occlusion_hint) { fuchsia::ui::composition::ViewportProperties properties; properties.set_logical_size( {static_cast<uint32_t>(view_size.fWidth), static_cast<uint32_t>(view_size.fHeight)}); properties.set_inset( {static_cast<int32_t>(viewport.pending_occlusion_hint.fTop), static_cast<int32_t>(viewport.pending_occlusion_hint.fRight), static_cast<int32_t>(viewport.pending_occlusion_hint.fBottom), static_cast<int32_t>(viewport.pending_occlusion_hint.fLeft)}); flatland_->flatland()->SetViewportProperties(viewport.viewport_id, std::move(properties)); viewport.size = view_size; viewport.occlusion_hint = viewport.pending_occlusion_hint; } // Attach the View to the main scene graph. const auto main_child_transform = viewport.mutators.clips.empty() ? viewport.transform_id : viewport.clip_transforms[0].transform_id; flatland_->flatland()->AddChild(root_transform_id_, main_child_transform); child_transforms_.emplace_back(main_child_transform); } // Acquire the surface associated with the layer. SurfaceProducerSurface* surface_for_layer = nullptr; if (layer->second.canvas_spy->DidDrawIntoCanvas()) { const auto& surface_index = frame_surface_indices.find(layer_id); if (surface_index != frame_surface_indices.end()) { FML_CHECK(surface_index->second < frame_surfaces.size()); surface_for_layer = frame_surfaces[surface_index->second].get(); FML_CHECK(surface_for_layer != nullptr); } else { const std::string layer_id_str = layer_id.has_value() ? std::to_string(layer_id.value()) : "Background"; FML_LOG(ERROR) << "Missing surface for layer " << layer_id_str << "; skipping scene graph add of layer."; FML_DCHECK(false); } } // Draw the layer if we acquired a surface for it successfully. if (surface_for_layer != nullptr) { // Create a new layer if needed for the surface. FML_CHECK(layer_index <= layers_.size()); if (layer_index == layers_.size()) { Layer new_layer{.transform_id = flatland_->NextTransformId()}; flatland_->flatland()->CreateTransform(new_layer.transform_id); layers_.emplace_back(std::move(new_layer)); } // Update the image content and set size. flatland_->flatland()->SetContent(layers_[layer_index].transform_id, {surface_for_layer->GetImageId()}); flatland_->flatland()->SetImageDestinationSize( {surface_for_layer->GetImageId()}, {static_cast<uint32_t>(surface_for_layer->GetSize().width()), static_cast<uint32_t>(surface_for_layer->GetSize().height())}); // Flutter Embedder lacks an API to detect if a layer has alpha or not. // For now, we assume any layer beyond the first has alpha. flatland_->flatland()->SetImageBlendingFunction( {surface_for_layer->GetImageId()}, layer_index == 0 ? fuchsia::ui::composition::BlendMode::SRC : fuchsia::ui::composition::BlendMode::SRC_OVER); // Set hit regions for this layer; these hit regions correspond to the // portions of the layer on which skia drew content. { FML_CHECK(layer->second.rtree); std::list<SkRect> intersection_rects = layer->second.rtree->searchNonOverlappingDrawnRects( SkRect::Make(layer->second.surface_size)); std::vector<fuchsia::ui::composition::HitRegion> hit_regions; for (const SkRect& rect : intersection_rects) { hit_regions.emplace_back(); auto& new_hit_region = hit_regions.back(); new_hit_region.region.x = rect.x(); new_hit_region.region.y = rect.y(); new_hit_region.region.width = rect.width(); new_hit_region.region.height = rect.height(); new_hit_region.hit_test = fuchsia::ui::composition::HitTestInteraction::DEFAULT; } flatland_->flatland()->SetHitRegions( layers_[layer_index].transform_id, std::move(hit_regions)); } // Attach the Layer to the main scene graph. flatland_->flatland()->AddChild(root_transform_id_, layers_[layer_index].transform_id); child_transforms_.emplace_back(layers_[layer_index].transform_id); } // Reset for the next pass: layer_index++; } // Set up the input interceptor at the top of the scene, if applicable. It // will capture all input, and any unwanted input will be reinjected into // embedded views. if (input_interceptor_transform_.has_value()) { flatland_->flatland()->AddChild(root_transform_id_, *input_interceptor_transform_); child_transforms_.emplace_back(*input_interceptor_transform_); } } // Present the session to Scenic, along with surface acquire/release fences. { TRACE_EVENT0("flutter", "SessionPresent"); flatland_->Present(); } // Render the recorded SkPictures into the surfaces. { TRACE_EVENT0("flutter", "RasterizeSurfaces"); for (const auto& surface_index : frame_surface_indices) { TRACE_EVENT0("flutter", "RasterizeSurface"); FML_CHECK(surface_index.second < frame_surfaces.size()); SurfaceProducerSurface* surface = frame_surfaces[surface_index.second].get(); FML_CHECK(surface != nullptr); sk_sp<SkSurface> sk_surface = surface->GetSkiaSurface(); FML_CHECK(sk_surface != nullptr); FML_CHECK(SkISize::Make(sk_surface->width(), sk_surface->height()) == frame_size_); SkCanvas* canvas = sk_surface->getCanvas(); FML_CHECK(canvas != nullptr); const auto& layer = frame_layers_.find(surface_index.first); FML_CHECK(layer != frame_layers_.end()); canvas->setMatrix(SkMatrix::I()); canvas->clear(SK_ColorTRANSPARENT); canvas->drawPicture(layer->second.picture); if (GrDirectContext* direct_context = GrAsDirectContext(canvas->recordingContext())) { direct_context->flushAndSubmit(); } } } // Flush deferred Skia work and inform Scenic that render targets are ready. { TRACE_EVENT0("flutter", "PresentSurfaces"); surface_producer_->SubmitSurfaces(std::move(frame_surfaces)); } // Submit the underlying render-backend-specific frame for processing. frame->Submit(); } void ExternalViewEmbedder::CreateView(int64_t view_id, ViewCallback on_view_created, ViewCreatedCallback on_view_bound) { FML_CHECK(views_.find(view_id) == views_.end()); const auto transform_id = flatland_->NextTransformId(); const auto viewport_id = flatland_->NextContentId(); View new_view = {.transform_id = transform_id, .viewport_id = viewport_id}; flatland_->flatland()->CreateTransform(new_view.transform_id); fuchsia::ui::composition::ChildViewWatcherHandle child_view_watcher; new_view.pending_create_viewport_callback = [this, transform_id, viewport_id, view_id, child_view_watcher_request = child_view_watcher.NewRequest()]( const SkSize& size, const SkRect& inset) mutable { fuchsia::ui::composition::ViewportProperties properties; properties.set_logical_size({static_cast<uint32_t>(size.fWidth), static_cast<uint32_t>(size.fHeight)}); properties.set_inset({static_cast<int32_t>(inset.fTop), static_cast<int32_t>(inset.fRight), static_cast<int32_t>(inset.fBottom), static_cast<int32_t>(inset.fLeft)}); flatland_->flatland()->CreateViewport( viewport_id, {zx::channel((zx_handle_t)view_id)}, std::move(properties), std::move(child_view_watcher_request)); flatland_->flatland()->SetContent(transform_id, viewport_id); }; on_view_created(); on_view_bound(new_view.viewport_id, std::move(child_view_watcher)); views_.emplace(std::make_pair(view_id, std::move(new_view))); } void ExternalViewEmbedder::DestroyView(int64_t view_id, ViewIdCallback on_view_unbound) { auto view = views_.find(view_id); FML_CHECK(view != views_.end()); auto viewport_id = view->second.viewport_id; auto transform_id = view->second.transform_id; auto& clip_transforms = view->second.clip_transforms; if (!view->second.pending_create_viewport_callback) { flatland_->flatland()->ReleaseViewport(viewport_id, [](auto) {}); } auto itr = std::find_if( child_transforms_.begin(), child_transforms_.end(), [transform_id, &clip_transforms](fuchsia::ui::composition::TransformId id) { return id.value == transform_id.value || (!clip_transforms.empty() && (id.value == clip_transforms[0].transform_id.value)); }); if (itr != child_transforms_.end()) { flatland_->flatland()->RemoveChild(root_transform_id_, *itr); child_transforms_.erase(itr); } for (auto& clip_transform : clip_transforms) { DetachClipTransformChildren(flatland_.get(), &clip_transform); } flatland_->flatland()->ReleaseTransform(transform_id); for (auto& clip_transform : clip_transforms) { flatland_->flatland()->ReleaseTransform(clip_transform.transform_id); } views_.erase(view); on_view_unbound(viewport_id); } void ExternalViewEmbedder::SetViewProperties(int64_t view_id, const SkRect& occlusion_hint, bool hit_testable, bool focusable) { auto found = views_.find(view_id); FML_CHECK(found != views_.end()); // Note that pending_create_viewport_callback might not have run at this // point. auto& viewport = found->second; viewport.pending_occlusion_hint = occlusion_hint; } void ExternalViewEmbedder::Reset() { frame_layers_.clear(); frame_composition_order_.clear(); frame_size_ = SkISize::Make(0, 0); frame_dpr_ = 1.f; // Clear all children from root. for (const auto& transform : child_transforms_) { flatland_->flatland()->RemoveChild(root_transform_id_, transform); } child_transforms_.clear(); // Clear images on all layers so they aren't cached unnecessarily. for (const auto& layer : layers_) { flatland_->flatland()->SetContent(layer.transform_id, {0}); } } ExternalViewEmbedder::ViewMutators ExternalViewEmbedder::ParseMutatorStack( const flutter::MutatorsStack& mutators_stack) { ViewMutators mutators; SkMatrix total_transform = SkMatrix::I(); SkMatrix transform_accumulator = SkMatrix::I(); for (auto i = mutators_stack.Begin(); i != mutators_stack.End(); ++i) { const auto& mutator = *i; switch (mutator->GetType()) { case flutter::MutatorType::kOpacity: { mutators.opacity *= std::clamp(mutator->GetAlphaFloat(), 0.f, 1.f); } break; case flutter::MutatorType::kTransform: { total_transform.preConcat(mutator->GetMatrix()); transform_accumulator.preConcat(mutator->GetMatrix()); } break; case flutter::MutatorType::kClipRect: { mutators.clips.emplace_back(TransformedClip{ .transform = transform_accumulator, .rect = mutator->GetRect(), }); transform_accumulator = SkMatrix::I(); } break; case flutter::MutatorType::kClipRRect: { mutators.clips.emplace_back(TransformedClip{ .transform = transform_accumulator, .rect = mutator->GetRRect().getBounds(), }); transform_accumulator = SkMatrix::I(); } break; case flutter::MutatorType::kClipPath: { mutators.clips.emplace_back(TransformedClip{ .transform = transform_accumulator, .rect = mutator->GetPath().getBounds(), }); transform_accumulator = SkMatrix::I(); } break; default: { break; } } } mutators.total_transform = total_transform; mutators.transform = transform_accumulator; mutators.opacity = std::clamp(mutators.opacity, 0.f, 1.f); return mutators; } } // namespace flutter_runner
engine/shell/platform/fuchsia/flutter/external_view_embedder.cc/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/external_view_embedder.cc", "repo_id": "engine", "token_count": 11700 }
357
// 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_SHELL_PLATFORM_FUCHSIA_FLUTTER_ISOLATE_CONFIGURATOR_H_ #define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_ISOLATE_CONFIGURATOR_H_ #include <lib/zx/channel.h> #include <lib/zx/eventpair.h> #include "flutter/fml/macros.h" #include "unique_fdio_ns.h" namespace flutter_runner { // Contains all the information necessary to configure a new root isolate. This // is a single use item. The lifetime of this object must extend past that of // the root isolate. class IsolateConfigurator final { public: IsolateConfigurator(UniqueFDIONS fdio_ns, zx::channel directory_request, zx::eventpair view_ref); ~IsolateConfigurator(); // Can be used only once and only on the UI thread with the newly created // isolate already current. bool ConfigureCurrentIsolate(); private: bool used_ = false; UniqueFDIONS fdio_ns_; zx::channel directory_request_; zx::eventpair view_ref_; void BindFuchsia(); void BindZircon(); void BindDartIO(); FML_DISALLOW_COPY_AND_ASSIGN(IsolateConfigurator); }; } // namespace flutter_runner #endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_ISOLATE_CONFIGURATOR_H_
engine/shell/platform/fuchsia/flutter/isolate_configurator.h/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/isolate_configurator.h", "repo_id": "engine", "token_count": 489 }
358
// 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 <gtest/gtest.h> #include "runner.h" #include "third_party/icu/source/i18n/unicode/timezone.h" namespace flutter_runner { // This test has not been configured with tzdata files. This test shows that // even without the data files, the runner continues initialization. It will // use whatever the base data exists in icudtl.dat. TEST(RunnerTZDataTest, LoadsWithoutTZDataPresent) { bool success = Runner::SetupICUInternal(); ASSERT_TRUE(success) << "failed to load set up ICU data"; } } // namespace flutter_runner
engine/shell/platform/fuchsia/flutter/runner_tzdata_missing_unittest.cc/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/runner_tzdata_missing_unittest.cc", "repo_id": "engine", "token_count": 212 }
359
// 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_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_FAKES_MOCK_INJECTOR_REGISTRY_H_ #define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_FAKES_MOCK_INJECTOR_REGISTRY_H_ #include <fuchsia/ui/pointerinjector/cpp/fidl.h> #include <lib/fidl/cpp/binding_set.h> #include <unordered_map> namespace flutter_runner::testing { // A test stub to act as the protocol server. A test can control what is sent // back by this server implementation, via the ScheduleCallback call. class MockInjectorRegistry : public fuchsia::ui::pointerinjector::Registry, public fuchsia::ui::pointerinjector::Device { public: explicit MockInjectorRegistry( fidl::InterfaceRequest<fuchsia::ui::pointerinjector::Registry> registry) : registry_(this, std::move(registry)) {} // |fuchsia.ui.pointerinjector.Registry.Register|. void Register( fuchsia::ui::pointerinjector::Config config, fidl::InterfaceRequest<fuchsia::ui::pointerinjector::Device> injector, RegisterCallback callback) override { num_register_calls_++; const uint32_t id = next_id_++; auto [it, success] = bindings_.try_emplace(id, this, std::move(injector)); it->second.set_error_handler( [this, id](zx_status_t status) { bindings_.erase(id); }); config_ = std::move(config); callback(); } // |fuchsia.ui.pointerinjector.Device.Inject|. void Inject(std::vector<fuchsia::ui::pointerinjector::Event> events, InjectCallback callback) override { num_events_received_ += events.size(); for (auto& event : events) { events_.push_back(std::move(event)); } callback(); } void ClearBindings() { bindings_.clear(); } // Returns the |fuchsia::ui::pointerinjector::Config| received in the last // |Register(...)| call. const fuchsia::ui::pointerinjector::Config& config() const { return config_; } // Returns all the |fuchsia::ui::pointerinjector::Event|s received from the // |Inject(...)| calls. const std::vector<fuchsia::ui::pointerinjector::Event>& events() const { return events_; } uint32_t num_register_calls() { return num_register_calls_; } size_t num_registered() { return bindings_.size(); } uint32_t num_events_received() const { return num_events_received_; } private: uint32_t next_id_ = 0; uint32_t num_events_received_ = 0; uint32_t num_register_calls_ = 0; fuchsia::ui::pointerinjector::Config config_; std::vector<fuchsia::ui::pointerinjector::Event> events_; std::unordered_map<uint32_t, fidl::Binding<fuchsia::ui::pointerinjector::Device>> bindings_; fidl::Binding<fuchsia::ui::pointerinjector::Registry> registry_; FML_DISALLOW_COPY_AND_ASSIGN(MockInjectorRegistry); }; } // namespace flutter_runner::testing #endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_FAKES_MOCK_INJECTOR_REGISTRY_H_
engine/shell/platform/fuchsia/flutter/tests/fakes/mock_injector_registry.h/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/tests/fakes/mock_injector_registry.h", "repo_id": "engine", "token_count": 1156 }
360
// 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'; void main(List<String> args) { print('child-view: starting'); TestApp app = TestApp(); app.run(); } class TestApp { static const _yellow = Color.fromARGB(255, 255, 255, 0); static const _pink = Color.fromARGB(255, 255, 0, 255); Color _backgroundColor = _pink; void run() { window.onPointerDataPacket = (PointerDataPacket packet) { this.pointerDataPacket(packet); }; window.onMetricsChanged = () { window.scheduleFrame(); }; window.onBeginFrame = (Duration duration) { this.beginFrame(duration); }; window.scheduleFrame(); } void beginFrame(Duration duration) { final pixelRatio = window.devicePixelRatio; final size = window.physicalSize / pixelRatio; final physicalBounds = Offset.zero & size * pixelRatio; final recorder = PictureRecorder(); final canvas = Canvas(recorder, physicalBounds); canvas.scale(pixelRatio, pixelRatio); final paint = Paint()..color = this._backgroundColor; canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), paint); final picture = recorder.endRecording(); final sceneBuilder = SceneBuilder() ..pushClipRect(physicalBounds) ..addPicture(Offset.zero, picture) ..pop(); window.render(sceneBuilder.build()); } void pointerDataPacket(PointerDataPacket packet) { for (final data in packet.data) { if (data.change == PointerChange.down) { this._backgroundColor = _yellow; } } window.scheduleFrame(); } }
engine/shell/platform/fuchsia/flutter/tests/integration/embedder/child-view/lib/child_view.dart/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/tests/integration/embedder/child-view/lib/child_view.dart", "repo_id": "engine", "token_count": 599 }
361
# Copyright 2013 The Flutter Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import("//flutter/tools/fuchsia/dart/dart_library.gni") import("//flutter/tools/fuchsia/flutter/flutter_component.gni") import("//flutter/tools/fuchsia/gn-sdk/src/component.gni") import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni") import("//flutter/tools/fuchsia/gn-sdk/src/package.gni") dart_library("lib") { package_name = "touch-input-view" sources = [ "touch-input-view.dart" ] deps = [ "//flutter/shell/platform/fuchsia/dart:args" ] } flutter_component("component") { testonly = true component_name = "touch-input-view" manifest = rebase_path("meta/touch-input-view.cml") main_package = "touch-input-view" main_dart = "touch-input-view.dart" deps = [ ":lib" ] } fuchsia_package("package") { testonly = true package_name = "touch-input-view" deps = [ ":component" ] }
engine/shell/platform/fuchsia/flutter/tests/integration/touch-input/touch-input-view/BUILD.gn/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/tests/integration/touch-input/touch-input-view/BUILD.gn", "repo_id": "engine", "token_count": 369 }
362
# Copyright 2013 The Flutter Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import("//flutter/build/dart/dart.gni") import("//flutter/tools/fuchsia/clang.gni") import("$dart_src/build/dart/dart_action.gni") template("generate_dart_profiler_symbols") { assert(defined(invoker.library_label), "Must define 'library_label'") assert(defined(invoker.library_path), "Must define 'library_path'") assert(defined(invoker.output), "Must define 'output'") prebuilt_dart_action(target_name) { deps = [ invoker.library_label ] inputs = [ invoker.library_path ] outputs = [ invoker.output ] script = "dart_profiler_symbols.dart" packages = rebase_path("$dart_src/.dart_tool/package_config.json") args = [ "--nm", rebase_path("//buildtools/${host_os}-${host_cpu}/clang/bin/llvm-nm"), "--binary", rebase_path(invoker.library_path), "--output", rebase_path(invoker.output), ] } } generate_dart_profiler_symbols("dart_jit_runner") { library_label = "//flutter/shell/platform/fuchsia/dart_runner:dart_jit_runner_bin" library_path = "${root_out_dir}/exe.unstripped/dart_jit_runner" output = "${target_gen_dir}/dart_jit_runner.dartprofilersymbols" } generate_dart_profiler_symbols("dart_aot_runner") { library_label = "//flutter/shell/platform/fuchsia/dart_runner:dart_aot_runner_bin" library_path = "${root_out_dir}/exe.unstripped/dart_aot_runner" output = "${target_gen_dir}/dart_aot_runner.dartprofilersymbols" } generate_dart_profiler_symbols("flutter_jit_runner") { library_label = "//flutter/shell/platform/fuchsia/flutter:jit" library_path = "${root_out_dir}/exe.unstripped/flutter_jit_runner" output = "${target_gen_dir}/flutter_jit_runner.dartprofilersymbols" } generate_dart_profiler_symbols("flutter_aot_runner") { library_label = "//flutter/shell/platform/fuchsia/flutter:aot" library_path = "${root_out_dir}/exe.unstripped/flutter_aot_runner" output = "${target_gen_dir}/flutter_aot_runner.dartprofilersymbols" }
engine/shell/platform/fuchsia/runtime/dart/profiler_symbols/BUILD.gn/0
{ "file_path": "engine/shell/platform/fuchsia/runtime/dart/profiler_symbols/BUILD.gn", "repo_id": "engine", "token_count": 862 }
363
// 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 "root_inspect_node.h" #include <lib/async/default.h> namespace dart_utils { std::unique_ptr<inspect::ComponentInspector> RootInspectNode::inspector_; std::mutex RootInspectNode::mutex_; void RootInspectNode::Initialize(sys::ComponentContext* context) { std::lock_guard<std::mutex> lock(mutex_); if (!inspector_) { inspector_ = std::make_unique<inspect::ComponentInspector>( async_get_default_dispatcher(), inspect::PublishOptions{}); } } inspect::Node RootInspectNode::CreateRootChild(const std::string& name) { std::lock_guard<std::mutex> lock(mutex_); return inspector_->inspector().GetRoot().CreateChild(name); } inspect::Inspector* RootInspectNode::GetInspector() { return &inspector_->inspector(); } } // namespace dart_utils
engine/shell/platform/fuchsia/runtime/dart/utils/root_inspect_node.cc/0
{ "file_path": "engine/shell/platform/fuchsia/runtime/dart/utils/root_inspect_node.cc", "repo_id": "engine", "token_count": 321 }
364
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/glfw/client_wrapper/include/flutter/flutter_window.h" #include <memory> #include <string> #include "flutter/shell/platform/glfw/client_wrapper/testing/stub_flutter_glfw_api.h" #include "gtest/gtest.h" namespace flutter { namespace { // Stub implementation to validate calls to the API. class TestGlfwApi : public testing::StubFlutterGlfwApi { public: // |flutter::testing::StubFlutterGlfwApi| void SetSizeLimits(FlutterDesktopSize minimum_size, FlutterDesktopSize maximum_size) override { set_size_limits_called_ = true; } bool set_size_limits_called() { return set_size_limits_called_; } private: bool set_size_limits_called_ = false; }; } // namespace TEST(FlutterWindowTest, SetSizeLimits) { const std::string icu_data_path = "fake/path/to/icu"; testing::ScopedStubFlutterGlfwApi scoped_api_stub( std::make_unique<TestGlfwApi>()); auto test_api = static_cast<TestGlfwApi*>(scoped_api_stub.stub()); // This is not actually used so any non-zero value works. auto raw_window = reinterpret_cast<FlutterDesktopWindowRef>(1); auto window = std::make_unique<FlutterWindow>(raw_window); FlutterDesktopSize minimum_size = {}; minimum_size.width = 100; minimum_size.height = 100; FlutterDesktopSize maximum_size = {}; maximum_size.width = -1; maximum_size.height = -1; window->SetSizeLimits(minimum_size, maximum_size); EXPECT_EQ(test_api->set_size_limits_called(), true); } } // namespace flutter
engine/shell/platform/glfw/client_wrapper/flutter_window_unittests.cc/0
{ "file_path": "engine/shell/platform/glfw/client_wrapper/flutter_window_unittests.cc", "repo_id": "engine", "token_count": 597 }
365
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/glfw/key_event_handler.h" #include <iostream> #include "flutter/shell/platform/common/json_message_codec.h" static constexpr char kChannelName[] = "flutter/keyevent"; static constexpr char kKeyCodeKey[] = "keyCode"; static constexpr char kKeyMapKey[] = "keymap"; static constexpr char kScanCodeKey[] = "scanCode"; static constexpr char kModifiersKey[] = "modifiers"; static constexpr char kTypeKey[] = "type"; static constexpr char kToolkitKey[] = "toolkit"; static constexpr char kUnicodeScalarValues[] = "unicodeScalarValues"; static constexpr char kLinuxKeyMap[] = "linux"; static constexpr char kGLFWKey[] = "glfw"; static constexpr char kKeyUp[] = "keyup"; static constexpr char kKeyDown[] = "keydown"; // Masks used for UTF-8 to UTF-32 conversion. static constexpr int kTwoByteMask = 0xC0; static constexpr int kThreeByteMask = 0xE0; static constexpr int kFourByteMask = 0xF0; namespace flutter { namespace { // Information about the UTF-8 encoded code point. struct UTF8CodePointInfo { // The bit-mask that determines the length of the code point. int first_byte_mask; // The number of bytes of the code point. size_t length; }; // Creates a [UTF8CodePointInfo] from a given byte. [first_byte] must be the // first byte in the code point. UTF8CodePointInfo GetUTF8CodePointInfo(int first_byte) { UTF8CodePointInfo byte_info; // The order matters. Otherwise, it is possible that comparing against i.e. // kThreeByteMask and kFourByteMask could be both true. if ((first_byte & kFourByteMask) == kFourByteMask) { byte_info.first_byte_mask = 0x07; byte_info.length = 4; } else if ((first_byte & kThreeByteMask) == kThreeByteMask) { byte_info.first_byte_mask = 0x0F; byte_info.length = 3; } else if ((first_byte & kTwoByteMask) == kTwoByteMask) { byte_info.first_byte_mask = 0x1F; byte_info.length = 2; } else { byte_info.first_byte_mask = 0xFF; byte_info.length = 1; } return byte_info; } // Queries GLFW for the printable key name given a [key] and [scan_code] and // converts it to UTF-32. The Flutter framework accepts only one code point, // therefore, only the first code point will be used. There is unlikely to be // more than one, but there is no guarantee that it won't happen. bool GetUTF32CodePointFromGLFWKey(int key, int scan_code, uint32_t* code_point) { // Get the name of the printable key, encoded as UTF-8. // There's a known issue with glfwGetKeyName, where users with multiple // layouts configured on their machines, will not always return the right // value. See: https://github.com/glfw/glfw/issues/1462 const char* utf8 = glfwGetKeyName(key, scan_code); if (utf8 == nullptr) { return false; } // The first byte determines the length of the whole code point. const auto byte_info = GetUTF8CodePointInfo(utf8[0]); // Tracks how many bits the current byte should shift to the left. int shift = byte_info.length - 1; const int complement_mask = 0x3F; uint32_t result = 0; size_t current_byte_index = 0; while (current_byte_index < byte_info.length) { const int current_byte = utf8[current_byte_index]; const int mask = current_byte_index == 0 ? byte_info.first_byte_mask : complement_mask; current_byte_index++; const int bits_to_shift = 6 * shift--; result += (current_byte & mask) << bits_to_shift; } *code_point = result; return true; } } // namespace KeyEventHandler::KeyEventHandler(flutter::BinaryMessenger* messenger) : channel_( std::make_unique<flutter::BasicMessageChannel<rapidjson::Document>>( messenger, kChannelName, &flutter::JsonMessageCodec::GetInstance())) {} KeyEventHandler::~KeyEventHandler() = default; void KeyEventHandler::CharHook(GLFWwindow* window, unsigned int code_point) {} void KeyEventHandler::KeyboardHook(GLFWwindow* window, int key, int scancode, int action, int mods) { // TODO(chrome-bot): Translate to a cross-platform key code system rather than // passing the native key code. // NOLINTNEXTLINE(clang-analyzer-core.NullDereference) rapidjson::Document event(rapidjson::kObjectType); auto& allocator = event.GetAllocator(); event.AddMember(kKeyCodeKey, key, allocator); event.AddMember(kKeyMapKey, kLinuxKeyMap, allocator); event.AddMember(kScanCodeKey, scancode, allocator); event.AddMember(kModifiersKey, mods, allocator); event.AddMember(kToolkitKey, kGLFWKey, allocator); uint32_t unicodeInt; bool result = GetUTF32CodePointFromGLFWKey(key, scancode, &unicodeInt); if (result) { event.AddMember(kUnicodeScalarValues, unicodeInt, allocator); } switch (action) { case GLFW_PRESS: case GLFW_REPEAT: event.AddMember(kTypeKey, kKeyDown, allocator); break; case GLFW_RELEASE: event.AddMember(kTypeKey, kKeyUp, allocator); break; default: std::cerr << "Unknown key event action: " << action << std::endl; return; } channel_->Send(event); } } // namespace flutter
engine/shell/platform/glfw/key_event_handler.cc/0
{ "file_path": "engine/shell/platform/glfw/key_event_handler.cc", "repo_id": "engine", "token_count": 2014 }
366
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/linux/fl_accessible_text_field.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_standard_message_codec.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_value.h" G_DEFINE_AUTOPTR_CLEANUP_FUNC(PangoContext, g_object_unref) // PangoLayout g_autoptr macro weren't added until 1.49.4. Add them manually. // https://gitlab.gnome.org/GNOME/pango/-/commit/0b84e14 #if !PANGO_VERSION_CHECK(1, 49, 4) G_DEFINE_AUTOPTR_CLEANUP_FUNC(PangoLayout, g_object_unref) #endif typedef bool (*FlTextBoundaryCallback)(const PangoLogAttr* attr); struct _FlAccessibleTextField { FlAccessibleNode parent_instance; gint selection_base; gint selection_extent; GtkEntryBuffer* buffer; FlutterTextDirection text_direction; }; static void fl_accessible_text_iface_init(AtkTextIface* iface); static void fl_accessible_editable_text_iface_init(AtkEditableTextIface* iface); G_DEFINE_TYPE_WITH_CODE( FlAccessibleTextField, fl_accessible_text_field, FL_TYPE_ACCESSIBLE_NODE, G_IMPLEMENT_INTERFACE(ATK_TYPE_TEXT, fl_accessible_text_iface_init) G_IMPLEMENT_INTERFACE(ATK_TYPE_EDITABLE_TEXT, fl_accessible_editable_text_iface_init)) static gchar* get_substring(FlAccessibleTextField* self, glong start, glong end) { const gchar* value = gtk_entry_buffer_get_text(self->buffer); if (end == -1) { // g_utf8_substring() accepts -1 since 2.72 end = g_utf8_strlen(value, -1); } return g_utf8_substring(value, start, end); } static PangoContext* get_pango_context(FlAccessibleTextField* self) { PangoFontMap* font_map = pango_cairo_font_map_get_default(); PangoContext* context = pango_font_map_create_context(font_map); pango_context_set_base_dir(context, self->text_direction == kFlutterTextDirectionRTL ? PANGO_DIRECTION_RTL : PANGO_DIRECTION_LTR); return context; } static PangoLayout* create_pango_layout(FlAccessibleTextField* self) { g_autoptr(PangoContext) context = get_pango_context(self); PangoLayout* layout = pango_layout_new(context); pango_layout_set_text(layout, gtk_entry_buffer_get_text(self->buffer), -1); return layout; } static gchar* get_string_at_offset(FlAccessibleTextField* self, gint start, gint end, FlTextBoundaryCallback is_start, FlTextBoundaryCallback is_end, gint* start_offset, gint* end_offset) { g_autoptr(PangoLayout) layout = create_pango_layout(self); gint n_attrs = 0; const PangoLogAttr* attrs = pango_layout_get_log_attrs_readonly(layout, &n_attrs); while (start > 0 && !is_start(&attrs[start])) { --start; } if (start_offset != nullptr) { *start_offset = start; } while (end < n_attrs && !is_end(&attrs[end])) { ++end; } if (end_offset != nullptr) { *end_offset = end; } return get_substring(self, start, end); } static gchar* get_char_at_offset(FlAccessibleTextField* self, gint offset, gint* start_offset, gint* end_offset) { return get_string_at_offset( self, offset, offset + 1, [](const PangoLogAttr* attr) -> bool { return attr->is_char_break; }, [](const PangoLogAttr* attr) -> bool { return attr->is_char_break; }, start_offset, end_offset); } static gchar* get_word_at_offset(FlAccessibleTextField* self, gint offset, gint* start_offset, gint* end_offset) { return get_string_at_offset( self, offset, offset, [](const PangoLogAttr* attr) -> bool { return attr->is_word_start; }, [](const PangoLogAttr* attr) -> bool { return attr->is_word_end; }, start_offset, end_offset); } static gchar* get_sentence_at_offset(FlAccessibleTextField* self, gint offset, gint* start_offset, gint* end_offset) { return get_string_at_offset( self, offset, offset, [](const PangoLogAttr* attr) -> bool { return attr->is_sentence_start; }, [](const PangoLogAttr* attr) -> bool { return attr->is_sentence_end; }, start_offset, end_offset); } static gchar* get_line_at_offset(FlAccessibleTextField* self, gint offset, gint* start_offset, gint* end_offset) { g_autoptr(PangoLayout) layout = create_pango_layout(self); GSList* lines = pango_layout_get_lines_readonly(layout); while (lines != nullptr) { PangoLayoutLine* line = static_cast<PangoLayoutLine*>(lines->data); if (offset >= line->start_index && offset <= line->start_index + line->length) { if (start_offset != nullptr) { *start_offset = line->start_index; } if (end_offset != nullptr) { *end_offset = line->start_index + line->length; } return get_substring(self, line->start_index, line->start_index + line->length); } lines = lines->next; } return nullptr; } static gchar* get_paragraph_at_offset(FlAccessibleTextField* self, gint offset, gint* start_offset, gint* end_offset) { g_autoptr(PangoLayout) layout = create_pango_layout(self); PangoLayoutLine* start = nullptr; PangoLayoutLine* end = nullptr; gint n_lines = pango_layout_get_line_count(layout); for (gint i = 0; i < n_lines; ++i) { PangoLayoutLine* line = pango_layout_get_line(layout, i); if (line->is_paragraph_start) { end = line; } if (start != nullptr && end != nullptr && offset >= start->start_index && offset <= end->start_index + end->length) { if (start_offset != nullptr) { *start_offset = start->start_index; } if (end_offset != nullptr) { *end_offset = end->start_index + end->length; } return get_substring(self, start->start_index, end->start_index + end->length); } if (line->is_paragraph_start) { start = line; } } return nullptr; } static void perform_set_text_action(FlAccessibleTextField* self, const char* text) { g_autoptr(FlValue) value = fl_value_new_string(text); g_autoptr(FlStandardMessageCodec) codec = fl_standard_message_codec_new(); g_autoptr(GBytes) message = fl_message_codec_encode_message(FL_MESSAGE_CODEC(codec), value, nullptr); fl_accessible_node_perform_action(FL_ACCESSIBLE_NODE(self), kFlutterSemanticsActionSetText, message); } static void perform_set_selection_action(FlAccessibleTextField* self, gint base, gint extent) { g_autoptr(FlValue) value = fl_value_new_map(); fl_value_set_string_take(value, "base", fl_value_new_int(base)); fl_value_set_string_take(value, "extent", fl_value_new_int(extent)); g_autoptr(FlStandardMessageCodec) codec = fl_standard_message_codec_new(); g_autoptr(GBytes) message = fl_message_codec_encode_message(FL_MESSAGE_CODEC(codec), value, nullptr); fl_accessible_node_perform_action( FL_ACCESSIBLE_NODE(self), kFlutterSemanticsActionSetSelection, message); } // Implements GObject::dispose. static void fl_accessible_text_field_dispose(GObject* object) { FlAccessibleTextField* self = FL_ACCESSIBLE_TEXT_FIELD(object); g_clear_object(&self->buffer); G_OBJECT_CLASS(fl_accessible_text_field_parent_class)->dispose(object); } // Implements FlAccessibleNode::set_value. static void fl_accessible_text_field_set_value(FlAccessibleNode* node, const gchar* value) { g_return_if_fail(FL_IS_ACCESSIBLE_TEXT_FIELD(node)); FlAccessibleTextField* self = FL_ACCESSIBLE_TEXT_FIELD(node); if (g_strcmp0(gtk_entry_buffer_get_text(self->buffer), value) == 0) { return; } gtk_entry_buffer_set_text(self->buffer, value, -1); } // Implements FlAccessibleNode::set_text_selection. static void fl_accessible_text_field_set_text_selection(FlAccessibleNode* node, gint base, gint extent) { g_return_if_fail(FL_IS_ACCESSIBLE_TEXT_FIELD(node)); FlAccessibleTextField* self = FL_ACCESSIBLE_TEXT_FIELD(node); gboolean caret_moved = extent != self->selection_extent; gboolean has_selection = base != extent; gboolean had_selection = self->selection_base != self->selection_extent; gboolean selection_changed = (has_selection || had_selection) && (caret_moved || base != self->selection_base); self->selection_base = base; self->selection_extent = extent; if (selection_changed) { g_signal_emit_by_name(self, "text-selection-changed", nullptr); } if (caret_moved) { g_signal_emit_by_name(self, "text-caret-moved", extent, nullptr); } } // Implements FlAccessibleNode::set_text_direction. static void fl_accessible_text_field_set_text_direction( FlAccessibleNode* node, FlutterTextDirection direction) { g_return_if_fail(FL_IS_ACCESSIBLE_TEXT_FIELD(node)); FlAccessibleTextField* self = FL_ACCESSIBLE_TEXT_FIELD(node); self->text_direction = direction; } // Overrides FlAccessibleNode::perform_action. void fl_accessible_text_field_perform_action(FlAccessibleNode* self, FlutterSemanticsAction action, GBytes* data) { FlAccessibleNodeClass* parent_class = FL_ACCESSIBLE_NODE_CLASS(fl_accessible_text_field_parent_class); switch (action) { case kFlutterSemanticsActionMoveCursorForwardByCharacter: case kFlutterSemanticsActionMoveCursorBackwardByCharacter: case kFlutterSemanticsActionMoveCursorForwardByWord: case kFlutterSemanticsActionMoveCursorBackwardByWord: { // These actions require a boolean argument that indicates whether the // selection should be extended or collapsed when moving the cursor. g_autoptr(FlValue) extend_selection = fl_value_new_bool(false); g_autoptr(FlStandardMessageCodec) codec = fl_standard_message_codec_new(); g_autoptr(GBytes) message = fl_message_codec_encode_message( FL_MESSAGE_CODEC(codec), extend_selection, nullptr); parent_class->perform_action(self, action, message); break; } default: parent_class->perform_action(self, action, data); break; } } // Implements AtkText::get_character_count. static gint fl_accessible_text_field_get_character_count(AtkText* text) { g_return_val_if_fail(FL_IS_ACCESSIBLE_TEXT_FIELD(text), 0); FlAccessibleTextField* self = FL_ACCESSIBLE_TEXT_FIELD(text); return gtk_entry_buffer_get_length(self->buffer); } // Implements AtkText::get_text. static gchar* fl_accessible_text_field_get_text(AtkText* text, gint start_offset, gint end_offset) { g_return_val_if_fail(FL_IS_ACCESSIBLE_TEXT_FIELD(text), nullptr); FlAccessibleTextField* self = FL_ACCESSIBLE_TEXT_FIELD(text); return get_substring(self, start_offset, end_offset); } // Implements AtkText::get_string_at_offset. static gchar* fl_accessible_text_field_get_string_at_offset( AtkText* text, gint offset, AtkTextGranularity granularity, gint* start_offset, gint* end_offset) { g_return_val_if_fail(FL_IS_ACCESSIBLE_TEXT_FIELD(text), nullptr); FlAccessibleTextField* self = FL_ACCESSIBLE_TEXT_FIELD(text); switch (granularity) { case ATK_TEXT_GRANULARITY_CHAR: return get_char_at_offset(self, offset, start_offset, end_offset); case ATK_TEXT_GRANULARITY_WORD: return get_word_at_offset(self, offset, start_offset, end_offset); case ATK_TEXT_GRANULARITY_SENTENCE: return get_sentence_at_offset(self, offset, start_offset, end_offset); case ATK_TEXT_GRANULARITY_LINE: return get_line_at_offset(self, offset, start_offset, end_offset); case ATK_TEXT_GRANULARITY_PARAGRAPH: return get_paragraph_at_offset(self, offset, start_offset, end_offset); default: return nullptr; } } // Implements AtkText::get_text_at_offset (deprecated but still commonly used). static gchar* fl_accessible_text_field_get_text_at_offset( AtkText* text, gint offset, AtkTextBoundary boundary_type, gint* start_offset, gint* end_offset) { switch (boundary_type) { case ATK_TEXT_BOUNDARY_CHAR: return fl_accessible_text_field_get_string_at_offset( text, offset, ATK_TEXT_GRANULARITY_CHAR, start_offset, end_offset); break; case ATK_TEXT_BOUNDARY_WORD_START: case ATK_TEXT_BOUNDARY_WORD_END: return fl_accessible_text_field_get_string_at_offset( text, offset, ATK_TEXT_GRANULARITY_WORD, start_offset, end_offset); break; case ATK_TEXT_BOUNDARY_SENTENCE_START: case ATK_TEXT_BOUNDARY_SENTENCE_END: return fl_accessible_text_field_get_string_at_offset( text, offset, ATK_TEXT_GRANULARITY_SENTENCE, start_offset, end_offset); break; case ATK_TEXT_BOUNDARY_LINE_START: case ATK_TEXT_BOUNDARY_LINE_END: return fl_accessible_text_field_get_string_at_offset( text, offset, ATK_TEXT_GRANULARITY_LINE, start_offset, end_offset); break; default: return nullptr; } } // Implements AtkText::get_caret_offset. static gint fl_accessible_text_field_get_caret_offset(AtkText* text) { g_return_val_if_fail(FL_IS_ACCESSIBLE_TEXT_FIELD(text), -1); FlAccessibleTextField* self = FL_ACCESSIBLE_TEXT_FIELD(text); return self->selection_extent; } // Implements AtkText::set_caret_offset. static gboolean fl_accessible_text_field_set_caret_offset(AtkText* text, gint offset) { g_return_val_if_fail(FL_IS_ACCESSIBLE_TEXT_FIELD(text), false); FlAccessibleTextField* self = FL_ACCESSIBLE_TEXT_FIELD(text); perform_set_selection_action(self, offset, offset); return true; } // Implements AtkText::get_n_selections. static gint fl_accessible_text_field_get_n_selections(AtkText* text) { g_return_val_if_fail(FL_IS_ACCESSIBLE_TEXT_FIELD(text), 0); FlAccessibleTextField* self = FL_ACCESSIBLE_TEXT_FIELD(text); if (self->selection_base == self->selection_extent) { return 0; } return 1; } // Implements AtkText::get_selection. static gchar* fl_accessible_text_field_get_selection(AtkText* text, gint selection_num, gint* start_offset, gint* end_offset) { g_return_val_if_fail(FL_IS_ACCESSIBLE_TEXT_FIELD(text), nullptr); FlAccessibleTextField* self = FL_ACCESSIBLE_TEXT_FIELD(text); if (selection_num != 0 || self->selection_base == self->selection_extent) { return nullptr; } gint start = MIN(self->selection_base, self->selection_extent); gint end = MAX(self->selection_base, self->selection_extent); if (start_offset != nullptr) { *start_offset = start; } if (end_offset != nullptr) { *end_offset = end; } return get_substring(self, start, end); } // Implements AtkText::add_selection. static gboolean fl_accessible_text_field_add_selection(AtkText* text, gint start_offset, gint end_offset) { g_return_val_if_fail(FL_IS_ACCESSIBLE_TEXT_FIELD(text), false); FlAccessibleTextField* self = FL_ACCESSIBLE_TEXT_FIELD(text); if (self->selection_base != self->selection_extent) { return false; } perform_set_selection_action(self, start_offset, end_offset); return true; } // Implements AtkText::remove_selection. static gboolean fl_accessible_text_field_remove_selection(AtkText* text, gint selection_num) { g_return_val_if_fail(FL_IS_ACCESSIBLE_TEXT_FIELD(text), false); FlAccessibleTextField* self = FL_ACCESSIBLE_TEXT_FIELD(text); if (selection_num != 0 || self->selection_base == self->selection_extent) { return false; } perform_set_selection_action(self, self->selection_extent, self->selection_extent); return true; } // Implements AtkText::set_selection. static gboolean fl_accessible_text_field_set_selection(AtkText* text, gint selection_num, gint start_offset, gint end_offset) { g_return_val_if_fail(FL_IS_ACCESSIBLE_TEXT_FIELD(text), false); FlAccessibleTextField* self = FL_ACCESSIBLE_TEXT_FIELD(text); if (selection_num != 0) { return false; } perform_set_selection_action(self, start_offset, end_offset); return true; } // Implements AtkEditableText::set_text_contents. static void fl_accessible_text_field_set_text_contents( AtkEditableText* editable_text, const gchar* string) { g_return_if_fail(FL_IS_ACCESSIBLE_TEXT_FIELD(editable_text)); FlAccessibleTextField* self = FL_ACCESSIBLE_TEXT_FIELD(editable_text); perform_set_text_action(self, string); } // Implements AtkEditableText::insert_text. static void fl_accessible_text_field_insert_text(AtkEditableText* editable_text, const gchar* string, gint length, gint* position) { g_return_if_fail(FL_IS_ACCESSIBLE_TEXT_FIELD(editable_text)); FlAccessibleTextField* self = FL_ACCESSIBLE_TEXT_FIELD(editable_text); *position += gtk_entry_buffer_insert_text(self->buffer, *position, string, length); perform_set_text_action(self, gtk_entry_buffer_get_text(self->buffer)); perform_set_selection_action(self, *position, *position); } // Implements AtkEditableText::delete_text. static void fl_accessible_node_delete_text(AtkEditableText* editable_text, gint start_pos, gint end_pos) { g_return_if_fail(FL_IS_ACCESSIBLE_TEXT_FIELD(editable_text)); FlAccessibleTextField* self = FL_ACCESSIBLE_TEXT_FIELD(editable_text); gtk_entry_buffer_delete_text(self->buffer, start_pos, end_pos - start_pos); perform_set_text_action(self, gtk_entry_buffer_get_text(self->buffer)); perform_set_selection_action(self, start_pos, start_pos); } // Implement AtkEditableText::copy_text. static void fl_accessible_text_field_copy_text(AtkEditableText* editable_text, gint start_pos, gint end_pos) { g_return_if_fail(FL_IS_ACCESSIBLE_TEXT_FIELD(editable_text)); FlAccessibleTextField* self = FL_ACCESSIBLE_TEXT_FIELD(editable_text); perform_set_selection_action(self, start_pos, end_pos); fl_accessible_node_perform_action(FL_ACCESSIBLE_NODE(editable_text), kFlutterSemanticsActionCopy, nullptr); } // Implements AtkEditableText::cut_text. static void fl_accessible_text_field_cut_text(AtkEditableText* editable_text, gint start_pos, gint end_pos) { g_return_if_fail(FL_IS_ACCESSIBLE_TEXT_FIELD(editable_text)); FlAccessibleTextField* self = FL_ACCESSIBLE_TEXT_FIELD(editable_text); perform_set_selection_action(self, start_pos, end_pos); fl_accessible_node_perform_action(FL_ACCESSIBLE_NODE(editable_text), kFlutterSemanticsActionCut, nullptr); } // Implements AtkEditableText::paste_text. static void fl_accessible_text_field_paste_text(AtkEditableText* editable_text, gint position) { g_return_if_fail(FL_IS_ACCESSIBLE_TEXT_FIELD(editable_text)); FlAccessibleTextField* self = FL_ACCESSIBLE_TEXT_FIELD(editable_text); perform_set_selection_action(self, position, position); fl_accessible_node_perform_action(FL_ACCESSIBLE_NODE(editable_text), kFlutterSemanticsActionPaste, nullptr); } static void fl_accessible_text_field_class_init( FlAccessibleTextFieldClass* klass) { G_OBJECT_CLASS(klass)->dispose = fl_accessible_text_field_dispose; FL_ACCESSIBLE_NODE_CLASS(klass)->set_value = fl_accessible_text_field_set_value; FL_ACCESSIBLE_NODE_CLASS(klass)->set_text_selection = fl_accessible_text_field_set_text_selection; FL_ACCESSIBLE_NODE_CLASS(klass)->set_text_direction = fl_accessible_text_field_set_text_direction; FL_ACCESSIBLE_NODE_CLASS(klass)->perform_action = fl_accessible_text_field_perform_action; } static void fl_accessible_text_iface_init(AtkTextIface* iface) { iface->get_character_count = fl_accessible_text_field_get_character_count; iface->get_text = fl_accessible_text_field_get_text; iface->get_text_at_offset = fl_accessible_text_field_get_text_at_offset; iface->get_string_at_offset = fl_accessible_text_field_get_string_at_offset; iface->get_caret_offset = fl_accessible_text_field_get_caret_offset; iface->set_caret_offset = fl_accessible_text_field_set_caret_offset; iface->get_n_selections = fl_accessible_text_field_get_n_selections; iface->get_selection = fl_accessible_text_field_get_selection; iface->add_selection = fl_accessible_text_field_add_selection; iface->remove_selection = fl_accessible_text_field_remove_selection; iface->set_selection = fl_accessible_text_field_set_selection; } static void fl_accessible_editable_text_iface_init( AtkEditableTextIface* iface) { iface->set_text_contents = fl_accessible_text_field_set_text_contents; iface->insert_text = fl_accessible_text_field_insert_text; iface->delete_text = fl_accessible_node_delete_text; iface->copy_text = fl_accessible_text_field_copy_text; iface->cut_text = fl_accessible_text_field_cut_text; iface->paste_text = fl_accessible_text_field_paste_text; } static void fl_accessible_text_field_init(FlAccessibleTextField* self) { self->selection_base = -1; self->selection_extent = -1; self->buffer = gtk_entry_buffer_new("", 0); g_signal_connect_object( self->buffer, "inserted-text", G_CALLBACK(+[](FlAccessibleTextField* self, guint position, gchar* chars, guint n_chars) { g_signal_emit_by_name(self, "text-insert", position, n_chars, chars, nullptr); }), self, G_CONNECT_SWAPPED); g_signal_connect_object(self->buffer, "deleted-text", G_CALLBACK(+[](FlAccessibleTextField* self, guint position, guint n_chars) { g_autofree gchar* chars = atk_text_get_text( ATK_TEXT(self), position, position + n_chars); g_signal_emit_by_name(self, "text-remove", position, n_chars, chars, nullptr); }), self, G_CONNECT_SWAPPED); } FlAccessibleNode* fl_accessible_text_field_new(FlEngine* engine, int32_t id) { return FL_ACCESSIBLE_NODE(g_object_new(fl_accessible_text_field_get_type(), "engine", engine, "id", id, nullptr)); }
engine/shell/platform/linux/fl_accessible_text_field.cc/0
{ "file_path": "engine/shell/platform/linux/fl_accessible_text_field.cc", "repo_id": "engine", "token_count": 10998 }
367
// 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_SHELL_PLATFORM_LINUX_FL_ENGINE_PRIVATE_H_ #define FLUTTER_SHELL_PLATFORM_LINUX_FL_ENGINE_PRIVATE_H_ #include <glib-object.h> #include "flutter/shell/platform/embedder/embedder.h" #include "flutter/shell/platform/linux/fl_renderer.h" #include "flutter/shell/platform/linux/fl_task_runner.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_dart_project.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_engine.h" G_BEGIN_DECLS /** * FlEngineError: * Errors for #FlEngine objects to set on failures. */ typedef enum { // NOLINTBEGIN(readability-identifier-naming) FL_ENGINE_ERROR_FAILED, // NOLINTEND(readability-identifier-naming) } FlEngineError; GQuark fl_engine_error_quark(void) G_GNUC_CONST; /** * FlEnginePlatformMessageHandler: * @engine: an #FlEngine. * @channel: channel message received on. * @message: message content received from Dart. * @response_handle: a handle to respond to the message with. * @user_data: (closure): data provided when registering this handler. * * Function called when platform messages are received. * * Returns: %TRUE if message has been accepted. */ typedef gboolean (*FlEnginePlatformMessageHandler)( FlEngine* engine, const gchar* channel, GBytes* message, const FlutterPlatformMessageResponseHandle* response_handle, gpointer user_data); /** * FlEngineUpdateSemanticsHandler: * @engine: an #FlEngine. * @node: semantic node information. * @user_data: (closure): data provided when registering this handler. * * Function called when semantics node updates are received. */ typedef void (*FlEngineUpdateSemanticsHandler)( FlEngine* engine, const FlutterSemanticsUpdate2* update, gpointer user_data); /** * FlEngineOnPreEngineRestartHandler: * @engine: an #FlEngine. * @user_data: (closure): data provided when registering this handler. * * Function called right before the engine is restarted. */ typedef void (*FlEngineOnPreEngineRestartHandler)(FlEngine* engine, gpointer user_data); /** * fl_engine_new: * @project: an #FlDartProject. * @renderer: an #FlRenderer. * * Creates new Flutter engine. * * Returns: a new #FlEngine. */ FlEngine* fl_engine_new(FlDartProject* project, FlRenderer* renderer); /** * fl_engine_get_embedder_api: * @engine: an #FlEngine. * * Gets the embedder API proc table, allowing modificiations for unit testing. * * Returns: a mutable pointer to the embedder API proc table. */ FlutterEngineProcTable* fl_engine_get_embedder_api(FlEngine* engine); /** * fl_engine_set_platform_message_handler: * @engine: an #FlEngine. * @handler: function to call when a platform message is received. * @user_data: (closure): user data to pass to @handler. * @destroy_notify: (allow-none): a function which gets called to free * @user_data, or %NULL. * * Registers the function called when a platform message is received. Call * fl_engine_send_platform_message_response() with the response to this message. * Ownership of #FlutterPlatformMessageResponseHandle is * transferred to the caller, and the message must be responded to avoid * memory leaks. */ void fl_engine_set_platform_message_handler( FlEngine* engine, FlEnginePlatformMessageHandler handler, gpointer user_data, GDestroyNotify destroy_notify); /** * fl_engine_set_update_semantics_handler: * @engine: an #FlEngine. * @handler: function to call when a semantics update is received. * @user_data: (closure): user data to pass to @handler. * @destroy_notify: (allow-none): a function which gets called to free * @user_data, or %NULL. * * Registers the function called when a semantics update is received. */ void fl_engine_set_update_semantics_handler( FlEngine* engine, FlEngineUpdateSemanticsHandler handler, gpointer user_data, GDestroyNotify destroy_notify); /** * fl_engine_set_on_pre_engine_restart_handler: * @engine: an #FlEngine. * @handler: function to call when the engine is restarted. * @user_data: (closure): user data to pass to @handler. * @destroy_notify: (allow-none): a function which gets called to free * @user_data, or %NULL. * * Registers the function called right before the engine is restarted. */ void fl_engine_set_on_pre_engine_restart_handler( FlEngine* engine, FlEngineOnPreEngineRestartHandler handler, gpointer user_data, GDestroyNotify destroy_notify); /** * fl_engine_start: * @engine: an #FlEngine. * @error: (allow-none): #GError location to store the error occurring, or %NULL * to ignore. * * Starts the Flutter engine. * * Returns: %TRUE on success. */ gboolean fl_engine_start(FlEngine* engine, GError** error); /** * fl_engine_send_window_metrics_event: * @engine: an #FlEngine. * @width: width of the window in pixels. * @height: height of the window in pixels. * @pixel_ratio: scale factor for window. * * Sends a window metrics event to the engine. */ void fl_engine_send_window_metrics_event(FlEngine* engine, size_t width, size_t height, double pixel_ratio); /** * fl_engine_send_window_state_event: * @engine: an #FlEngine. * @visible: whether the window is currently visible or not. * @focused: whether the window is currently focused or not. * * Sends a window state event to the engine. */ void fl_engine_send_window_state_event(FlEngine* engine, gboolean visible, gboolean focused); /** * fl_engine_send_mouse_pointer_event: * @engine: an #FlEngine. * @phase: mouse phase. * @timestamp: time when event occurred in microseconds. * @x: x location of mouse cursor. * @y: y location of mouse cursor. * @scroll_delta_x: x offset of scroll. * @scroll_delta_y: y offset of scroll. * @buttons: buttons that are pressed. * * Sends a mouse pointer event to the engine. */ void fl_engine_send_mouse_pointer_event(FlEngine* engine, FlutterPointerPhase phase, size_t timestamp, double x, double y, double scroll_delta_x, double scroll_delta_y, int64_t buttons); void fl_engine_send_pointer_pan_zoom_event(FlEngine* self, size_t timestamp, double x, double y, FlutterPointerPhase phase, double pan_x, double pan_y, double scale, double rotation); /** * fl_engine_send_key_event: */ void fl_engine_send_key_event(FlEngine* engine, const FlutterKeyEvent* event, FlutterKeyEventCallback callback, void* user_data); /** * fl_engine_dispatch_semantics_action: * @engine: an #FlEngine. * @id: the semantics action identifier. * @action: the action being dispatched. * @data: (allow-none): data associated with the action. */ void fl_engine_dispatch_semantics_action(FlEngine* engine, uint64_t id, FlutterSemanticsAction action, GBytes* data); /** * fl_engine_send_platform_message_response: * @engine: an #FlEngine. * @handle: handle that was provided in #FlEnginePlatformMessageHandler. * @response: (allow-none): response to send or %NULL for an empty response. * @error: (allow-none): #GError location to store the error occurring, or %NULL * to ignore. * * Responds to a platform message. * * Returns: %TRUE on success. */ gboolean fl_engine_send_platform_message_response( FlEngine* engine, const FlutterPlatformMessageResponseHandle* handle, GBytes* response, GError** error); /** * fl_engine_send_platform_message: * @engine: an #FlEngine. * @channel: channel to send to. * @message: (allow-none): message buffer to send or %NULL for an empty message * @cancellable: (allow-none): a #GCancellable or %NULL. * @callback: (scope async): a #GAsyncReadyCallback to call when the request is * satisfied. * @user_data: (closure): user data to pass to @callback. * * Asynchronously sends a platform message. */ void fl_engine_send_platform_message(FlEngine* engine, const gchar* channel, GBytes* message, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data); /** * fl_engine_send_platform_message_finish: * @engine: an #FlEngine. * @result: a #GAsyncResult. * @error: (allow-none): #GError location to store the error occurring, or %NULL * to ignore. * * Completes request started with fl_engine_send_platform_message(). * * Returns: message response on success or %NULL on error. */ GBytes* fl_engine_send_platform_message_finish(FlEngine* engine, GAsyncResult* result, GError** error); /** * fl_engine_get_task_runner: * @engine: an #FlEngine. * @result: a #FlTaskRunner. * * Returns: task runner responsible for scheduling Flutter tasks. */ FlTaskRunner* fl_engine_get_task_runner(FlEngine* engine); /** * fl_engine_execute_task: * @engine: an #FlEngine. * @task: a #FlutterTask to execute. * * Executes given Flutter task. */ void fl_engine_execute_task(FlEngine* engine, FlutterTask* task); /** * fl_engine_mark_texture_frame_available: * @engine: an #FlEngine. * @texture_id: the identifier of the texture whose frame has been updated. * * Tells the Flutter engine that a new texture frame is available for the given * texture. * * Returns: %TRUE on success. */ gboolean fl_engine_mark_texture_frame_available(FlEngine* engine, int64_t texture_id); /** * fl_engine_register_external_texture: * @engine: an #FlEngine. * @texture_id: the identifier of the texture that is available. * * Tells the Flutter engine that a new external texture is available. * * Returns: %TRUE on success. */ gboolean fl_engine_register_external_texture(FlEngine* engine, int64_t texture_id); /** * fl_engine_unregister_external_texture: * @engine: an #FlEngine. * @texture_id: the identifier of the texture that is not available anymore. * * Tells the Flutter engine that an existing external texture is not available * anymore. * * Returns: %TRUE on success. */ gboolean fl_engine_unregister_external_texture(FlEngine* engine, int64_t texture_id); /** * fl_engine_update_accessibility_features: * @engine: an #FlEngine. * @flags: the features to enable in the accessibility tree. * * Tells the Flutter engine to update the flags on the accessibility tree. */ void fl_engine_update_accessibility_features(FlEngine* engine, int32_t flags); /** * fl_engine_get_switches: * @project: an #FlEngine. * * Determines the switches that should be passed to the Flutter engine. * * Returns: an array of switches to pass to the Flutter engine. */ GPtrArray* fl_engine_get_switches(FlEngine* engine); G_END_DECLS #endif // FLUTTER_SHELL_PLATFORM_LINUX_FL_ENGINE_PRIVATE_H_
engine/shell/platform/linux/fl_engine_private.h/0
{ "file_path": "engine/shell/platform/linux/fl_engine_private.h", "repo_id": "engine", "token_count": 4843 }
368
// 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_SHELL_PLATFORM_LINUX_FL_KEY_EMBEDDER_RESPONDER_PRIVATE_H_ #define FLUTTER_SHELL_PLATFORM_LINUX_FL_KEY_EMBEDDER_RESPONDER_PRIVATE_H_ #include <gdk/gdk.h> #include "flutter/shell/platform/linux/fl_key_responder.h" #include "flutter/shell/platform/linux/fl_keyboard_manager.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_binary_messenger.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_value.h" /** * FlKeyEmbedderCheckedKey: * * The information for a key that #FlKeyEmbedderResponder should keep state * synchronous on. For every record of #FlKeyEmbedderCheckedKey, the responder * will check the #GdkEvent::state and the internal state, and synchronize * events if they don't match. * * #FlKeyEmbedderCheckedKey can synchronize pressing states (such as * whether ControlLeft is pressed) or lock states (such as whether CapsLock * is enabled). * * #FlKeyEmbedderCheckedKey has a "primary key". For pressing states, the * primary key is the left of the modifiers. For lock states, the primary * key is the key. * * #FlKeyEmbedderCheckedKey may also have a "secondary key". It is only * available to pressing states, which is the right of the modifiers. */ typedef struct { // The physical key for the primary key. uint64_t primary_physical_key; // The logical key for the primary key. uint64_t primary_logical_key; // The logical key for the secondary key. uint64_t secondary_logical_key; // Whether this key is CapsLock. CapsLock uses a different event model in GDK // and needs special treatment. bool is_caps_lock; } FlKeyEmbedderCheckedKey; #endif // FLUTTER_SHELL_PLATFORM_LINUX_FL_KEY_EMBEDDER_RESPONDER_PRIVATE_H_
engine/shell/platform/linux/fl_key_embedder_responder_private.h/0
{ "file_path": "engine/shell/platform/linux/fl_key_embedder_responder_private.h", "repo_id": "engine", "token_count": 615 }
369
// 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_SHELL_PLATFORM_LINUX_FL_METHOD_CHANNEL_PRIVATE_H_ #define FLUTTER_SHELL_PLATFORM_LINUX_FL_METHOD_CHANNEL_PRIVATE_H_ #include "flutter/shell/platform/linux/public/flutter_linux/fl_method_channel.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_binary_messenger.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_method_response.h" G_BEGIN_DECLS /** * fl_method_channel_respond: * @channel: an #FlMethodChannel. * @response_handle: an #FlBinaryMessengerResponseHandle. * @response: an #FlMethodResponse. * @error: (allow-none): #GError location to store the error occurring, or %NULL * to ignore. * * Responds to a method call. * * Returns: %TRUE on success. */ gboolean fl_method_channel_respond( FlMethodChannel* channel, FlBinaryMessengerResponseHandle* response_handle, FlMethodResponse* response, GError** error); G_END_DECLS #endif // FLUTTER_SHELL_PLATFORM_LINUX_FL_METHOD_CHANNEL_PRIVATE_H_
engine/shell/platform/linux/fl_method_channel_private.h/0
{ "file_path": "engine/shell/platform/linux/fl_method_channel_private.h", "repo_id": "engine", "token_count": 407 }
370
// 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_SHELL_PLATFORM_LINUX_FL_PLUGIN_REGISTRAR_PRIVATE_H_ #define FLUTTER_SHELL_PLATFORM_LINUX_FL_PLUGIN_REGISTRAR_PRIVATE_H_ #include "flutter/shell/platform/linux/public/flutter_linux/fl_binary_messenger.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_plugin_registrar.h" G_BEGIN_DECLS /** * fl_plugin_registrar_new: * @view: (allow-none): the #FlView that is being plugged into or %NULL for * headless mode. * @messenger: the #FlBinaryMessenger to communicate with. * @texture_registrar: the #FlTextureRegistrar to communicate with. * * Creates a new #FlPluginRegistrar. * * Returns: a new #FlPluginRegistrar. */ FlPluginRegistrar* fl_plugin_registrar_new( FlView* view, FlBinaryMessenger* messenger, FlTextureRegistrar* texture_registrar); G_END_DECLS #endif // FLUTTER_SHELL_PLATFORM_LINUX_FL_PLUGIN_REGISTRAR_PRIVATE_H_
engine/shell/platform/linux/fl_plugin_registrar_private.h/0
{ "file_path": "engine/shell/platform/linux/fl_plugin_registrar_private.h", "repo_id": "engine", "token_count": 393 }
371
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/linux/fl_settings_plugin.h" #include <gmodule.h> #include "flutter/shell/platform/embedder/embedder.h" #include "flutter/shell/platform/linux/fl_engine_private.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_basic_message_channel.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_binary_messenger.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_json_message_codec.h" static constexpr char kChannelName[] = "flutter/settings"; static constexpr char kTextScaleFactorKey[] = "textScaleFactor"; static constexpr char kAlwaysUse24HourFormatKey[] = "alwaysUse24HourFormat"; static constexpr char kPlatformBrightnessKey[] = "platformBrightness"; static constexpr char kPlatformBrightnessLight[] = "light"; static constexpr char kPlatformBrightnessDark[] = "dark"; struct _FlSettingsPlugin { GObject parent_instance; FlBasicMessageChannel* channel; FlEngine* engine; FlSettings* settings; }; G_DEFINE_TYPE(FlSettingsPlugin, fl_settings_plugin, G_TYPE_OBJECT) static const gchar* to_platform_brightness(FlColorScheme color_scheme) { switch (color_scheme) { case FL_COLOR_SCHEME_LIGHT: return kPlatformBrightnessLight; case FL_COLOR_SCHEME_DARK: return kPlatformBrightnessDark; default: g_return_val_if_reached(nullptr); } } // Sends the current settings to the Flutter engine. static void update_settings(FlSettingsPlugin* self) { FlClockFormat clock_format = fl_settings_get_clock_format(self->settings); FlColorScheme color_scheme = fl_settings_get_color_scheme(self->settings); gdouble scaling_factor = fl_settings_get_text_scaling_factor(self->settings); g_autoptr(FlValue) message = fl_value_new_map(); fl_value_set_string_take(message, kTextScaleFactorKey, fl_value_new_float(scaling_factor)); fl_value_set_string_take( message, kAlwaysUse24HourFormatKey, fl_value_new_bool(clock_format == FL_CLOCK_FORMAT_24H)); fl_value_set_string_take( message, kPlatformBrightnessKey, fl_value_new_string(to_platform_brightness(color_scheme))); fl_basic_message_channel_send(self->channel, message, nullptr, nullptr, nullptr); if (self->engine != nullptr) { int32_t flags = 0; if (!fl_settings_get_enable_animations(self->settings)) { flags |= kFlutterAccessibilityFeatureDisableAnimations; } if (fl_settings_get_high_contrast(self->settings)) { flags |= kFlutterAccessibilityFeatureHighContrast; } fl_engine_update_accessibility_features(self->engine, flags); } } static void fl_settings_plugin_dispose(GObject* object) { FlSettingsPlugin* self = FL_SETTINGS_PLUGIN(object); g_clear_object(&self->channel); g_clear_object(&self->settings); if (self->engine != nullptr) { g_object_remove_weak_pointer(G_OBJECT(self), reinterpret_cast<gpointer*>(&(self->engine))); self->engine = nullptr; } G_OBJECT_CLASS(fl_settings_plugin_parent_class)->dispose(object); } static void fl_settings_plugin_class_init(FlSettingsPluginClass* klass) { G_OBJECT_CLASS(klass)->dispose = fl_settings_plugin_dispose; } static void fl_settings_plugin_init(FlSettingsPlugin* self) {} FlSettingsPlugin* fl_settings_plugin_new(FlEngine* engine) { g_return_val_if_fail(FL_IS_ENGINE(engine), nullptr); FlSettingsPlugin* self = FL_SETTINGS_PLUGIN(g_object_new(fl_settings_plugin_get_type(), nullptr)); self->engine = engine; g_object_add_weak_pointer(G_OBJECT(self), reinterpret_cast<gpointer*>(&(self->engine))); FlBinaryMessenger* messenger = fl_engine_get_binary_messenger(engine); g_autoptr(FlJsonMessageCodec) codec = fl_json_message_codec_new(); self->channel = fl_basic_message_channel_new(messenger, kChannelName, FL_MESSAGE_CODEC(codec)); return self; } void fl_settings_plugin_start(FlSettingsPlugin* self, FlSettings* settings) { g_return_if_fail(FL_IS_SETTINGS_PLUGIN(self)); g_return_if_fail(FL_IS_SETTINGS(settings)); self->settings = FL_SETTINGS(g_object_ref(settings)); g_signal_connect_object(settings, "changed", G_CALLBACK(update_settings), self, G_CONNECT_SWAPPED); update_settings(self); }
engine/shell/platform/linux/fl_settings_plugin.cc/0
{ "file_path": "engine/shell/platform/linux/fl_settings_plugin.cc", "repo_id": "engine", "token_count": 1707 }
372
// 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 <utility> #include "flutter/shell/platform/linux/fl_method_codec_private.h" #include "flutter/shell/platform/linux/fl_text_input_plugin.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_binary_messenger.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_json_method_codec.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_value.h" #include "flutter/shell/platform/linux/testing/fl_test.h" #include "flutter/shell/platform/linux/testing/mock_binary_messenger.h" #include "flutter/shell/platform/linux/testing/mock_binary_messenger_response_handle.h" #include "flutter/shell/platform/linux/testing/mock_im_context.h" #include "flutter/shell/platform/linux/testing/mock_text_input_view_delegate.h" #include "flutter/testing/testing.h" #include "gmock/gmock.h" #include "gtest/gtest.h" void printTo(FlMethodResponse* response, ::std::ostream* os) { *os << ::testing::PrintToString( fl_method_response_get_result(response, nullptr)); } MATCHER_P(SuccessResponse, result, "") { g_autoptr(FlJsonMethodCodec) codec = fl_json_method_codec_new(); g_autoptr(FlMethodResponse) response = fl_method_codec_decode_response(FL_METHOD_CODEC(codec), arg, nullptr); if (fl_value_equal(fl_method_response_get_result(response, nullptr), result)) { return true; } *result_listener << ::testing::PrintToString(response); return false; } MATCHER_P(FlValueEq, value, "equal to " + ::testing::PrintToString(value)) { return fl_value_equal(arg, value); } class MethodCallMatcher { public: using is_gtest_matcher = void; explicit MethodCallMatcher(::testing::Matcher<std::string> name, ::testing::Matcher<FlValue*> args) : name_(std::move(name)), args_(std::move(args)) {} bool MatchAndExplain(GBytes* method_call, ::testing::MatchResultListener* result_listener) const { g_autoptr(FlJsonMethodCodec) codec = fl_json_method_codec_new(); g_autoptr(GError) error = nullptr; g_autofree gchar* name = nullptr; g_autoptr(FlValue) args = nullptr; gboolean result = fl_method_codec_decode_method_call( FL_METHOD_CODEC(codec), method_call, &name, &args, &error); if (!result) { *result_listener << ::testing::PrintToString(error->message); return false; } if (!name_.MatchAndExplain(name, result_listener)) { *result_listener << " where the name doesn't match: \"" << name << "\""; return false; } if (!args_.MatchAndExplain(args, result_listener)) { *result_listener << " where the args don't match: " << ::testing::PrintToString(args); return false; } return true; } void DescribeTo(std::ostream* os) const { *os << "method name "; name_.DescribeTo(os); *os << " and args "; args_.DescribeTo(os); } void DescribeNegationTo(std::ostream* os) const { *os << "method name "; name_.DescribeNegationTo(os); *os << " or args "; args_.DescribeNegationTo(os); } private: ::testing::Matcher<std::string> name_; ::testing::Matcher<FlValue*> args_; }; ::testing::Matcher<GBytes*> MethodCall(const std::string& name, ::testing::Matcher<FlValue*> args) { return MethodCallMatcher(::testing::StrEq(name), std::move(args)); } static FlValue* build_map(std::map<const gchar*, FlValue*> args) { FlValue* value = fl_value_new_map(); for (auto it = args.begin(); it != args.end(); ++it) { fl_value_set_string_take(value, it->first, it->second); } return value; } static FlValue* build_list(std::vector<FlValue*> args) { FlValue* value = fl_value_new_list(); for (auto it = args.begin(); it != args.end(); ++it) { fl_value_append_take(value, *it); } return value; } struct InputConfig { int64_t client_id = -1; const gchar* input_type = "TextInputType.text"; const gchar* input_action = "TextInputAction.none"; gboolean enable_delta_model = false; }; static FlValue* build_input_config(InputConfig config) { return build_list({ fl_value_new_int(config.client_id), build_map({ {"inputAction", fl_value_new_string(config.input_action)}, {"inputType", build_map({ {"name", fl_value_new_string(config.input_type)}, })}, {"enableDeltaModel", fl_value_new_bool(config.enable_delta_model)}, }), }); } struct EditingState { const gchar* text = ""; int selection_base = -1; int selection_extent = -1; int composing_base = -1; int composing_extent = -1; }; static FlValue* build_editing_state(EditingState state) { return build_map({ {"text", fl_value_new_string(state.text)}, {"selectionBase", fl_value_new_int(state.selection_base)}, {"selectionExtent", fl_value_new_int(state.selection_extent)}, {"selectionAffinity", fl_value_new_string("TextAffinity.downstream")}, {"selectionIsDirectional", fl_value_new_bool(false)}, {"composingBase", fl_value_new_int(state.composing_base)}, {"composingExtent", fl_value_new_int(state.composing_extent)}, }); } struct EditingDelta { const gchar* old_text = ""; const gchar* delta_text = ""; int delta_start = -1; int delta_end = -1; int selection_base = -1; int selection_extent = -1; int composing_base = -1; int composing_extent = -1; }; static FlValue* build_editing_delta(EditingDelta delta) { return build_map({ {"oldText", fl_value_new_string(delta.old_text)}, {"deltaText", fl_value_new_string(delta.delta_text)}, {"deltaStart", fl_value_new_int(delta.delta_start)}, {"deltaEnd", fl_value_new_int(delta.delta_end)}, {"selectionBase", fl_value_new_int(delta.selection_base)}, {"selectionExtent", fl_value_new_int(delta.selection_extent)}, {"selectionAffinity", fl_value_new_string("TextAffinity.downstream")}, {"selectionIsDirectional", fl_value_new_bool(false)}, {"composingBase", fl_value_new_int(delta.composing_base)}, {"composingExtent", fl_value_new_int(delta.composing_extent)}, }); } static void send_key_event(FlTextInputPlugin* plugin, gint keyval, gint state = 0) { GdkEvent* gdk_event = gdk_event_new(GDK_KEY_PRESS); gdk_event->key.keyval = keyval; gdk_event->key.state = state; FlKeyEvent* key_event = fl_key_event_new_from_gdk_event(gdk_event); fl_text_input_plugin_filter_keypress(plugin, key_event); fl_key_event_dispose(key_event); } TEST(FlTextInputPluginTest, MessageHandler) { ::testing::NiceMock<flutter::testing::MockBinaryMessenger> messenger; ::testing::NiceMock<flutter::testing::MockIMContext> context; ::testing::NiceMock<flutter::testing::MockTextInputViewDelegate> delegate; g_autoptr(FlTextInputPlugin) plugin = fl_text_input_plugin_new(messenger, context, delegate); EXPECT_NE(plugin, nullptr); EXPECT_TRUE(messenger.HasMessageHandler("flutter/textinput")); } TEST(FlTextInputPluginTest, SetClient) { ::testing::NiceMock<flutter::testing::MockBinaryMessenger> messenger; ::testing::NiceMock<flutter::testing::MockIMContext> context; ::testing::NiceMock<flutter::testing::MockTextInputViewDelegate> delegate; g_autoptr(FlTextInputPlugin) plugin = fl_text_input_plugin_new(messenger, context, delegate); EXPECT_NE(plugin, nullptr); g_autoptr(FlValue) args = build_input_config({.client_id = 1}); g_autoptr(FlJsonMethodCodec) codec = fl_json_method_codec_new(); g_autoptr(GBytes) message = fl_method_codec_encode_method_call( FL_METHOD_CODEC(codec), "TextInput.setClient", args, nullptr); g_autoptr(FlValue) null = fl_value_new_null(); EXPECT_CALL(messenger, fl_binary_messenger_send_response( ::testing::Eq<FlBinaryMessenger*>(messenger), ::testing::_, SuccessResponse(null), ::testing::_)) .WillOnce(::testing::Return(true)); messenger.ReceiveMessage("flutter/textinput", message); } TEST(FlTextInputPluginTest, Show) { ::testing::NiceMock<flutter::testing::MockBinaryMessenger> messenger; ::testing::NiceMock<flutter::testing::MockIMContext> context; ::testing::NiceMock<flutter::testing::MockTextInputViewDelegate> delegate; g_autoptr(FlTextInputPlugin) plugin = fl_text_input_plugin_new(messenger, context, delegate); EXPECT_NE(plugin, nullptr); EXPECT_CALL(context, gtk_im_context_focus_in(::testing::Eq<GtkIMContext*>(context))); g_autoptr(FlValue) null = fl_value_new_null(); EXPECT_CALL(messenger, fl_binary_messenger_send_response( ::testing::Eq<FlBinaryMessenger*>(messenger), ::testing::_, SuccessResponse(null), ::testing::_)) .WillOnce(::testing::Return(true)); g_autoptr(FlJsonMethodCodec) codec = fl_json_method_codec_new(); g_autoptr(GBytes) message = fl_method_codec_encode_method_call( FL_METHOD_CODEC(codec), "TextInput.show", nullptr, nullptr); messenger.ReceiveMessage("flutter/textinput", message); } TEST(FlTextInputPluginTest, Hide) { ::testing::NiceMock<flutter::testing::MockBinaryMessenger> messenger; ::testing::NiceMock<flutter::testing::MockIMContext> context; ::testing::NiceMock<flutter::testing::MockTextInputViewDelegate> delegate; g_autoptr(FlTextInputPlugin) plugin = fl_text_input_plugin_new(messenger, context, delegate); EXPECT_NE(plugin, nullptr); EXPECT_CALL(context, gtk_im_context_focus_out(::testing::Eq<GtkIMContext*>(context))); g_autoptr(FlValue) null = fl_value_new_null(); EXPECT_CALL(messenger, fl_binary_messenger_send_response( ::testing::Eq<FlBinaryMessenger*>(messenger), ::testing::_, SuccessResponse(null), ::testing::_)) .WillOnce(::testing::Return(true)); g_autoptr(FlJsonMethodCodec) codec = fl_json_method_codec_new(); g_autoptr(GBytes) message = fl_method_codec_encode_method_call( FL_METHOD_CODEC(codec), "TextInput.hide", nullptr, nullptr); messenger.ReceiveMessage("flutter/textinput", message); } TEST(FlTextInputPluginTest, ClearClient) { ::testing::NiceMock<flutter::testing::MockBinaryMessenger> messenger; ::testing::NiceMock<flutter::testing::MockIMContext> context; ::testing::NiceMock<flutter::testing::MockTextInputViewDelegate> delegate; g_autoptr(FlTextInputPlugin) plugin = fl_text_input_plugin_new(messenger, context, delegate); EXPECT_NE(plugin, nullptr); g_autoptr(FlValue) null = fl_value_new_null(); EXPECT_CALL(messenger, fl_binary_messenger_send_response( ::testing::Eq<FlBinaryMessenger*>(messenger), ::testing::_, SuccessResponse(null), ::testing::_)) .WillOnce(::testing::Return(true)); g_autoptr(FlJsonMethodCodec) codec = fl_json_method_codec_new(); g_autoptr(GBytes) message = fl_method_codec_encode_method_call( FL_METHOD_CODEC(codec), "TextInput.clearClient", nullptr, nullptr); messenger.ReceiveMessage("flutter/textinput", message); } TEST(FlTextInputPluginTest, PerformAction) { ::testing::NiceMock<flutter::testing::MockBinaryMessenger> messenger; ::testing::NiceMock<flutter::testing::MockIMContext> context; ::testing::NiceMock<flutter::testing::MockTextInputViewDelegate> delegate; g_autoptr(FlTextInputPlugin) plugin = fl_text_input_plugin_new(messenger, context, delegate); EXPECT_NE(plugin, nullptr); // set input config g_autoptr(FlValue) config = build_input_config({ .client_id = 1, .input_type = "TextInputType.multiline", .input_action = "TextInputAction.newline", }); g_autoptr(FlJsonMethodCodec) codec = fl_json_method_codec_new(); g_autoptr(GBytes) set_client = fl_method_codec_encode_method_call( FL_METHOD_CODEC(codec), "TextInput.setClient", config, nullptr); g_autoptr(FlValue) null = fl_value_new_null(); EXPECT_CALL(messenger, fl_binary_messenger_send_response( ::testing::Eq<FlBinaryMessenger*>(messenger), ::testing::_, SuccessResponse(null), ::testing::_)) .WillOnce(::testing::Return(true)); messenger.ReceiveMessage("flutter/textinput", set_client); // set editing state g_autoptr(FlValue) state = build_editing_state({ .text = "Flutter", .selection_base = 7, .selection_extent = 7, }); g_autoptr(GBytes) set_state = fl_method_codec_encode_method_call( FL_METHOD_CODEC(codec), "TextInput.setEditingState", state, nullptr); EXPECT_CALL(messenger, fl_binary_messenger_send_response( ::testing::Eq<FlBinaryMessenger*>(messenger), ::testing::_, SuccessResponse(null), ::testing::_)) .WillOnce(::testing::Return(true)); messenger.ReceiveMessage("flutter/textinput", set_state); // update editing state g_autoptr(FlValue) new_state = build_list({ fl_value_new_int(1), // client_id build_editing_state({ .text = "Flutter\n", .selection_base = 8, .selection_extent = 8, }), }); EXPECT_CALL(messenger, fl_binary_messenger_send_on_channel( ::testing::Eq<FlBinaryMessenger*>(messenger), ::testing::StrEq("flutter/textinput"), MethodCall("TextInputClient.updateEditingState", FlValueEq(new_state)), ::testing::_, ::testing::_, ::testing::_)); // perform action g_autoptr(FlValue) action = build_list({ fl_value_new_int(1), // client_id fl_value_new_string("TextInputAction.newline"), }); EXPECT_CALL(messenger, fl_binary_messenger_send_on_channel( ::testing::Eq<FlBinaryMessenger*>(messenger), ::testing::StrEq("flutter/textinput"), MethodCall("TextInputClient.performAction", FlValueEq(action)), ::testing::_, ::testing::_, ::testing::_)); send_key_event(plugin, GDK_KEY_Return); } // Regression test for https://github.com/flutter/flutter/issues/125879. TEST(FlTextInputPluginTest, MultilineWithSendAction) { ::testing::NiceMock<flutter::testing::MockBinaryMessenger> messenger; ::testing::NiceMock<flutter::testing::MockIMContext> context; ::testing::NiceMock<flutter::testing::MockTextInputViewDelegate> delegate; g_autoptr(FlTextInputPlugin) plugin = fl_text_input_plugin_new(messenger, context, delegate); EXPECT_NE(plugin, nullptr); // Set input config. g_autoptr(FlValue) config = build_input_config({ .client_id = 1, .input_type = "TextInputType.multiline", .input_action = "TextInputAction.send", }); g_autoptr(FlJsonMethodCodec) codec = fl_json_method_codec_new(); g_autoptr(GBytes) set_client = fl_method_codec_encode_method_call( FL_METHOD_CODEC(codec), "TextInput.setClient", config, nullptr); g_autoptr(FlValue) null = fl_value_new_null(); EXPECT_CALL(messenger, fl_binary_messenger_send_response( ::testing::Eq<FlBinaryMessenger*>(messenger), ::testing::_, SuccessResponse(null), ::testing::_)) .WillOnce(::testing::Return(true)); messenger.ReceiveMessage("flutter/textinput", set_client); // Set editing state. g_autoptr(FlValue) state = build_editing_state({ .text = "Flutter", .selection_base = 7, .selection_extent = 7, }); g_autoptr(GBytes) set_state = fl_method_codec_encode_method_call( FL_METHOD_CODEC(codec), "TextInput.setEditingState", state, nullptr); EXPECT_CALL(messenger, fl_binary_messenger_send_response( ::testing::Eq<FlBinaryMessenger*>(messenger), ::testing::_, SuccessResponse(null), ::testing::_)) .WillOnce(::testing::Return(true)); messenger.ReceiveMessage("flutter/textinput", set_state); // Perform action. g_autoptr(FlValue) action = build_list({ fl_value_new_int(1), // client_id fl_value_new_string("TextInputAction.send"), }); // Because the input action is not set to TextInputAction.newline, the next // expected call is "TextInputClient.performAction". If the input action was // set to TextInputAction.newline the next call would be // "TextInputClient.updateEditingState" (this case is tested in the test named // 'PerformAction'). EXPECT_CALL(messenger, fl_binary_messenger_send_on_channel( ::testing::Eq<FlBinaryMessenger*>(messenger), ::testing::StrEq("flutter/textinput"), MethodCall("TextInputClient.performAction", FlValueEq(action)), ::testing::_, ::testing::_, ::testing::_)); send_key_event(plugin, GDK_KEY_Return); } TEST(FlTextInputPluginTest, MoveCursor) { ::testing::NiceMock<flutter::testing::MockBinaryMessenger> messenger; ::testing::NiceMock<flutter::testing::MockIMContext> context; ::testing::NiceMock<flutter::testing::MockTextInputViewDelegate> delegate; g_autoptr(FlTextInputPlugin) plugin = fl_text_input_plugin_new(messenger, context, delegate); EXPECT_NE(plugin, nullptr); // set input config g_autoptr(FlValue) config = build_input_config({.client_id = 1}); g_autoptr(FlJsonMethodCodec) codec = fl_json_method_codec_new(); g_autoptr(GBytes) set_client = fl_method_codec_encode_method_call( FL_METHOD_CODEC(codec), "TextInput.setClient", config, nullptr); g_autoptr(FlValue) null = fl_value_new_null(); EXPECT_CALL(messenger, fl_binary_messenger_send_response( ::testing::Eq<FlBinaryMessenger*>(messenger), ::testing::_, SuccessResponse(null), ::testing::_)) .WillOnce(::testing::Return(true)); messenger.ReceiveMessage("flutter/textinput", set_client); // set editing state g_autoptr(FlValue) state = build_editing_state({ .text = "Flutter", .selection_base = 4, .selection_extent = 4, }); g_autoptr(GBytes) set_state = fl_method_codec_encode_method_call( FL_METHOD_CODEC(codec), "TextInput.setEditingState", state, nullptr); EXPECT_CALL(messenger, fl_binary_messenger_send_response( ::testing::Eq<FlBinaryMessenger*>(messenger), ::testing::_, SuccessResponse(null), ::testing::_)) .WillOnce(::testing::Return(true)); messenger.ReceiveMessage("flutter/textinput", set_state); // move cursor to beginning g_autoptr(FlValue) beginning = build_list({ fl_value_new_int(1), // client_id build_editing_state({ .text = "Flutter", .selection_base = 0, .selection_extent = 0, }), }); EXPECT_CALL(messenger, fl_binary_messenger_send_on_channel( ::testing::Eq<FlBinaryMessenger*>(messenger), ::testing::StrEq("flutter/textinput"), MethodCall("TextInputClient.updateEditingState", FlValueEq(beginning)), ::testing::_, ::testing::_, ::testing::_)); send_key_event(plugin, GDK_KEY_Home); // move cursor to end g_autoptr(FlValue) end = build_list({ fl_value_new_int(1), // client_id build_editing_state({ .text = "Flutter", .selection_base = 7, .selection_extent = 7, }), }); EXPECT_CALL(messenger, fl_binary_messenger_send_on_channel( ::testing::Eq<FlBinaryMessenger*>(messenger), ::testing::StrEq("flutter/textinput"), MethodCall("TextInputClient.updateEditingState", FlValueEq(end)), ::testing::_, ::testing::_, ::testing::_)); send_key_event(plugin, GDK_KEY_End); } TEST(FlTextInputPluginTest, Select) { ::testing::NiceMock<flutter::testing::MockBinaryMessenger> messenger; ::testing::NiceMock<flutter::testing::MockIMContext> context; ::testing::NiceMock<flutter::testing::MockTextInputViewDelegate> delegate; g_autoptr(FlTextInputPlugin) plugin = fl_text_input_plugin_new(messenger, context, delegate); EXPECT_NE(plugin, nullptr); // set input config g_autoptr(FlValue) config = build_input_config({.client_id = 1}); g_autoptr(FlJsonMethodCodec) codec = fl_json_method_codec_new(); g_autoptr(GBytes) set_client = fl_method_codec_encode_method_call( FL_METHOD_CODEC(codec), "TextInput.setClient", config, nullptr); g_autoptr(FlValue) null = fl_value_new_null(); EXPECT_CALL(messenger, fl_binary_messenger_send_response( ::testing::Eq<FlBinaryMessenger*>(messenger), ::testing::_, SuccessResponse(null), ::testing::_)) .WillOnce(::testing::Return(true)); messenger.ReceiveMessage("flutter/textinput", set_client); // set editing state g_autoptr(FlValue) state = build_editing_state({ .text = "Flutter", .selection_base = 4, .selection_extent = 4, }); g_autoptr(GBytes) set_state = fl_method_codec_encode_method_call( FL_METHOD_CODEC(codec), "TextInput.setEditingState", state, nullptr); EXPECT_CALL(messenger, fl_binary_messenger_send_response( ::testing::Eq<FlBinaryMessenger*>(messenger), ::testing::_, SuccessResponse(null), ::testing::_)) .WillOnce(::testing::Return(true)); messenger.ReceiveMessage("flutter/textinput", set_state); // select to end g_autoptr(FlValue) select_to_end = build_list({ fl_value_new_int(1), // client_id build_editing_state({ .text = "Flutter", .selection_base = 4, .selection_extent = 7, }), }); EXPECT_CALL(messenger, fl_binary_messenger_send_on_channel( ::testing::Eq<FlBinaryMessenger*>(messenger), ::testing::StrEq("flutter/textinput"), MethodCall("TextInputClient.updateEditingState", FlValueEq(select_to_end)), ::testing::_, ::testing::_, ::testing::_)); send_key_event(plugin, GDK_KEY_End, GDK_SHIFT_MASK); // select to beginning g_autoptr(FlValue) select_to_beginning = build_list({ fl_value_new_int(1), // client_id build_editing_state({ .text = "Flutter", .selection_base = 4, .selection_extent = 0, }), }); EXPECT_CALL(messenger, fl_binary_messenger_send_on_channel( ::testing::Eq<FlBinaryMessenger*>(messenger), ::testing::StrEq("flutter/textinput"), MethodCall("TextInputClient.updateEditingState", FlValueEq(select_to_beginning)), ::testing::_, ::testing::_, ::testing::_)); send_key_event(plugin, GDK_KEY_Home, GDK_SHIFT_MASK); } TEST(FlTextInputPluginTest, Composing) { ::testing::NiceMock<flutter::testing::MockBinaryMessenger> messenger; ::testing::NiceMock<flutter::testing::MockIMContext> context; ::testing::NiceMock<flutter::testing::MockTextInputViewDelegate> delegate; g_autoptr(FlTextInputPlugin) plugin = fl_text_input_plugin_new(messenger, context, delegate); EXPECT_NE(plugin, nullptr); g_signal_emit_by_name(context, "preedit-start", nullptr); // update EXPECT_CALL(context, gtk_im_context_get_preedit_string( ::testing::Eq<GtkIMContext*>(context), ::testing::A<gchar**>(), ::testing::_, ::testing::A<gint*>())) .WillOnce( ::testing::DoAll(::testing::SetArgPointee<1>(g_strdup("Flutter")), ::testing::SetArgPointee<3>(0))); g_autoptr(FlValue) state = build_list({ fl_value_new_int(-1), // client_id build_editing_state({ .text = "Flutter", .selection_base = 0, .selection_extent = 0, .composing_base = 0, .composing_extent = 7, }), }); EXPECT_CALL(messenger, fl_binary_messenger_send_on_channel( ::testing::Eq<FlBinaryMessenger*>(messenger), ::testing::StrEq("flutter/textinput"), MethodCall("TextInputClient.updateEditingState", FlValueEq(state)), ::testing::_, ::testing::_, ::testing::_)); g_signal_emit_by_name(context, "preedit-changed", nullptr); // commit g_autoptr(FlValue) commit = build_list({ fl_value_new_int(-1), // client_id build_editing_state({ .text = "engine", .selection_base = 6, .selection_extent = 6, }), }); EXPECT_CALL(messenger, fl_binary_messenger_send_on_channel( ::testing::Eq<FlBinaryMessenger*>(messenger), ::testing::StrEq("flutter/textinput"), MethodCall("TextInputClient.updateEditingState", FlValueEq(commit)), ::testing::_, ::testing::_, ::testing::_)); g_signal_emit_by_name(context, "commit", "engine", nullptr); // end EXPECT_CALL(messenger, fl_binary_messenger_send_on_channel( ::testing::Eq<FlBinaryMessenger*>(messenger), ::testing::StrEq("flutter/textinput"), MethodCall("TextInputClient.updateEditingState", ::testing::_), ::testing::_, ::testing::_, ::testing::_)); g_signal_emit_by_name(context, "preedit-end", nullptr); } TEST(FlTextInputPluginTest, SurroundingText) { ::testing::NiceMock<flutter::testing::MockBinaryMessenger> messenger; ::testing::NiceMock<flutter::testing::MockIMContext> context; ::testing::NiceMock<flutter::testing::MockTextInputViewDelegate> delegate; g_autoptr(FlTextInputPlugin) plugin = fl_text_input_plugin_new(messenger, context, delegate); EXPECT_NE(plugin, nullptr); // set input config g_autoptr(FlValue) config = build_input_config({.client_id = 1}); g_autoptr(FlJsonMethodCodec) codec = fl_json_method_codec_new(); g_autoptr(GBytes) set_client = fl_method_codec_encode_method_call( FL_METHOD_CODEC(codec), "TextInput.setClient", config, nullptr); g_autoptr(FlValue) null = fl_value_new_null(); EXPECT_CALL(messenger, fl_binary_messenger_send_response( ::testing::Eq<FlBinaryMessenger*>(messenger), ::testing::_, SuccessResponse(null), ::testing::_)) .WillOnce(::testing::Return(true)); messenger.ReceiveMessage("flutter/textinput", set_client); // set editing state g_autoptr(FlValue) state = build_editing_state({ .text = "Flutter", .selection_base = 3, .selection_extent = 3, }); g_autoptr(GBytes) set_state = fl_method_codec_encode_method_call( FL_METHOD_CODEC(codec), "TextInput.setEditingState", state, nullptr); EXPECT_CALL(messenger, fl_binary_messenger_send_response( ::testing::Eq<FlBinaryMessenger*>(messenger), ::testing::_, SuccessResponse(null), ::testing::_)) .WillOnce(::testing::Return(true)); messenger.ReceiveMessage("flutter/textinput", set_state); // retrieve EXPECT_CALL(context, gtk_im_context_set_surrounding( ::testing::Eq<GtkIMContext*>(context), ::testing::StrEq("Flutter"), 7, 3)); gboolean retrieved = false; g_signal_emit_by_name(context, "retrieve-surrounding", &retrieved, nullptr); EXPECT_TRUE(retrieved); // delete g_autoptr(FlValue) update = build_list({ fl_value_new_int(1), // client_id build_editing_state({ .text = "Flutr", .selection_base = 3, .selection_extent = 3, }), }); EXPECT_CALL(messenger, fl_binary_messenger_send_on_channel( ::testing::Eq<FlBinaryMessenger*>(messenger), ::testing::StrEq("flutter/textinput"), MethodCall("TextInputClient.updateEditingState", FlValueEq(update)), ::testing::_, ::testing::_, ::testing::_)); gboolean deleted = false; g_signal_emit_by_name(context, "delete-surrounding", 1, 2, &deleted, nullptr); EXPECT_TRUE(deleted); } TEST(FlTextInputPluginTest, SetMarkedTextRect) { ::testing::NiceMock<flutter::testing::MockBinaryMessenger> messenger; ::testing::NiceMock<flutter::testing::MockIMContext> context; ::testing::NiceMock<flutter::testing::MockTextInputViewDelegate> delegate; g_autoptr(FlTextInputPlugin) plugin = fl_text_input_plugin_new(messenger, context, delegate); EXPECT_NE(plugin, nullptr); g_signal_emit_by_name(context, "preedit-start", nullptr); // set editable size and transform g_autoptr(FlValue) size_and_transform = build_map({ { "transform", build_list({ fl_value_new_float(1), fl_value_new_float(2), fl_value_new_float(3), fl_value_new_float(4), fl_value_new_float(5), fl_value_new_float(6), fl_value_new_float(7), fl_value_new_float(8), fl_value_new_float(9), fl_value_new_float(10), fl_value_new_float(11), fl_value_new_float(12), fl_value_new_float(13), fl_value_new_float(14), fl_value_new_float(15), fl_value_new_float(16), }), }, }); g_autoptr(FlJsonMethodCodec) codec = fl_json_method_codec_new(); g_autoptr(GBytes) set_editable_size_and_transform = fl_method_codec_encode_method_call( FL_METHOD_CODEC(codec), "TextInput.setEditableSizeAndTransform", size_and_transform, nullptr); g_autoptr(FlValue) null = fl_value_new_null(); EXPECT_CALL(messenger, fl_binary_messenger_send_response( ::testing::Eq<FlBinaryMessenger*>(messenger), ::testing::_, SuccessResponse(null), ::testing::_)) .WillOnce(::testing::Return(true)); messenger.ReceiveMessage("flutter/textinput", set_editable_size_and_transform); // set marked text rect g_autoptr(FlValue) rect = build_map({ {"x", fl_value_new_float(1)}, {"y", fl_value_new_float(2)}, {"width", fl_value_new_float(3)}, {"height", fl_value_new_float(4)}, }); g_autoptr(GBytes) set_marked_text_rect = fl_method_codec_encode_method_call( FL_METHOD_CODEC(codec), "TextInput.setMarkedTextRect", rect, nullptr); EXPECT_CALL(messenger, fl_binary_messenger_send_response( ::testing::Eq<FlBinaryMessenger*>(messenger), ::testing::_, SuccessResponse(null), ::testing::_)) .WillOnce(::testing::Return(true)); EXPECT_CALL(delegate, fl_text_input_view_delegate_translate_coordinates( ::testing::Eq<FlTextInputViewDelegate*>(delegate), ::testing::Eq(27), ::testing::Eq(32), ::testing::_, ::testing::_)) .WillOnce(::testing::DoAll(::testing::SetArgPointee<3>(123), ::testing::SetArgPointee<4>(456))); EXPECT_CALL(context, gtk_im_context_set_cursor_location( ::testing::Eq<GtkIMContext*>(context), ::testing::Pointee(::testing::AllOf( ::testing::Field(&GdkRectangle::x, 123), ::testing::Field(&GdkRectangle::y, 456), ::testing::Field(&GdkRectangle::width, 0), ::testing::Field(&GdkRectangle::height, 0))))); messenger.ReceiveMessage("flutter/textinput", set_marked_text_rect); } TEST(FlTextInputPluginTest, TextInputTypeNone) { ::testing::NiceMock<flutter::testing::MockBinaryMessenger> messenger; ::testing::NiceMock<flutter::testing::MockIMContext> context; ::testing::NiceMock<flutter::testing::MockTextInputViewDelegate> delegate; g_autoptr(FlTextInputPlugin) plugin = fl_text_input_plugin_new(messenger, context, delegate); EXPECT_NE(plugin, nullptr); g_autoptr(FlValue) args = build_input_config({ .client_id = 1, .input_type = "TextInputType.none", }); g_autoptr(FlJsonMethodCodec) codec = fl_json_method_codec_new(); g_autoptr(GBytes) set_client = fl_method_codec_encode_method_call( FL_METHOD_CODEC(codec), "TextInput.setClient", args, nullptr); g_autoptr(FlValue) null = fl_value_new_null(); EXPECT_CALL(messenger, fl_binary_messenger_send_response( ::testing::Eq<FlBinaryMessenger*>(messenger), ::testing::A<FlBinaryMessengerResponseHandle*>(), SuccessResponse(null), ::testing::A<GError**>())) .WillOnce(::testing::Return(true)); messenger.ReceiveMessage("flutter/textinput", set_client); EXPECT_CALL(context, gtk_im_context_focus_in(::testing::Eq<GtkIMContext*>(context))) .Times(0); EXPECT_CALL(context, gtk_im_context_focus_out(::testing::Eq<GtkIMContext*>(context))); EXPECT_CALL(messenger, fl_binary_messenger_send_response( ::testing::Eq<FlBinaryMessenger*>(messenger), ::testing::_, SuccessResponse(null), ::testing::_)) .WillOnce(::testing::Return(true)); g_autoptr(GBytes) show = fl_method_codec_encode_method_call( FL_METHOD_CODEC(codec), "TextInput.show", nullptr, nullptr); messenger.ReceiveMessage("flutter/textinput", show); } TEST(FlTextInputPluginTest, TextEditingDelta) { ::testing::NiceMock<flutter::testing::MockBinaryMessenger> messenger; ::testing::NiceMock<flutter::testing::MockIMContext> context; ::testing::NiceMock<flutter::testing::MockTextInputViewDelegate> delegate; g_autoptr(FlTextInputPlugin) plugin = fl_text_input_plugin_new(messenger, context, delegate); EXPECT_NE(plugin, nullptr); // set config g_autoptr(FlValue) args = build_input_config({ .client_id = 1, .enable_delta_model = true, }); g_autoptr(FlJsonMethodCodec) codec = fl_json_method_codec_new(); g_autoptr(GBytes) set_client = fl_method_codec_encode_method_call( FL_METHOD_CODEC(codec), "TextInput.setClient", args, nullptr); g_autoptr(FlValue) null = fl_value_new_null(); EXPECT_CALL(messenger, fl_binary_messenger_send_response( ::testing::Eq<FlBinaryMessenger*>(messenger), ::testing::A<FlBinaryMessengerResponseHandle*>(), SuccessResponse(null), ::testing::A<GError**>())) .WillOnce(::testing::Return(true)); messenger.ReceiveMessage("flutter/textinput", set_client); // set editing state g_autoptr(FlValue) state = build_editing_state({ .text = "Flutter", .selection_base = 7, .selection_extent = 7, }); g_autoptr(GBytes) set_state = fl_method_codec_encode_method_call( FL_METHOD_CODEC(codec), "TextInput.setEditingState", state, nullptr); EXPECT_CALL(messenger, fl_binary_messenger_send_response( ::testing::Eq<FlBinaryMessenger*>(messenger), ::testing::_, SuccessResponse(null), ::testing::_)) .WillOnce(::testing::Return(true)); messenger.ReceiveMessage("flutter/textinput", set_state); // update editing state with deltas g_autoptr(FlValue) deltas = build_list({ fl_value_new_int(1), // client_id build_map({{ "deltas", build_list({ build_editing_delta({ .old_text = "Flutter", .delta_text = "Flutter", .delta_start = 7, .delta_end = 7, .selection_base = 0, .selection_extent = 0, }), }), }}), }); EXPECT_CALL(messenger, fl_binary_messenger_send_on_channel( ::testing::Eq<FlBinaryMessenger*>(messenger), ::testing::StrEq("flutter/textinput"), MethodCall("TextInputClient.updateEditingStateWithDeltas", FlValueEq(deltas)), ::testing::_, ::testing::_, ::testing::_)); send_key_event(plugin, GDK_KEY_Home); } TEST(FlTextInputPluginTest, ComposingDelta) { ::testing::NiceMock<flutter::testing::MockBinaryMessenger> messenger; ::testing::NiceMock<flutter::testing::MockIMContext> context; ::testing::NiceMock<flutter::testing::MockTextInputViewDelegate> delegate; g_autoptr(FlTextInputPlugin) plugin = fl_text_input_plugin_new(messenger, context, delegate); EXPECT_NE(plugin, nullptr); // set config g_autoptr(FlValue) args = build_input_config({ .client_id = 1, .enable_delta_model = true, }); g_autoptr(FlJsonMethodCodec) codec = fl_json_method_codec_new(); g_autoptr(GBytes) set_client = fl_method_codec_encode_method_call( FL_METHOD_CODEC(codec), "TextInput.setClient", args, nullptr); g_autoptr(FlValue) null = fl_value_new_null(); EXPECT_CALL(messenger, fl_binary_messenger_send_response( ::testing::Eq<FlBinaryMessenger*>(messenger), ::testing::A<FlBinaryMessengerResponseHandle*>(), SuccessResponse(null), ::testing::A<GError**>())) .WillOnce(::testing::Return(true)); messenger.ReceiveMessage("flutter/textinput", set_client); g_signal_emit_by_name(context, "preedit-start", nullptr); // update EXPECT_CALL(context, gtk_im_context_get_preedit_string( ::testing::Eq<GtkIMContext*>(context), ::testing::A<gchar**>(), ::testing::_, ::testing::A<gint*>())) .WillOnce( ::testing::DoAll(::testing::SetArgPointee<1>(g_strdup("Flutter ")), ::testing::SetArgPointee<3>(8))); g_autoptr(FlValue) update = build_list({ fl_value_new_int(1), // client_id build_map({{ "deltas", build_list({ build_editing_delta({ .old_text = "", .delta_text = "Flutter ", .delta_start = 0, .delta_end = 0, .selection_base = 8, .selection_extent = 8, .composing_base = 0, .composing_extent = 8, }), }), }}), }); EXPECT_CALL(messenger, fl_binary_messenger_send_on_channel( ::testing::Eq<FlBinaryMessenger*>(messenger), ::testing::StrEq("flutter/textinput"), MethodCall("TextInputClient.updateEditingStateWithDeltas", FlValueEq(update)), ::testing::_, ::testing::_, ::testing::_)); g_signal_emit_by_name(context, "preedit-changed", nullptr); // commit g_autoptr(FlValue) commit = build_list({ fl_value_new_int(1), // client_id build_map({{ "deltas", build_list({ build_editing_delta({ .old_text = "Flutter ", .delta_text = "Flutter engine", .delta_start = 0, .delta_end = 8, .selection_base = 14, .selection_extent = 14, .composing_base = -1, .composing_extent = -1, }), }), }}), }); EXPECT_CALL(messenger, fl_binary_messenger_send_on_channel( ::testing::Eq<FlBinaryMessenger*>(messenger), ::testing::StrEq("flutter/textinput"), MethodCall("TextInputClient.updateEditingStateWithDeltas", FlValueEq(commit)), ::testing::_, ::testing::_, ::testing::_)); g_signal_emit_by_name(context, "commit", "Flutter engine", nullptr); // end g_autoptr(FlValue) end = build_list({ fl_value_new_int(1), // client_id build_map({{ "deltas", build_list({ build_editing_delta({ .old_text = "Flutter engine", .selection_base = 14, .selection_extent = 14, }), }), }}), }); EXPECT_CALL(messenger, fl_binary_messenger_send_on_channel( ::testing::Eq<FlBinaryMessenger*>(messenger), ::testing::StrEq("flutter/textinput"), MethodCall("TextInputClient.updateEditingStateWithDeltas", FlValueEq(end)), ::testing::_, ::testing::_, ::testing::_)); g_signal_emit_by_name(context, "preedit-end", nullptr); } TEST(FlTextInputPluginTest, NonComposingDelta) { ::testing::NiceMock<flutter::testing::MockBinaryMessenger> messenger; ::testing::NiceMock<flutter::testing::MockIMContext> context; ::testing::NiceMock<flutter::testing::MockTextInputViewDelegate> delegate; g_autoptr(FlTextInputPlugin) plugin = fl_text_input_plugin_new(messenger, context, delegate); EXPECT_NE(plugin, nullptr); // set config g_autoptr(FlValue) args = build_input_config({ .client_id = 1, .enable_delta_model = true, }); g_autoptr(FlJsonMethodCodec) codec = fl_json_method_codec_new(); g_autoptr(GBytes) set_client = fl_method_codec_encode_method_call( FL_METHOD_CODEC(codec), "TextInput.setClient", args, nullptr); g_autoptr(FlValue) null = fl_value_new_null(); EXPECT_CALL(messenger, fl_binary_messenger_send_response( ::testing::Eq<FlBinaryMessenger*>(messenger), ::testing::A<FlBinaryMessengerResponseHandle*>(), SuccessResponse(null), ::testing::A<GError**>())) .WillOnce(::testing::Return(true)); messenger.ReceiveMessage("flutter/textinput", set_client); // commit F g_autoptr(FlValue) commit = build_list({ fl_value_new_int(1), // client_id build_map({{ "deltas", build_list({ build_editing_delta({ .old_text = "", .delta_text = "F", .delta_start = 0, .delta_end = 0, .selection_base = 1, .selection_extent = 1, .composing_base = -1, .composing_extent = -1, }), }), }}), }); EXPECT_CALL(messenger, fl_binary_messenger_send_on_channel( ::testing::Eq<FlBinaryMessenger*>(messenger), ::testing::StrEq("flutter/textinput"), MethodCall("TextInputClient.updateEditingStateWithDeltas", FlValueEq(commit)), ::testing::_, ::testing::_, ::testing::_)); g_signal_emit_by_name(context, "commit", "F", nullptr); // commit l g_autoptr(FlValue) commitL = build_list({ fl_value_new_int(1), // client_id build_map({{ "deltas", build_list({ build_editing_delta({ .old_text = "F", .delta_text = "l", .delta_start = 1, .delta_end = 1, .selection_base = 2, .selection_extent = 2, .composing_base = -1, .composing_extent = -1, }), }), }}), }); EXPECT_CALL(messenger, fl_binary_messenger_send_on_channel( ::testing::Eq<FlBinaryMessenger*>(messenger), ::testing::StrEq("flutter/textinput"), MethodCall("TextInputClient.updateEditingStateWithDeltas", FlValueEq(commitL)), ::testing::_, ::testing::_, ::testing::_)); g_signal_emit_by_name(context, "commit", "l", nullptr); // commit u g_autoptr(FlValue) commitU = build_list({ fl_value_new_int(1), // client_id build_map({{ "deltas", build_list({ build_editing_delta({ .old_text = "Fl", .delta_text = "u", .delta_start = 2, .delta_end = 2, .selection_base = 3, .selection_extent = 3, .composing_base = -1, .composing_extent = -1, }), }), }}), }); EXPECT_CALL(messenger, fl_binary_messenger_send_on_channel( ::testing::Eq<FlBinaryMessenger*>(messenger), ::testing::StrEq("flutter/textinput"), MethodCall("TextInputClient.updateEditingStateWithDeltas", FlValueEq(commitU)), ::testing::_, ::testing::_, ::testing::_)); g_signal_emit_by_name(context, "commit", "u", nullptr); // commit t g_autoptr(FlValue) commitTa = build_list({ fl_value_new_int(1), // client_id build_map({{ "deltas", build_list({ build_editing_delta({ .old_text = "Flu", .delta_text = "t", .delta_start = 3, .delta_end = 3, .selection_base = 4, .selection_extent = 4, .composing_base = -1, .composing_extent = -1, }), }), }}), }); EXPECT_CALL(messenger, fl_binary_messenger_send_on_channel( ::testing::Eq<FlBinaryMessenger*>(messenger), ::testing::StrEq("flutter/textinput"), MethodCall("TextInputClient.updateEditingStateWithDeltas", FlValueEq(commitTa)), ::testing::_, ::testing::_, ::testing::_)); g_signal_emit_by_name(context, "commit", "t", nullptr); // commit t again g_autoptr(FlValue) commitTb = build_list({ fl_value_new_int(1), // client_id build_map({{ "deltas", build_list({ build_editing_delta({ .old_text = "Flut", .delta_text = "t", .delta_start = 4, .delta_end = 4, .selection_base = 5, .selection_extent = 5, .composing_base = -1, .composing_extent = -1, }), }), }}), }); EXPECT_CALL(messenger, fl_binary_messenger_send_on_channel( ::testing::Eq<FlBinaryMessenger*>(messenger), ::testing::StrEq("flutter/textinput"), MethodCall("TextInputClient.updateEditingStateWithDeltas", FlValueEq(commitTb)), ::testing::_, ::testing::_, ::testing::_)); g_signal_emit_by_name(context, "commit", "t", nullptr); // commit e g_autoptr(FlValue) commitE = build_list({ fl_value_new_int(1), // client_id build_map({{ "deltas", build_list({ build_editing_delta({ .old_text = "Flutt", .delta_text = "e", .delta_start = 5, .delta_end = 5, .selection_base = 6, .selection_extent = 6, .composing_base = -1, .composing_extent = -1, }), }), }}), }); EXPECT_CALL(messenger, fl_binary_messenger_send_on_channel( ::testing::Eq<FlBinaryMessenger*>(messenger), ::testing::StrEq("flutter/textinput"), MethodCall("TextInputClient.updateEditingStateWithDeltas", FlValueEq(commitE)), ::testing::_, ::testing::_, ::testing::_)); g_signal_emit_by_name(context, "commit", "e", nullptr); // commit r g_autoptr(FlValue) commitR = build_list({ fl_value_new_int(1), // client_id build_map({{ "deltas", build_list({ build_editing_delta({ .old_text = "Flutte", .delta_text = "r", .delta_start = 6, .delta_end = 6, .selection_base = 7, .selection_extent = 7, .composing_base = -1, .composing_extent = -1, }), }), }}), }); EXPECT_CALL(messenger, fl_binary_messenger_send_on_channel( ::testing::Eq<FlBinaryMessenger*>(messenger), ::testing::StrEq("flutter/textinput"), MethodCall("TextInputClient.updateEditingStateWithDeltas", FlValueEq(commitR)), ::testing::_, ::testing::_, ::testing::_)); g_signal_emit_by_name(context, "commit", "r", nullptr); }
engine/shell/platform/linux/fl_text_input_plugin_test.cc/0
{ "file_path": "engine/shell/platform/linux/fl_text_input_plugin_test.cc", "repo_id": "engine", "token_count": 23696 }
373
// 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. // Included first as it collides with the X11 headers. #include "gtest/gtest.h" #include "flutter/shell/platform/linux/fl_view_accessible.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_engine.h" #include "flutter/shell/platform/linux/testing/fl_test.h" #include "flutter/shell/platform/linux/testing/mock_signal_handler.h" TEST(FlViewAccessibleTest, BuildTree) { g_autoptr(FlEngine) engine = make_mock_engine(); g_autoptr(FlViewAccessible) accessible = FL_VIEW_ACCESSIBLE( g_object_new(fl_view_accessible_get_type(), "engine", engine, nullptr)); int32_t children[] = {111, 222}; FlutterSemanticsNode2 root_node = { .id = 0, .label = "root", .child_count = 2, .children_in_traversal_order = children, }; FlutterSemanticsNode2 child1_node = {.id = 111, .label = "child 1"}; FlutterSemanticsNode2 child2_node = {.id = 222, .label = "child 2"}; FlutterSemanticsNode2* nodes[3] = {&root_node, &child1_node, &child2_node}; FlutterSemanticsUpdate2 update = {.node_count = 3, .nodes = nodes}; fl_view_accessible_handle_update_semantics(accessible, &update); AtkObject* root_object = atk_object_ref_accessible_child(ATK_OBJECT(accessible), 0); EXPECT_STREQ(atk_object_get_name(root_object), "root"); EXPECT_EQ(atk_object_get_index_in_parent(root_object), 0); EXPECT_EQ(atk_object_get_n_accessible_children(root_object), 2); AtkObject* child1_object = atk_object_ref_accessible_child(root_object, 0); EXPECT_STREQ(atk_object_get_name(child1_object), "child 1"); EXPECT_EQ(atk_object_get_parent(child1_object), root_object); EXPECT_EQ(atk_object_get_index_in_parent(child1_object), 0); EXPECT_EQ(atk_object_get_n_accessible_children(child1_object), 0); AtkObject* child2_object = atk_object_ref_accessible_child(root_object, 1); EXPECT_STREQ(atk_object_get_name(child2_object), "child 2"); EXPECT_EQ(atk_object_get_parent(child2_object), root_object); EXPECT_EQ(atk_object_get_index_in_parent(child2_object), 1); EXPECT_EQ(atk_object_get_n_accessible_children(child2_object), 0); } TEST(FlViewAccessibleTest, AddRemoveChildren) { g_autoptr(FlEngine) engine = make_mock_engine(); g_autoptr(FlViewAccessible) accessible = FL_VIEW_ACCESSIBLE( g_object_new(fl_view_accessible_get_type(), "engine", engine, nullptr)); FlutterSemanticsNode2 root_node = { .id = 0, .label = "root", .child_count = 0, }; FlutterSemanticsNode2* nodes[1] = {&root_node}; FlutterSemanticsUpdate2 update = {.node_count = 1, .nodes = nodes}; fl_view_accessible_handle_update_semantics(accessible, &update); AtkObject* root_object = atk_object_ref_accessible_child(ATK_OBJECT(accessible), 0); EXPECT_EQ(atk_object_get_n_accessible_children(root_object), 0); // add child1 AtkObject* child1_object = nullptr; FlutterSemanticsNode2 child1_node = {.id = 111, .label = "child 1"}; { flutter::testing::MockSignalHandler2<gint, AtkObject*> child1_added( root_object, "children-changed::add"); EXPECT_SIGNAL2(child1_added, ::testing::Eq(0), ::testing::A<AtkObject*>()) .WillOnce(::testing::SaveArg<1>(&child1_object)); int32_t children[] = {111}; root_node.child_count = 1; root_node.children_in_traversal_order = children; FlutterSemanticsNode2* nodes[2] = {&root_node, &child1_node}; FlutterSemanticsUpdate2 update = {.node_count = 2, .nodes = nodes}; fl_view_accessible_handle_update_semantics(accessible, &update); } EXPECT_EQ(atk_object_get_n_accessible_children(root_object), 1); EXPECT_EQ(atk_object_ref_accessible_child(root_object, 0), child1_object); EXPECT_STREQ(atk_object_get_name(child1_object), "child 1"); EXPECT_EQ(atk_object_get_parent(child1_object), root_object); EXPECT_EQ(atk_object_get_index_in_parent(child1_object), 0); EXPECT_EQ(atk_object_get_n_accessible_children(child1_object), 0); // add child2 AtkObject* child2_object = nullptr; FlutterSemanticsNode2 child2_node = {.id = 222, .label = "child 2"}; { flutter::testing::MockSignalHandler2<gint, AtkObject*> child2_added( root_object, "children-changed::add"); EXPECT_SIGNAL2(child2_added, ::testing::Eq(1), ::testing::A<AtkObject*>()) .WillOnce(::testing::SaveArg<1>(&child2_object)); int32_t children[] = {111, 222}; root_node.child_count = 2; root_node.children_in_traversal_order = children; FlutterSemanticsNode2* nodes[3] = {&root_node, &child1_node, &child2_node}; FlutterSemanticsUpdate2 update = {.node_count = 3, .nodes = nodes}; fl_view_accessible_handle_update_semantics(accessible, &update); } EXPECT_EQ(atk_object_get_n_accessible_children(root_object), 2); EXPECT_EQ(atk_object_ref_accessible_child(root_object, 0), child1_object); EXPECT_EQ(atk_object_ref_accessible_child(root_object, 1), child2_object); EXPECT_STREQ(atk_object_get_name(child1_object), "child 1"); EXPECT_EQ(atk_object_get_parent(child1_object), root_object); EXPECT_EQ(atk_object_get_index_in_parent(child1_object), 0); EXPECT_EQ(atk_object_get_n_accessible_children(child1_object), 0); EXPECT_STREQ(atk_object_get_name(child2_object), "child 2"); EXPECT_EQ(atk_object_get_parent(child2_object), root_object); EXPECT_EQ(atk_object_get_index_in_parent(child2_object), 1); EXPECT_EQ(atk_object_get_n_accessible_children(child2_object), 0); // remove child1 { flutter::testing::MockSignalHandler2<gint, AtkObject*> child1_removed( root_object, "children-changed::remove"); EXPECT_SIGNAL2(child1_removed, ::testing::Eq(0), ::testing::Eq(child1_object)); const int32_t children[] = {222}; root_node.child_count = 1; root_node.children_in_traversal_order = children; FlutterSemanticsNode2* nodes[3] = {&root_node, &child2_node}; FlutterSemanticsUpdate2 update = {.node_count = 2, .nodes = nodes}; fl_view_accessible_handle_update_semantics(accessible, &update); } EXPECT_EQ(atk_object_get_n_accessible_children(root_object), 1); EXPECT_EQ(atk_object_ref_accessible_child(root_object, 0), child2_object); EXPECT_STREQ(atk_object_get_name(child2_object), "child 2"); EXPECT_EQ(atk_object_get_parent(child2_object), root_object); EXPECT_EQ(atk_object_get_index_in_parent(child2_object), 0); EXPECT_EQ(atk_object_get_n_accessible_children(child2_object), 0); // remove child2 { flutter::testing::MockSignalHandler2<gint, AtkObject*> child2_removed( root_object, "children-changed::remove"); EXPECT_SIGNAL2(child2_removed, ::testing::Eq(0), ::testing::Eq(child2_object)); root_node.child_count = 0; FlutterSemanticsNode2* nodes[1] = {&root_node}; FlutterSemanticsUpdate2 update = {.node_count = 1, .nodes = nodes}; fl_view_accessible_handle_update_semantics(accessible, &update); } EXPECT_EQ(atk_object_get_n_accessible_children(root_object), 0); }
engine/shell/platform/linux/fl_view_accessible_test.cc/0
{ "file_path": "engine/shell/platform/linux/fl_view_accessible_test.cc", "repo_id": "engine", "token_count": 2803 }
374
// 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_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_METHOD_CHANNEL_H_ #define FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_METHOD_CHANNEL_H_ #if !defined(__FLUTTER_LINUX_INSIDE__) && !defined(FLUTTER_LINUX_COMPILATION) #error "Only <flutter_linux/flutter_linux.h> can be included directly." #endif #include <gio/gio.h> #include <glib-object.h> #include <gmodule.h> #include "fl_binary_messenger.h" #include "fl_method_call.h" #include "fl_method_codec.h" #include "fl_method_response.h" G_BEGIN_DECLS G_MODULE_EXPORT G_DECLARE_FINAL_TYPE(FlMethodChannel, fl_method_channel, FL, METHOD_CHANNEL, GObject) /** * FlMethodChannel: * * #FlMethodChannel is an object that allows method calls to and from Dart code. * * The following example shows how to call and handle methods on a channel. * See #FlMethodResponse for how to handle errors in more detail. * * |[<!-- language="C" --> * static FlMethodChannel *channel = NULL; * * static void method_call_cb (FlMethodChannel* channel, * FlMethodCall* method_call, * gpointer user_data) { * g_autoptr(FlMethodResponse) response = NULL; * if (strcmp (fl_method_call_get_name (method_call), "Foo.bar") == 0) { * g_autoptr(GError) bar_error = NULL; * g_autoptr(FlValue) result = * do_bar (fl_method_call_get_args (method_call), &bar_error); * if (result == NULL) { * response = * FL_METHOD_RESPONSE (fl_method_error_response_new ("bar error", * bar_error->message, * nullptr); * } else { * response = * FL_METHOD_RESPONSE (fl_method_success_response_new (result)); * } * } else { * response = * FL_METHOD_RESPONSE (fl_method_not_implemented_response_new ()); * } * * g_autoptr(GError) error = NULL; * if (!fl_method_call_respond(method_call, response, &error)) * g_warning ("Failed to send response: %s", error->message); * } * * static void method_response_cb(GObject *object, * GAsyncResult *result, * gpointer user_data) { * g_autoptr(GError) error = NULL; * g_autoptr(FlMethodResponse) response = * fl_method_channel_invoke_method_finish (FL_METHOD_CODEC (object), result, * &error); * if (response == NULL) { * g_warning ("Failed to call method: %s", error->message); * return; * } * * g_autoptr(FlValue) value = * fl_method_response_get_result (response, &error); * if (response == NULL) { * g_warning ("Method returned error: %s", error->message); * return; * } * * use_result (value); * } * * static void call_method () { * g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new (); * channel = * fl_method_channel_new(messenger, "flutter/foo", FL_METHOD_CODEC (codec)); * fl_method_channel_set_method_call_handler (channel, method_call_cb, NULL, * NULL); * * g_autoptr(FlValue) args = fl_value_new_string ("Hello World"); * fl_method_channel_invoke_method (channel, "Foo.foo", args, * cancellable, method_response_cb, NULL); * } * ]| * * #FlMethodChannel matches the MethodChannel class in the Flutter services * library. */ /** * FlMethodChannelMethodCallHandler: * @channel: an #FlMethodChannel. * @method_call: an #FlMethodCall. * @user_data: (closure): data provided when registering this handler. * * Function called when a method call is received. Respond to the method call * with fl_method_call_respond(). If the response is not occurring in this * callback take a reference to @method_call and release that once it has been * responded to. Failing to respond before the last reference to @method_call is * dropped is a programming error. */ typedef void (*FlMethodChannelMethodCallHandler)(FlMethodChannel* channel, FlMethodCall* method_call, gpointer user_data); /** * fl_method_channel_new: * @messenger: an #FlBinaryMessenger. * @name: a channel name. * @codec: the method codec. * * Creates a new method channel. @codec must match the codec used on the Dart * end of the channel. * * Returns: a new #FlMethodChannel. */ FlMethodChannel* fl_method_channel_new(FlBinaryMessenger* messenger, const gchar* name, FlMethodCodec* codec); /** * fl_method_channel_set_method_call_handler: * @channel: an #FlMethodChannel. * @handler: function to call when a method call is received on this channel. * @user_data: (closure): user data to pass to @handler. * @destroy_notify: (allow-none): a function which gets called to free * @user_data, or %NULL. * * Sets the function called when a method call is received from the Dart side of * the channel. See #FlMethodChannelMethodCallHandler for details on how to * respond to method calls. * * The handler is removed if the channel is closed or is replaced by another * handler, set @destroy_notify if you want to detect this. */ void fl_method_channel_set_method_call_handler( FlMethodChannel* channel, FlMethodChannelMethodCallHandler handler, gpointer user_data, GDestroyNotify destroy_notify); /** * fl_method_channel_invoke_method: * @channel: an #FlMethodChannel. * @method: the method to call. * @args: (allow-none): arguments to the method, must match what the * #FlMethodCodec supports. * @cancellable: (allow-none): a #GCancellable or %NULL. * @callback: (scope async): (allow-none): a #GAsyncReadyCallback to call when * the request is satisfied or %NULL to ignore the response. * @user_data: (closure): user data to pass to @callback. * * Calls a method on this channel. */ void fl_method_channel_invoke_method(FlMethodChannel* channel, const gchar* method, FlValue* args, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data); /** * fl_method_channel_invoke_method_finish: * @channel: an #FlMethodChannel. * @result: #GAsyncResult. * @error: (allow-none): #GError location to store the error occurring, or %NULL * to ignore. * * Completes request started with fl_method_channel_invoke_method(). * * Returns: (transfer full): an #FlMethodResponse or %NULL on error. */ FlMethodResponse* fl_method_channel_invoke_method_finish( FlMethodChannel* channel, GAsyncResult* result, GError** error); G_END_DECLS #endif // FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_METHOD_CHANNEL_H_
engine/shell/platform/linux/public/flutter_linux/fl_method_channel.h/0
{ "file_path": "engine/shell/platform/linux/public/flutter_linux/fl_method_channel.h", "repo_id": "engine", "token_count": 2965 }
375
// 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_SHELL_PLATFORM_LINUX_TESTING_FL_TEST_H_ #define FLUTTER_SHELL_PLATFORM_LINUX_TESTING_FL_TEST_H_ #include "flutter/shell/platform/linux/public/flutter_linux/fl_engine.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_value.h" #include <glib.h> #include <stdint.h> #include <ostream> G_BEGIN_DECLS // Helper functions for the tests. This is not included in the shell library. // Helper function to convert a hexadecimal string (e.g. "01feab") into GBytes GBytes* hex_string_to_bytes(const gchar* hex_string); // Helper function to convert GBytes into a hexadecimal string (e.g. "01feab") gchar* bytes_to_hex_string(GBytes* bytes); // Creates a mock engine that responds to platform messages. FlEngine* make_mock_engine(); // Creates a mock engine using a specified FlDartProject that responds to // platform messages. FlEngine* make_mock_engine_with_project(FlDartProject* project); // GTest printer for FlValue. void PrintTo(FlValue* v, std::ostream* os); G_END_DECLS #endif // FLUTTER_SHELL_PLATFORM_LINUX_TESTING_FL_TEST_H_
engine/shell/platform/linux/testing/fl_test.h/0
{ "file_path": "engine/shell/platform/linux/testing/fl_test.h", "repo_id": "engine", "token_count": 434 }
376
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/windows/accessibility_plugin.h" #include <variant> #include "flutter/fml/logging.h" #include "flutter/fml/platform/win/wstring_conversion.h" #include "flutter/shell/platform/common/client_wrapper/include/flutter/standard_message_codec.h" #include "flutter/shell/platform/windows/flutter_windows_engine.h" #include "flutter/shell/platform/windows/flutter_windows_view.h" namespace flutter { namespace { static constexpr char kAccessibilityChannelName[] = "flutter/accessibility"; static constexpr char kTypeKey[] = "type"; static constexpr char kDataKey[] = "data"; static constexpr char kMessageKey[] = "message"; static constexpr char kAnnounceValue[] = "announce"; // Handles messages like: // {"type": "announce", "data": {"message": "Hello"}} void HandleMessage(AccessibilityPlugin* plugin, const EncodableValue& message) { const auto* map = std::get_if<EncodableMap>(&message); if (!map) { FML_LOG(ERROR) << "Accessibility message must be a map."; return; } const auto& type_itr = map->find(EncodableValue{kTypeKey}); const auto& data_itr = map->find(EncodableValue{kDataKey}); if (type_itr == map->end()) { FML_LOG(ERROR) << "Accessibility message must have a 'type' property."; return; } if (data_itr == map->end()) { FML_LOG(ERROR) << "Accessibility message must have a 'data' property."; return; } const auto* type = std::get_if<std::string>(&type_itr->second); const auto* data = std::get_if<EncodableMap>(&data_itr->second); if (!type) { FML_LOG(ERROR) << "Accessibility message 'type' property must be a string."; return; } if (!data) { FML_LOG(ERROR) << "Accessibility message 'data' property must be a map."; return; } if (type->compare(kAnnounceValue) == 0) { const auto& message_itr = data->find(EncodableValue{kMessageKey}); if (message_itr == data->end()) { return; } const auto* message = std::get_if<std::string>(&message_itr->second); if (!message) { return; } plugin->Announce(*message); } else { FML_LOG(WARNING) << "Accessibility message type '" << *type << "' is not supported."; } } } // namespace AccessibilityPlugin::AccessibilityPlugin(FlutterWindowsEngine* engine) : engine_(engine) {} void AccessibilityPlugin::SetUp(BinaryMessenger* binary_messenger, AccessibilityPlugin* plugin) { BasicMessageChannel<> channel{binary_messenger, kAccessibilityChannelName, &StandardMessageCodec::GetInstance()}; channel.SetMessageHandler( [plugin](const EncodableValue& message, const MessageReply<EncodableValue>& reply) { HandleMessage(plugin, message); // The accessibility channel does not support error handling. // Always return an empty response even on failure. reply(EncodableValue{std::monostate{}}); }); } void AccessibilityPlugin::Announce(const std::string_view message) { if (!engine_->semantics_enabled()) { return; } // TODO(loicsharma): Remove implicit view assumption. // https://github.com/flutter/flutter/issues/142845 auto view = engine_->view(kImplicitViewId); if (!view) { return; } std::wstring wide_text = fml::Utf8ToWideString(message); view->AnnounceAlert(wide_text); } } // namespace flutter
engine/shell/platform/windows/accessibility_plugin.cc/0
{ "file_path": "engine/shell/platform/windows/accessibility_plugin.cc", "repo_id": "engine", "token_count": 1279 }
377
// 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_SHELL_PLATFORM_WINDOWS_CLIENT_WRAPPER_TESTING_STUB_FLUTTER_WINDOWS_API_H_ #define FLUTTER_SHELL_PLATFORM_WINDOWS_CLIENT_WRAPPER_TESTING_STUB_FLUTTER_WINDOWS_API_H_ #include <memory> #include "flutter/shell/platform/windows/flutter_windows_internal.h" #include "flutter/shell/platform/windows/public/flutter_windows.h" namespace flutter { namespace testing { // Base class for a object that provides test implementations of the APIs in // the headers in platform/windows/public/. // Linking this class into a test binary will provide dummy forwarding // implementations of that C API, so that the wrapper can be tested separately // from the actual library. class StubFlutterWindowsApi { public: // Sets |stub| as the instance to which calls to the Flutter library C APIs // will be forwarded. static void SetTestStub(StubFlutterWindowsApi* stub); // Returns the current stub, as last set by SetTestFlutterStub. static StubFlutterWindowsApi* GetTestStub(); virtual ~StubFlutterWindowsApi() {} // Called for FlutterDesktopViewControllerCreate. virtual FlutterDesktopViewControllerRef ViewControllerCreate(int width, int height, FlutterDesktopEngineRef engine) { return nullptr; } // Called for FlutterDesktopViewControllerDestroy. virtual void ViewControllerDestroy() {} // Called for FlutterDesktopViewControllerForceRedraw. virtual void ViewControllerForceRedraw() {} // Called for FlutterDesktopViewControllerHandleTopLevelWindowProc. virtual bool ViewControllerHandleTopLevelWindowProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam, LRESULT* result) { return false; } // Called for FlutterDesktopEngineCreate. virtual FlutterDesktopEngineRef EngineCreate( const FlutterDesktopEngineProperties& engine_properties) { return nullptr; } // Called for FlutterDesktopEngineDestroy. virtual bool EngineDestroy() { return true; } // Called for FlutterDesktopEngineRun. virtual bool EngineRun(const char* entry_point) { return true; } // Called for FlutterDesktopEngineProcessMessages. virtual uint64_t EngineProcessMessages() { return 0; } // Called for FlutterDesktopEngineSetNextFrameCallback. virtual void EngineSetNextFrameCallback(VoidCallback callback, void* user_data) {} // Called for FlutterDesktopEngineReloadSystemFonts. virtual void EngineReloadSystemFonts() {} // Called for FlutterDesktopEngineRegisterPlatformViewType. virtual void EngineRegisterPlatformViewType( const char* view_type_name, FlutterPlatformViewTypeEntry view_type) {} // Called for FlutterDesktopViewGetHWND. virtual HWND ViewGetHWND() { return reinterpret_cast<HWND>(1); } // Called for FlutterDesktopViewGetGraphicsAdapter. virtual IDXGIAdapter* ViewGetGraphicsAdapter() { return reinterpret_cast<IDXGIAdapter*>(2); } // Called for FlutterDesktopPluginRegistrarGetView. virtual FlutterDesktopViewRef PluginRegistrarGetView() { return nullptr; } // Called for FlutterDesktopPluginRegistrarGetViewById. virtual FlutterDesktopViewRef PluginRegistrarGetViewById( FlutterDesktopViewId view_id) { return nullptr; } // Called for FlutterDesktopPluginRegistrarRegisterTopLevelWindowProcDelegate. virtual void PluginRegistrarRegisterTopLevelWindowProcDelegate( FlutterDesktopWindowProcCallback delegate, void* user_data) {} // Called for // FlutterDesktopPluginRegistrarUnregisterTopLevelWindowProcDelegate. virtual void PluginRegistrarUnregisterTopLevelWindowProcDelegate( FlutterDesktopWindowProcCallback delegate) {} // Called for FlutterDesktopEngineProcessExternalWindowMessage. virtual bool EngineProcessExternalWindowMessage( FlutterDesktopEngineRef engine, HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam, LRESULT* result) { return false; } }; // A test helper that owns a stub implementation, making it the test stub for // the lifetime of the object, then restoring the previous value. class ScopedStubFlutterWindowsApi { public: // Calls SetTestFlutterStub with |stub|. ScopedStubFlutterWindowsApi(std::unique_ptr<StubFlutterWindowsApi> stub); // Restores the previous test stub. ~ScopedStubFlutterWindowsApi(); StubFlutterWindowsApi* stub() { return stub_.get(); } private: std::unique_ptr<StubFlutterWindowsApi> stub_; // The previous stub. StubFlutterWindowsApi* previous_stub_; }; } // namespace testing } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_WINDOWS_CLIENT_WRAPPER_TESTING_STUB_FLUTTER_WINDOWS_API_H_
engine/shell/platform/windows/client_wrapper/testing/stub_flutter_windows_api.h/0
{ "file_path": "engine/shell/platform/windows/client_wrapper/testing/stub_flutter_windows_api.h", "repo_id": "engine", "token_count": 1689 }
378
// 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 <windows.h> #include "flutter/shell/platform/windows/dpi_utils.h" #include "gtest/gtest.h" namespace flutter { namespace testing { TEST(DpiUtilsTest, NonZero) { ASSERT_GT(GetDpiForHWND(nullptr), 0); ASSERT_GT(GetDpiForMonitor(nullptr), 0); }; TEST(DpiUtilsTest, NullHwndUsesPrimaryMonitor) { const POINT target_point = {0, 0}; HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTOPRIMARY); ASSERT_EQ(GetDpiForHWND(nullptr), GetDpiForMonitor(monitor)); }; } // namespace testing } // namespace flutter
engine/shell/platform/windows/dpi_utils_unittests.cc/0
{ "file_path": "engine/shell/platform/windows/dpi_utils_unittests.cc", "repo_id": "engine", "token_count": 257 }
379
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/windows/external_texture_d3d.h" #include "flutter/fml/logging.h" #include "flutter/shell/platform/embedder/embedder_struct_macros.h" namespace flutter { ExternalTextureD3d::ExternalTextureD3d( FlutterDesktopGpuSurfaceType type, const FlutterDesktopGpuSurfaceTextureCallback texture_callback, void* user_data, const egl::Manager* egl_manager, std::shared_ptr<egl::ProcTable> gl) : type_(type), texture_callback_(texture_callback), user_data_(user_data), egl_manager_(egl_manager), gl_(std::move(gl)) {} ExternalTextureD3d::~ExternalTextureD3d() { ReleaseImage(); if (gl_texture_ != 0) { gl_->DeleteTextures(1, &gl_texture_); } } bool ExternalTextureD3d::PopulateTexture(size_t width, size_t height, FlutterOpenGLTexture* opengl_texture) { const FlutterDesktopGpuSurfaceDescriptor* descriptor = texture_callback_(width, height, user_data_); if (!CreateOrUpdateTexture(descriptor)) { return false; } // Populate the texture object used by the engine. opengl_texture->target = GL_TEXTURE_2D; opengl_texture->name = gl_texture_; opengl_texture->format = GL_RGBA8_OES; opengl_texture->destruction_callback = nullptr; opengl_texture->user_data = nullptr; opengl_texture->width = SAFE_ACCESS(descriptor, visible_width, 0); opengl_texture->height = SAFE_ACCESS(descriptor, visible_height, 0); return true; } void ExternalTextureD3d::ReleaseImage() { if (egl_surface_ != EGL_NO_SURFACE) { eglReleaseTexImage(egl_manager_->egl_display(), egl_surface_, EGL_BACK_BUFFER); eglDestroySurface(egl_manager_->egl_display(), egl_surface_); egl_surface_ = EGL_NO_SURFACE; } } bool ExternalTextureD3d::CreateOrUpdateTexture( const FlutterDesktopGpuSurfaceDescriptor* descriptor) { if (descriptor == nullptr || SAFE_ACCESS(descriptor, handle, nullptr) == nullptr) { ReleaseImage(); return false; } if (gl_texture_ == 0) { gl_->GenTextures(1, &gl_texture_); gl_->BindTexture(GL_TEXTURE_2D, gl_texture_); gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } else { gl_->BindTexture(GL_TEXTURE_2D, gl_texture_); } auto handle = SAFE_ACCESS(descriptor, handle, nullptr); if (handle != last_surface_handle_) { ReleaseImage(); EGLint attributes[] = { EGL_WIDTH, static_cast<EGLint>(SAFE_ACCESS(descriptor, width, 0)), EGL_HEIGHT, static_cast<EGLint>(SAFE_ACCESS(descriptor, height, 0)), EGL_TEXTURE_TARGET, EGL_TEXTURE_2D, EGL_TEXTURE_FORMAT, EGL_TEXTURE_RGBA, // always EGL_TEXTURE_RGBA EGL_NONE}; egl_surface_ = egl_manager_->CreateSurfaceFromHandle( (type_ == kFlutterDesktopGpuSurfaceTypeD3d11Texture2D) ? EGL_D3D_TEXTURE_ANGLE : EGL_D3D_TEXTURE_2D_SHARE_HANDLE_ANGLE, handle, attributes); if (egl_surface_ == EGL_NO_SURFACE || eglBindTexImage(egl_manager_->egl_display(), egl_surface_, EGL_BACK_BUFFER) == EGL_FALSE) { FML_LOG(ERROR) << "Binding D3D surface failed."; } last_surface_handle_ = handle; } auto release_callback = SAFE_ACCESS(descriptor, release_callback, nullptr); if (release_callback) { release_callback(SAFE_ACCESS(descriptor, release_context, nullptr)); } return egl_surface_ != EGL_NO_SURFACE; } } // namespace flutter
engine/shell/platform/windows/external_texture_d3d.cc/0
{ "file_path": "engine/shell/platform/windows/external_texture_d3d.cc", "repo_id": "engine", "token_count": 1672 }
380
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/windows/flutter_windows_engine.h" #include <dwmapi.h> #include <filesystem> #include <sstream> #include "flutter/fml/logging.h" #include "flutter/fml/paths.h" #include "flutter/fml/platform/win/wstring_conversion.h" #include "flutter/shell/platform/common/client_wrapper/binary_messenger_impl.h" #include "flutter/shell/platform/common/client_wrapper/include/flutter/standard_message_codec.h" #include "flutter/shell/platform/common/path_utils.h" #include "flutter/shell/platform/embedder/embedder_struct_macros.h" #include "flutter/shell/platform/windows/accessibility_bridge_windows.h" #include "flutter/shell/platform/windows/compositor_opengl.h" #include "flutter/shell/platform/windows/compositor_software.h" #include "flutter/shell/platform/windows/flutter_windows_view.h" #include "flutter/shell/platform/windows/keyboard_key_channel_handler.h" #include "flutter/shell/platform/windows/system_utils.h" #include "flutter/shell/platform/windows/task_runner.h" #include "flutter/third_party/accessibility/ax/ax_node.h" // winbase.h defines GetCurrentTime as a macro. #undef GetCurrentTime static constexpr char kAccessibilityChannelName[] = "flutter/accessibility"; namespace flutter { namespace { // Lifted from vsync_waiter_fallback.cc static std::chrono::nanoseconds SnapToNextTick( std::chrono::nanoseconds value, std::chrono::nanoseconds tick_phase, std::chrono::nanoseconds tick_interval) { std::chrono::nanoseconds offset = (tick_phase - value) % tick_interval; if (offset != std::chrono::nanoseconds::zero()) offset = offset + tick_interval; return value + offset; } // Creates and returns a FlutterRendererConfig that renders to the view (if any) // of a FlutterWindowsEngine, using OpenGL (via ANGLE). // The user_data received by the render callbacks refers to the // FlutterWindowsEngine. FlutterRendererConfig GetOpenGLRendererConfig() { FlutterRendererConfig config = {}; config.type = kOpenGL; config.open_gl.struct_size = sizeof(config.open_gl); config.open_gl.make_current = [](void* user_data) -> bool { auto host = static_cast<FlutterWindowsEngine*>(user_data); if (!host->egl_manager()) { return false; } return host->egl_manager()->render_context()->MakeCurrent(); }; config.open_gl.clear_current = [](void* user_data) -> bool { auto host = static_cast<FlutterWindowsEngine*>(user_data); if (!host->egl_manager()) { return false; } return host->egl_manager()->render_context()->ClearCurrent(); }; config.open_gl.present = [](void* user_data) -> bool { FML_UNREACHABLE(); }; config.open_gl.fbo_reset_after_present = true; config.open_gl.fbo_with_frame_info_callback = [](void* user_data, const FlutterFrameInfo* info) -> uint32_t { FML_UNREACHABLE(); }; config.open_gl.gl_proc_resolver = [](void* user_data, const char* what) -> void* { return reinterpret_cast<void*>(eglGetProcAddress(what)); }; config.open_gl.make_resource_current = [](void* user_data) -> bool { auto host = static_cast<FlutterWindowsEngine*>(user_data); if (!host->egl_manager()) { return false; } return host->egl_manager()->resource_context()->MakeCurrent(); }; config.open_gl.gl_external_texture_frame_callback = [](void* user_data, int64_t texture_id, size_t width, size_t height, FlutterOpenGLTexture* texture) -> bool { auto host = static_cast<FlutterWindowsEngine*>(user_data); if (!host->texture_registrar()) { return false; } return host->texture_registrar()->PopulateTexture(texture_id, width, height, texture); }; return config; } // Creates and returns a FlutterRendererConfig that renders to the view (if any) // of a FlutterWindowsEngine, using software rasterization. // The user_data received by the render callbacks refers to the // FlutterWindowsEngine. FlutterRendererConfig GetSoftwareRendererConfig() { FlutterRendererConfig config = {}; config.type = kSoftware; config.software.struct_size = sizeof(config.software); config.software.surface_present_callback = [](void* user_data, const void* allocation, size_t row_bytes, size_t height) { FML_UNREACHABLE(); return false; }; return config; } // Converts a FlutterPlatformMessage to an equivalent FlutterDesktopMessage. static FlutterDesktopMessage ConvertToDesktopMessage( const FlutterPlatformMessage& engine_message) { FlutterDesktopMessage message = {}; message.struct_size = sizeof(message); message.channel = engine_message.channel; message.message = engine_message.message; message.message_size = engine_message.message_size; message.response_handle = engine_message.response_handle; return message; } // Converts a LanguageInfo struct to a FlutterLocale struct. |info| must outlive // the returned value, since the returned FlutterLocale has pointers into it. FlutterLocale CovertToFlutterLocale(const LanguageInfo& info) { FlutterLocale locale = {}; locale.struct_size = sizeof(FlutterLocale); locale.language_code = info.language.c_str(); if (!info.region.empty()) { locale.country_code = info.region.c_str(); } if (!info.script.empty()) { locale.script_code = info.script.c_str(); } return locale; } } // namespace FlutterWindowsEngine::FlutterWindowsEngine( const FlutterProjectBundle& project, std::shared_ptr<WindowsProcTable> windows_proc_table) : project_(std::make_unique<FlutterProjectBundle>(project)), windows_proc_table_(std::move(windows_proc_table)), aot_data_(nullptr, nullptr), lifecycle_manager_(std::make_unique<WindowsLifecycleManager>(this)) { if (windows_proc_table_ == nullptr) { windows_proc_table_ = std::make_shared<WindowsProcTable>(); } gl_ = egl::ProcTable::Create(); embedder_api_.struct_size = sizeof(FlutterEngineProcTable); FlutterEngineGetProcAddresses(&embedder_api_); task_runner_ = std::make_unique<TaskRunner>( embedder_api_.GetCurrentTime, [this](const auto* task) { if (!engine_) { FML_LOG(ERROR) << "Cannot post an engine task when engine is not running."; return; } if (embedder_api_.RunTask(engine_, task) != kSuccess) { FML_LOG(ERROR) << "Failed to post an engine task."; } }); // Set up the legacy structs backing the API handles. messenger_ = fml::RefPtr<FlutterDesktopMessenger>(new FlutterDesktopMessenger()); messenger_->SetEngine(this); plugin_registrar_ = std::make_unique<FlutterDesktopPluginRegistrar>(); plugin_registrar_->engine = this; messenger_wrapper_ = std::make_unique<BinaryMessengerImpl>(messenger_->ToRef()); message_dispatcher_ = std::make_unique<IncomingMessageDispatcher>(messenger_->ToRef()); texture_registrar_ = std::make_unique<FlutterWindowsTextureRegistrar>(this, gl_); // Check for impeller support. auto& switches = project_->GetSwitches(); enable_impeller_ = std::find(switches.begin(), switches.end(), "--enable-impeller=true") != switches.end(); egl_manager_ = egl::Manager::Create(enable_impeller_); window_proc_delegate_manager_ = std::make_unique<WindowProcDelegateManager>(); window_proc_delegate_manager_->RegisterTopLevelWindowProcDelegate( [](HWND hwnd, UINT msg, WPARAM wpar, LPARAM lpar, void* user_data, LRESULT* result) { BASE_DCHECK(user_data); FlutterWindowsEngine* that = static_cast<FlutterWindowsEngine*>(user_data); BASE_DCHECK(that->lifecycle_manager_); return that->lifecycle_manager_->WindowProc(hwnd, msg, wpar, lpar, result); }, static_cast<void*>(this)); // Set up internal channels. // TODO: Replace this with an embedder.h API. See // https://github.com/flutter/flutter/issues/71099 internal_plugin_registrar_ = std::make_unique<PluginRegistrar>(plugin_registrar_.get()); accessibility_plugin_ = std::make_unique<AccessibilityPlugin>(this); AccessibilityPlugin::SetUp(messenger_wrapper_.get(), accessibility_plugin_.get()); cursor_handler_ = std::make_unique<CursorHandler>(messenger_wrapper_.get(), this); platform_handler_ = std::make_unique<PlatformHandler>(messenger_wrapper_.get(), this); settings_plugin_ = std::make_unique<SettingsPlugin>(messenger_wrapper_.get(), task_runner_.get()); } FlutterWindowsEngine::~FlutterWindowsEngine() { messenger_->SetEngine(nullptr); Stop(); } void FlutterWindowsEngine::SetSwitches( const std::vector<std::string>& switches) { project_->SetSwitches(switches); } bool FlutterWindowsEngine::Run() { return Run(""); } bool FlutterWindowsEngine::Run(std::string_view entrypoint) { if (!project_->HasValidPaths()) { FML_LOG(ERROR) << "Missing or unresolvable paths to assets."; return false; } std::string assets_path_string = project_->assets_path().u8string(); std::string icu_path_string = project_->icu_path().u8string(); if (embedder_api_.RunsAOTCompiledDartCode()) { aot_data_ = project_->LoadAotData(embedder_api_); if (!aot_data_) { FML_LOG(ERROR) << "Unable to start engine without AOT data."; return false; } } // FlutterProjectArgs is expecting a full argv, so when processing it for // flags the first item is treated as the executable and ignored. Add a dummy // value so that all provided arguments are used. std::string executable_name = GetExecutableName(); std::vector<const char*> argv = {executable_name.c_str()}; std::vector<std::string> switches = project_->GetSwitches(); std::transform( switches.begin(), switches.end(), std::back_inserter(argv), [](const std::string& arg) -> const char* { return arg.c_str(); }); const std::vector<std::string>& entrypoint_args = project_->dart_entrypoint_arguments(); std::vector<const char*> entrypoint_argv; std::transform( entrypoint_args.begin(), entrypoint_args.end(), std::back_inserter(entrypoint_argv), [](const std::string& arg) -> const char* { return arg.c_str(); }); // Configure task runners. FlutterTaskRunnerDescription platform_task_runner = {}; platform_task_runner.struct_size = sizeof(FlutterTaskRunnerDescription); platform_task_runner.user_data = task_runner_.get(); platform_task_runner.runs_task_on_current_thread_callback = [](void* user_data) -> bool { return static_cast<TaskRunner*>(user_data)->RunsTasksOnCurrentThread(); }; platform_task_runner.post_task_callback = [](FlutterTask task, uint64_t target_time_nanos, void* user_data) -> void { static_cast<TaskRunner*>(user_data)->PostFlutterTask(task, target_time_nanos); }; FlutterCustomTaskRunners custom_task_runners = {}; custom_task_runners.struct_size = sizeof(FlutterCustomTaskRunners); custom_task_runners.platform_task_runner = &platform_task_runner; custom_task_runners.thread_priority_setter = &WindowsPlatformThreadPrioritySetter; FlutterProjectArgs args = {}; args.struct_size = sizeof(FlutterProjectArgs); args.shutdown_dart_vm_when_done = true; args.assets_path = assets_path_string.c_str(); args.icu_data_path = icu_path_string.c_str(); args.command_line_argc = static_cast<int>(argv.size()); args.command_line_argv = argv.empty() ? nullptr : argv.data(); // Fail if conflicting non-default entrypoints are specified in the method // argument and the project. // // TODO(cbracken): https://github.com/flutter/flutter/issues/109285 // The entrypoint method parameter should eventually be removed from this // method and only the entrypoint specified in project_ should be used. if (!project_->dart_entrypoint().empty() && !entrypoint.empty() && project_->dart_entrypoint() != entrypoint) { FML_LOG(ERROR) << "Conflicting entrypoints were specified in " "FlutterDesktopEngineProperties.dart_entrypoint and " "FlutterDesktopEngineRun(engine, entry_point). "; return false; } if (!entrypoint.empty()) { args.custom_dart_entrypoint = entrypoint.data(); } else if (!project_->dart_entrypoint().empty()) { args.custom_dart_entrypoint = project_->dart_entrypoint().c_str(); } args.dart_entrypoint_argc = static_cast<int>(entrypoint_argv.size()); args.dart_entrypoint_argv = entrypoint_argv.empty() ? nullptr : entrypoint_argv.data(); args.platform_message_callback = [](const FlutterPlatformMessage* engine_message, void* user_data) -> void { auto host = static_cast<FlutterWindowsEngine*>(user_data); return host->HandlePlatformMessage(engine_message); }; args.vsync_callback = [](void* user_data, intptr_t baton) -> void { auto host = static_cast<FlutterWindowsEngine*>(user_data); host->OnVsync(baton); }; args.on_pre_engine_restart_callback = [](void* user_data) { auto host = static_cast<FlutterWindowsEngine*>(user_data); host->OnPreEngineRestart(); }; args.update_semantics_callback2 = [](const FlutterSemanticsUpdate2* update, void* user_data) { auto host = static_cast<FlutterWindowsEngine*>(user_data); // TODO(loicsharma): Remove implicit view assumption. // https://github.com/flutter/flutter/issues/142845 auto view = host->view(kImplicitViewId); if (!view) { return; } auto accessibility_bridge = view->accessibility_bridge().lock(); if (!accessibility_bridge) { return; } for (size_t i = 0; i < update->node_count; i++) { const FlutterSemanticsNode2* node = update->nodes[i]; accessibility_bridge->AddFlutterSemanticsNodeUpdate(*node); } for (size_t i = 0; i < update->custom_action_count; i++) { const FlutterSemanticsCustomAction2* action = update->custom_actions[i]; accessibility_bridge->AddFlutterSemanticsCustomActionUpdate(*action); } accessibility_bridge->CommitUpdates(); }; args.root_isolate_create_callback = [](void* user_data) { auto host = static_cast<FlutterWindowsEngine*>(user_data); if (host->root_isolate_create_callback_) { host->root_isolate_create_callback_(); } }; args.channel_update_callback = [](const FlutterChannelUpdate* update, void* user_data) { auto host = static_cast<FlutterWindowsEngine*>(user_data); if (SAFE_ACCESS(update, channel, nullptr) != nullptr) { std::string channel_name(update->channel); host->OnChannelUpdate(std::move(channel_name), SAFE_ACCESS(update, listening, false)); } }; args.custom_task_runners = &custom_task_runners; if (!platform_view_plugin_) { platform_view_plugin_ = std::make_unique<PlatformViewPlugin>( messenger_wrapper_.get(), task_runner_.get()); } if (egl_manager_) { auto resolver = [](const char* name) -> void* { return reinterpret_cast<void*>(::eglGetProcAddress(name)); }; // TODO(schectman) Pass the platform view manager to the compositor // constructors: https://github.com/flutter/flutter/issues/143375 compositor_ = std::make_unique<CompositorOpenGL>(this, resolver); } else { compositor_ = std::make_unique<CompositorSoftware>(this); } FlutterCompositor compositor = {}; compositor.struct_size = sizeof(FlutterCompositor); compositor.user_data = this; compositor.create_backing_store_callback = [](const FlutterBackingStoreConfig* config, FlutterBackingStore* backing_store_out, void* user_data) -> bool { auto host = static_cast<FlutterWindowsEngine*>(user_data); return host->compositor_->CreateBackingStore(*config, backing_store_out); }; compositor.collect_backing_store_callback = [](const FlutterBackingStore* backing_store, void* user_data) -> bool { auto host = static_cast<FlutterWindowsEngine*>(user_data); return host->compositor_->CollectBackingStore(backing_store); }; compositor.present_view_callback = [](const FlutterPresentViewInfo* info) -> bool { auto host = static_cast<FlutterWindowsEngine*>(info->user_data); return host->compositor_->Present(info->view_id, info->layers, info->layers_count); }; args.compositor = &compositor; if (aot_data_) { args.aot_data = aot_data_.get(); } // The platform thread creates OpenGL contexts. These // must be released to be used by the engine's threads. FML_DCHECK(!egl_manager_ || !egl_manager_->HasContextCurrent()); FlutterRendererConfig renderer_config; if (enable_impeller_) { // Impeller does not support a Software backend. Avoid falling back and // confusing the engine on which renderer is selected. if (!egl_manager_) { FML_LOG(ERROR) << "Could not create surface manager. Impeller backend " "does not support software rendering."; return false; } renderer_config = GetOpenGLRendererConfig(); } else { renderer_config = egl_manager_ ? GetOpenGLRendererConfig() : GetSoftwareRendererConfig(); } auto result = embedder_api_.Run(FLUTTER_ENGINE_VERSION, &renderer_config, &args, this, &engine_); if (result != kSuccess || engine_ == nullptr) { FML_LOG(ERROR) << "Failed to start Flutter engine: error " << result; return false; } // Configure device frame rate displayed via devtools. FlutterEngineDisplay display = {}; display.struct_size = sizeof(FlutterEngineDisplay); display.display_id = 0; display.single_display = true; display.refresh_rate = 1.0 / (static_cast<double>(FrameInterval().count()) / 1000000000.0); std::vector<FlutterEngineDisplay> displays = {display}; embedder_api_.NotifyDisplayUpdate(engine_, kFlutterEngineDisplaysUpdateTypeStartup, displays.data(), displays.size()); SendSystemLocales(); SetLifecycleState(flutter::AppLifecycleState::kResumed); settings_plugin_->StartWatching(); settings_plugin_->SendSettings(); return true; } bool FlutterWindowsEngine::Stop() { if (engine_) { for (const auto& [callback, registrar] : plugin_registrar_destruction_callbacks_) { callback(registrar); } FlutterEngineResult result = embedder_api_.Shutdown(engine_); engine_ = nullptr; return (result == kSuccess); } return false; } std::unique_ptr<FlutterWindowsView> FlutterWindowsEngine::CreateView( std::unique_ptr<WindowBindingHandler> window) { // TODO(loicsharma): Remove implicit view assumption. // https://github.com/flutter/flutter/issues/142845 auto view = std::make_unique<FlutterWindowsView>( kImplicitViewId, this, std::move(window), windows_proc_table_); views_[kImplicitViewId] = view.get(); InitializeKeyboard(); return std::move(view); } void FlutterWindowsEngine::OnVsync(intptr_t baton) { std::chrono::nanoseconds current_time = std::chrono::nanoseconds(embedder_api_.GetCurrentTime()); std::chrono::nanoseconds frame_interval = FrameInterval(); auto next = SnapToNextTick(current_time, start_time_, frame_interval); embedder_api_.OnVsync(engine_, baton, next.count(), (next + frame_interval).count()); } std::chrono::nanoseconds FlutterWindowsEngine::FrameInterval() { if (frame_interval_override_.has_value()) { return frame_interval_override_.value(); } uint64_t interval = 16600000; DWM_TIMING_INFO timing_info = {}; timing_info.cbSize = sizeof(timing_info); HRESULT result = DwmGetCompositionTimingInfo(NULL, &timing_info); if (result == S_OK && timing_info.rateRefresh.uiDenominator > 0 && timing_info.rateRefresh.uiNumerator > 0) { interval = static_cast<double>(timing_info.rateRefresh.uiDenominator * 1000000000.0) / static_cast<double>(timing_info.rateRefresh.uiNumerator); } return std::chrono::nanoseconds(interval); } FlutterWindowsView* FlutterWindowsEngine::view(FlutterViewId view_id) const { auto iterator = views_.find(view_id); if (iterator == views_.end()) { return nullptr; } return iterator->second; } // Returns the currently configured Plugin Registrar. FlutterDesktopPluginRegistrarRef FlutterWindowsEngine::GetRegistrar() { return plugin_registrar_.get(); } void FlutterWindowsEngine::AddPluginRegistrarDestructionCallback( FlutterDesktopOnPluginRegistrarDestroyed callback, FlutterDesktopPluginRegistrarRef registrar) { plugin_registrar_destruction_callbacks_[callback] = registrar; } void FlutterWindowsEngine::SendWindowMetricsEvent( const FlutterWindowMetricsEvent& event) { if (engine_) { embedder_api_.SendWindowMetricsEvent(engine_, &event); } } void FlutterWindowsEngine::SendPointerEvent(const FlutterPointerEvent& event) { if (engine_) { embedder_api_.SendPointerEvent(engine_, &event, 1); } } void FlutterWindowsEngine::SendKeyEvent(const FlutterKeyEvent& event, FlutterKeyEventCallback callback, void* user_data) { if (engine_) { embedder_api_.SendKeyEvent(engine_, &event, callback, user_data); } } bool FlutterWindowsEngine::SendPlatformMessage( const char* channel, const uint8_t* message, const size_t message_size, const FlutterDesktopBinaryReply reply, void* user_data) { FlutterPlatformMessageResponseHandle* response_handle = nullptr; if (reply != nullptr && user_data != nullptr) { FlutterEngineResult result = embedder_api_.PlatformMessageCreateResponseHandle( engine_, reply, user_data, &response_handle); if (result != kSuccess) { FML_LOG(ERROR) << "Failed to create response handle"; return false; } } FlutterPlatformMessage platform_message = { sizeof(FlutterPlatformMessage), channel, message, message_size, response_handle, }; FlutterEngineResult message_result = embedder_api_.SendPlatformMessage(engine_, &platform_message); if (response_handle != nullptr) { embedder_api_.PlatformMessageReleaseResponseHandle(engine_, response_handle); } return message_result == kSuccess; } void FlutterWindowsEngine::SendPlatformMessageResponse( const FlutterDesktopMessageResponseHandle* handle, const uint8_t* data, size_t data_length) { embedder_api_.SendPlatformMessageResponse(engine_, handle, data, data_length); } void FlutterWindowsEngine::HandlePlatformMessage( const FlutterPlatformMessage* engine_message) { if (engine_message->struct_size != sizeof(FlutterPlatformMessage)) { FML_LOG(ERROR) << "Invalid message size received. Expected: " << sizeof(FlutterPlatformMessage) << " but received " << engine_message->struct_size; return; } auto message = ConvertToDesktopMessage(*engine_message); message_dispatcher_->HandleMessage(message, [this] {}, [this] {}); } void FlutterWindowsEngine::ReloadSystemFonts() { embedder_api_.ReloadSystemFonts(engine_); } void FlutterWindowsEngine::ScheduleFrame() { embedder_api_.ScheduleFrame(engine_); } void FlutterWindowsEngine::SetNextFrameCallback(fml::closure callback) { next_frame_callback_ = std::move(callback); embedder_api_.SetNextFrameCallback( engine_, [](void* user_data) { // Embedder callback runs on raster thread. Switch back to platform // thread. FlutterWindowsEngine* self = static_cast<FlutterWindowsEngine*>(user_data); self->task_runner_->PostTask(std::move(self->next_frame_callback_)); }, this); } void FlutterWindowsEngine::SetLifecycleState(flutter::AppLifecycleState state) { if (lifecycle_manager_) { lifecycle_manager_->SetLifecycleState(state); } } void FlutterWindowsEngine::SendSystemLocales() { std::vector<LanguageInfo> languages = GetPreferredLanguageInfo(*windows_proc_table_); std::vector<FlutterLocale> flutter_locales; flutter_locales.reserve(languages.size()); for (const auto& info : languages) { flutter_locales.push_back(CovertToFlutterLocale(info)); } // Convert the locale list to the locale pointer list that must be provided. std::vector<const FlutterLocale*> flutter_locale_list; flutter_locale_list.reserve(flutter_locales.size()); std::transform(flutter_locales.begin(), flutter_locales.end(), std::back_inserter(flutter_locale_list), [](const auto& arg) -> const auto* { return &arg; }); embedder_api_.UpdateLocales(engine_, flutter_locale_list.data(), flutter_locale_list.size()); } void FlutterWindowsEngine::InitializeKeyboard() { if (views_.empty()) { FML_LOG(ERROR) << "Cannot initialize keyboard on Windows headless mode."; } auto internal_plugin_messenger = internal_plugin_registrar_->messenger(); KeyboardKeyEmbedderHandler::GetKeyStateHandler get_key_state = GetKeyState; KeyboardKeyEmbedderHandler::MapVirtualKeyToScanCode map_vk_to_scan = [](UINT virtual_key, bool extended) { return MapVirtualKey(virtual_key, extended ? MAPVK_VK_TO_VSC_EX : MAPVK_VK_TO_VSC); }; keyboard_key_handler_ = std::move(CreateKeyboardKeyHandler( internal_plugin_messenger, get_key_state, map_vk_to_scan)); text_input_plugin_ = std::move(CreateTextInputPlugin(internal_plugin_messenger)); } std::unique_ptr<KeyboardHandlerBase> FlutterWindowsEngine::CreateKeyboardKeyHandler( BinaryMessenger* messenger, KeyboardKeyEmbedderHandler::GetKeyStateHandler get_key_state, KeyboardKeyEmbedderHandler::MapVirtualKeyToScanCode map_vk_to_scan) { auto keyboard_key_handler = std::make_unique<KeyboardKeyHandler>(messenger); keyboard_key_handler->AddDelegate( std::make_unique<KeyboardKeyEmbedderHandler>( [this](const FlutterKeyEvent& event, FlutterKeyEventCallback callback, void* user_data) { return SendKeyEvent(event, callback, user_data); }, get_key_state, map_vk_to_scan)); keyboard_key_handler->AddDelegate( std::make_unique<KeyboardKeyChannelHandler>(messenger)); keyboard_key_handler->InitKeyboardChannel(); return keyboard_key_handler; } std::unique_ptr<TextInputPlugin> FlutterWindowsEngine::CreateTextInputPlugin( BinaryMessenger* messenger) { return std::make_unique<TextInputPlugin>(messenger, this); } bool FlutterWindowsEngine::RegisterExternalTexture(int64_t texture_id) { return (embedder_api_.RegisterExternalTexture(engine_, texture_id) == kSuccess); } bool FlutterWindowsEngine::UnregisterExternalTexture(int64_t texture_id) { return (embedder_api_.UnregisterExternalTexture(engine_, texture_id) == kSuccess); } bool FlutterWindowsEngine::MarkExternalTextureFrameAvailable( int64_t texture_id) { return (embedder_api_.MarkExternalTextureFrameAvailable( engine_, texture_id) == kSuccess); } bool FlutterWindowsEngine::PostRasterThreadTask(fml::closure callback) const { struct Captures { fml::closure callback; }; auto captures = new Captures(); captures->callback = std::move(callback); if (embedder_api_.PostRenderThreadTask( engine_, [](void* opaque) { auto captures = reinterpret_cast<Captures*>(opaque); captures->callback(); delete captures; }, captures) == kSuccess) { return true; } delete captures; return false; } bool FlutterWindowsEngine::DispatchSemanticsAction( uint64_t target, FlutterSemanticsAction action, fml::MallocMapping data) { return (embedder_api_.DispatchSemanticsAction(engine_, target, action, data.GetMapping(), data.GetSize()) == kSuccess); } void FlutterWindowsEngine::UpdateSemanticsEnabled(bool enabled) { if (engine_ && semantics_enabled_ != enabled) { semantics_enabled_ = enabled; embedder_api_.UpdateSemanticsEnabled(engine_, enabled); for (auto iterator = views_.begin(); iterator != views_.end(); iterator++) { iterator->second->UpdateSemanticsEnabled(enabled); } } } void FlutterWindowsEngine::OnPreEngineRestart() { // Reset the keyboard's state on hot restart. if (!views_.empty()) { InitializeKeyboard(); } } std::string FlutterWindowsEngine::GetExecutableName() const { std::pair<bool, std::string> result = fml::paths::GetExecutablePath(); if (result.first) { const std::string& executable_path = result.second; size_t last_separator = executable_path.find_last_of("/\\"); if (last_separator == std::string::npos || last_separator == executable_path.size() - 1) { return executable_path; } return executable_path.substr(last_separator + 1); } return "Flutter"; } void FlutterWindowsEngine::UpdateAccessibilityFeatures() { UpdateHighContrastMode(); } void FlutterWindowsEngine::UpdateHighContrastMode() { high_contrast_enabled_ = windows_proc_table_->GetHighContrastEnabled(); SendAccessibilityFeatures(); settings_plugin_->UpdateHighContrastMode(high_contrast_enabled_); } void FlutterWindowsEngine::SendAccessibilityFeatures() { int flags = 0; if (high_contrast_enabled_) { flags |= FlutterAccessibilityFeature::kFlutterAccessibilityFeatureHighContrast; } embedder_api_.UpdateAccessibilityFeatures( engine_, static_cast<FlutterAccessibilityFeature>(flags)); } void FlutterWindowsEngine::RequestApplicationQuit(HWND hwnd, WPARAM wparam, LPARAM lparam, AppExitType exit_type) { platform_handler_->RequestAppExit(hwnd, wparam, lparam, exit_type, 0); } void FlutterWindowsEngine::OnQuit(std::optional<HWND> hwnd, std::optional<WPARAM> wparam, std::optional<LPARAM> lparam, UINT exit_code) { lifecycle_manager_->Quit(hwnd, wparam, lparam, exit_code); } void FlutterWindowsEngine::OnDwmCompositionChanged() { for (auto iterator = views_.begin(); iterator != views_.end(); iterator++) { iterator->second->OnDwmCompositionChanged(); } } void FlutterWindowsEngine::OnWindowStateEvent(HWND hwnd, WindowStateEvent event) { lifecycle_manager_->OnWindowStateEvent(hwnd, event); } std::optional<LRESULT> FlutterWindowsEngine::ProcessExternalWindowMessage( HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) { if (lifecycle_manager_) { return lifecycle_manager_->ExternalWindowMessage(hwnd, message, wparam, lparam); } return std::nullopt; } void FlutterWindowsEngine::OnChannelUpdate(std::string name, bool listening) { if (name == "flutter/platform" && listening) { lifecycle_manager_->BeginProcessingExit(); } else if (name == "flutter/lifecycle" && listening) { lifecycle_manager_->BeginProcessingLifecycle(); } } } // namespace flutter
engine/shell/platform/windows/flutter_windows_engine.cc/0
{ "file_path": "engine/shell/platform/windows/flutter_windows_engine.cc", "repo_id": "engine", "token_count": 12086 }
381
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/windows/keyboard_key_embedder_handler.h" #include <windows.h> #include <chrono> #include <string> #include "flutter/fml/logging.h" #include "flutter/shell/platform/windows/keyboard_utils.h" namespace flutter { namespace { // An arbitrary size for the character cache in bytes. // // It should hold a UTF-32 character encoded in UTF-8 as well as the trailing // '\0'. constexpr size_t kCharacterCacheSize = 8; constexpr SHORT kStateMaskToggled = 0x01; constexpr SHORT kStateMaskPressed = 0x80; const char* empty_character = ""; // Get some bits of the char, from the start'th bit from the right (excluded) // to the end'th bit from the right (included). // // For example, _GetBit(0x1234, 8, 4) => 0x3. char _GetBit(char32_t ch, size_t start, size_t end) { return (ch >> end) & ((1 << (start - end)) - 1); } } // namespace std::string ConvertChar32ToUtf8(char32_t ch) { std::string result; FML_DCHECK(0 <= ch && ch <= 0x10FFFF) << "Character out of range"; if (ch <= 0x007F) { result.push_back(ch); } else if (ch <= 0x07FF) { result.push_back(0b11000000 + _GetBit(ch, 11, 6)); result.push_back(0b10000000 + _GetBit(ch, 6, 0)); } else if (ch <= 0xFFFF) { result.push_back(0b11100000 + _GetBit(ch, 16, 12)); result.push_back(0b10000000 + _GetBit(ch, 12, 6)); result.push_back(0b10000000 + _GetBit(ch, 6, 0)); } else { result.push_back(0b11110000 + _GetBit(ch, 21, 18)); result.push_back(0b10000000 + _GetBit(ch, 18, 12)); result.push_back(0b10000000 + _GetBit(ch, 12, 6)); result.push_back(0b10000000 + _GetBit(ch, 6, 0)); } return result; } KeyboardKeyEmbedderHandler::KeyboardKeyEmbedderHandler( SendEventHandler send_event, GetKeyStateHandler get_key_state, MapVirtualKeyToScanCode map_virtual_key_to_scan_code) : perform_send_event_(send_event), get_key_state_(get_key_state), response_id_(1) { InitCriticalKeys(map_virtual_key_to_scan_code); } KeyboardKeyEmbedderHandler::~KeyboardKeyEmbedderHandler() = default; static bool isEasciiPrintable(int codeUnit) { return (codeUnit <= 0x7f && codeUnit >= 0x20) || (codeUnit <= 0xff && codeUnit >= 0x80); } // Converts upper letters to lower letters in ASCII and extended ASCII, and // returns as-is otherwise. // // Independent of locale. static uint64_t toLower(uint64_t n) { constexpr uint64_t lower_a = 0x61; constexpr uint64_t upper_a = 0x41; constexpr uint64_t upper_z = 0x5a; constexpr uint64_t lower_a_grave = 0xe0; constexpr uint64_t upper_a_grave = 0xc0; constexpr uint64_t upper_thorn = 0xde; constexpr uint64_t division = 0xf7; // ASCII range. if (n >= upper_a && n <= upper_z) { return n - upper_a + lower_a; } // EASCII range. if (n >= upper_a_grave && n <= upper_thorn && n != division) { return n - upper_a_grave + lower_a_grave; } return n; } // Transform scancodes sent by windows to scancodes written in Chromium spec. static uint16_t normalizeScancode(int windowsScanCode, bool extended) { // In Chromium spec the extended bit is shown as 0xe000 bit, // e.g. PageUp is represented as 0xe049. return (windowsScanCode & 0xff) | (extended ? 0xe000 : 0); } uint64_t KeyboardKeyEmbedderHandler::ApplyPlaneToId(uint64_t id, uint64_t plane) { return (id & valueMask) | plane; } uint64_t KeyboardKeyEmbedderHandler::GetPhysicalKey(int scancode, bool extended) { int chromiumScancode = normalizeScancode(scancode, extended); auto resultIt = windowsToPhysicalMap_.find(chromiumScancode); if (resultIt != windowsToPhysicalMap_.end()) return resultIt->second; return ApplyPlaneToId(scancode, windowsPlane); } uint64_t KeyboardKeyEmbedderHandler::GetLogicalKey(int key, bool extended, int scancode) { if (key == VK_PROCESSKEY) { return VK_PROCESSKEY; } // Normally logical keys should only be derived from key codes, but since some // key codes are either 0 or ambiguous (multiple keys using the same key // code), these keys are resolved by scan codes. auto numpadIter = scanCodeToLogicalMap_.find(normalizeScancode(scancode, extended)); if (numpadIter != scanCodeToLogicalMap_.cend()) return numpadIter->second; // Check if the keyCode is one we know about and have a mapping for. auto logicalIt = windowsToLogicalMap_.find(key); if (logicalIt != windowsToLogicalMap_.cend()) return logicalIt->second; // Upper case letters should be normalized into lower case letters. if (isEasciiPrintable(key)) { return ApplyPlaneToId(toLower(key), unicodePlane); } return ApplyPlaneToId(toLower(key), windowsPlane); } void KeyboardKeyEmbedderHandler::KeyboardHookImpl( int key, int scancode, int action, char32_t character, bool extended, bool was_down, std::function<void(bool)> callback) { const uint64_t physical_key = GetPhysicalKey(scancode, extended); const uint64_t logical_key = GetLogicalKey(key, extended, scancode); FML_DCHECK(action == WM_KEYDOWN || action == WM_KEYUP || action == WM_SYSKEYDOWN || action == WM_SYSKEYUP); auto last_logical_record_iter = pressingRecords_.find(physical_key); bool had_record = last_logical_record_iter != pressingRecords_.end(); uint64_t last_logical_record = had_record ? last_logical_record_iter->second : 0; // The logical key for the current "tap sequence". // // Key events are formed in tap sequences: down, repeats, up. The logical key // stays consistent throughout a tap sequence, which is this value. uint64_t sequence_logical_key = had_record ? last_logical_record : logical_key; if (sequence_logical_key == VK_PROCESSKEY) { // VK_PROCESSKEY means that the key press is used by an IME. These key // presses are considered handled and not sent to Flutter. These events must // be filtered by result_logical_key because the key up event of such // presses uses the "original" logical key. callback(true); return; } const bool is_event_down = action == WM_KEYDOWN || action == WM_SYSKEYDOWN; bool event_key_can_be_repeat = true; UpdateLastSeenCriticalKey(key, physical_key, sequence_logical_key); // Synchronize the toggled states of critical keys (such as whether CapsLocks // is enabled). Toggled states can only be changed upon a down event, so if // the recorded toggled state does not match the true state, this function // will synthesize (an up event if the key is recorded pressed, then) a down // event. // // After this function, all critical keys will have their toggled state // updated to the true state, while the critical keys whose toggled state have // been changed will be pressed regardless of their true pressed state. // Updating the pressed state will be done by // SynchronizeCriticalPressedStates. SynchronizeCriticalToggledStates(key, is_event_down, &event_key_can_be_repeat); // Synchronize the pressed states of critical keys (such as whether CapsLocks // is pressed). // // After this function, all critical keys except for the target key will have // their toggled state and pressed state matched with their true states. The // target key's pressed state will be updated immediately after this. SynchronizeCriticalPressedStates(key, physical_key, is_event_down, event_key_can_be_repeat); // Reassess the last logical record in case pressingRecords_ was modified // by the above synchronization methods. last_logical_record_iter = pressingRecords_.find(physical_key); had_record = last_logical_record_iter != pressingRecords_.end(); last_logical_record = had_record ? last_logical_record_iter->second : 0; // The resulting event's `type`. FlutterKeyEventType type; character = UndeadChar(character); char character_bytes[kCharacterCacheSize]; // What pressingRecords_[physical_key] should be after the KeyboardHookImpl // returns (0 if the entry should be removed). uint64_t eventual_logical_record; uint64_t result_logical_key; if (is_event_down) { if (had_record) { if (was_down) { // A normal repeated key. type = kFlutterKeyEventTypeRepeat; FML_DCHECK(had_record); ConvertUtf32ToUtf8_(character_bytes, character); eventual_logical_record = last_logical_record; result_logical_key = last_logical_record; } else { // A non-repeated key has been pressed that has the exact physical key // as a currently pressed one, usually indicating multiple keyboards are // pressing keys with the same physical key, or the up event was lost // during a loss of focus. The down event is ignored. callback(true); return; } } else { // A normal down event (whether the system event is a repeat or not). type = kFlutterKeyEventTypeDown; FML_DCHECK(!had_record); ConvertUtf32ToUtf8_(character_bytes, character); eventual_logical_record = logical_key; result_logical_key = logical_key; } } else { // isPhysicalDown is false if (last_logical_record == 0) { // The physical key has been released before. It might indicate a missed // event due to loss of focus, or multiple keyboards pressed keys with the // same physical key. Ignore the up event. callback(true); return; } else { // A normal up event. type = kFlutterKeyEventTypeUp; FML_DCHECK(had_record); // Up events never have character. character_bytes[0] = '\0'; eventual_logical_record = 0; result_logical_key = last_logical_record; } } if (eventual_logical_record != 0) { pressingRecords_[physical_key] = eventual_logical_record; } else { auto record_iter = pressingRecords_.find(physical_key); // Assert this in debug mode. But in cases that it doesn't satisfy // (such as due to a bug), make sure the `erase` is only called // with a valid value to avoid crashing. if (record_iter != pressingRecords_.end()) { pressingRecords_.erase(record_iter); } else { FML_DCHECK(false); } } FlutterKeyEvent key_data{ .struct_size = sizeof(FlutterKeyEvent), .timestamp = static_cast<double>( std::chrono::duration_cast<std::chrono::microseconds>( std::chrono::high_resolution_clock::now().time_since_epoch()) .count()), .type = type, .physical = physical_key, .logical = result_logical_key, .character = character_bytes, .synthesized = false, }; response_id_ += 1; uint64_t response_id = response_id_; PendingResponse pending{ .callback = [this, callback = std::move(callback)](bool handled, uint64_t response_id) { auto found = pending_responses_.find(response_id); if (found != pending_responses_.end()) { pending_responses_.erase(found); } callback(handled); }, .response_id = response_id, }; auto pending_ptr = std::make_unique<PendingResponse>(std::move(pending)); pending_responses_[response_id] = std::move(pending_ptr); SendEvent(key_data, KeyboardKeyEmbedderHandler::HandleResponse, reinterpret_cast<void*>(pending_responses_[response_id].get())); // Post-event synchronization. It is useful in cases where the true pressing // state does not match the event type. For example, a CapsLock down event is // received despite that GetKeyState says that CapsLock is not pressed. In // such case, post-event synchronization will synthesize a CapsLock up event // after the main event. SynchronizeCriticalPressedStates(key, physical_key, is_event_down, event_key_can_be_repeat); } void KeyboardKeyEmbedderHandler::KeyboardHook( int key, int scancode, int action, char32_t character, bool extended, bool was_down, std::function<void(bool)> callback) { sent_any_events = false; KeyboardHookImpl(key, scancode, action, character, extended, was_down, std::move(callback)); if (!sent_any_events) { FlutterKeyEvent empty_event{ .struct_size = sizeof(FlutterKeyEvent), .timestamp = static_cast<double>( std::chrono::duration_cast<std::chrono::microseconds>( std::chrono::high_resolution_clock::now().time_since_epoch()) .count()), .type = kFlutterKeyEventTypeDown, .physical = 0, .logical = 0, .character = empty_character, .synthesized = false, }; SendEvent(empty_event, nullptr, nullptr); } } std::map<uint64_t, uint64_t> KeyboardKeyEmbedderHandler::GetPressedState() { return pressingRecords_; } void KeyboardKeyEmbedderHandler::UpdateLastSeenCriticalKey( int virtual_key, uint64_t physical_key, uint64_t logical_key) { auto found = critical_keys_.find(virtual_key); if (found != critical_keys_.end()) { found->second.physical_key = physical_key; found->second.logical_key = logical_key; } } void KeyboardKeyEmbedderHandler::SynchronizeCriticalToggledStates( int event_virtual_key, bool is_event_down, bool* event_key_can_be_repeat) { // NowState ----------------> PreEventState --------------> TrueState // Synchronization Event for (auto& kv : critical_keys_) { UINT virtual_key = kv.first; CriticalKey& key_info = kv.second; if (key_info.physical_key == 0) { // Never seen this key. continue; } FML_DCHECK(key_info.logical_key != 0); // Check toggling state first, because it might alter pressing state. if (key_info.check_toggled) { const bool target_is_pressed = pressingRecords_.find(key_info.physical_key) != pressingRecords_.end(); // The togglable keys observe a 4-phase cycle: // // Phase# 0 1 2 3 // Event Down Up Down Up // Pressed 0 1 0 1 // Toggled 0 1 1 0 const bool true_toggled = get_key_state_(virtual_key) & kStateMaskToggled; bool pre_event_toggled = true_toggled; // Check if the main event's key is the key being checked. If it's the // non-repeat down event, toggle the state. if (virtual_key == event_virtual_key && !target_is_pressed && is_event_down) { pre_event_toggled = !pre_event_toggled; } if (key_info.toggled_on != pre_event_toggled) { // If the key is pressed, release it first. if (target_is_pressed) { SendEvent(SynthesizeSimpleEvent( kFlutterKeyEventTypeUp, key_info.physical_key, key_info.logical_key, empty_character), nullptr, nullptr); } // Synchronizing toggle state always ends with the key being pressed. pressingRecords_[key_info.physical_key] = key_info.logical_key; SendEvent(SynthesizeSimpleEvent(kFlutterKeyEventTypeDown, key_info.physical_key, key_info.logical_key, empty_character), nullptr, nullptr); *event_key_can_be_repeat = false; } key_info.toggled_on = true_toggled; } } } void KeyboardKeyEmbedderHandler::SynchronizeCriticalPressedStates( int event_virtual_key, int event_physical_key, bool is_event_down, bool event_key_can_be_repeat) { // During an incoming event, there might be a synthesized Flutter event for // each key of each pressing goal, followed by an eventual main Flutter // event. // // NowState ----------------> PreEventState --------------> TrueState // Synchronization Event // // The goal of the synchronization algorithm is to derive a pre-event state // that can satisfy the true state (`true_pressed`) after the event, and that // requires as few synthesized events based on the current state // (`now_pressed`) as possible. for (auto& kv : critical_keys_) { UINT virtual_key = kv.first; CriticalKey& key_info = kv.second; if (key_info.physical_key == 0) { // Never seen this key. continue; } FML_DCHECK(key_info.logical_key != 0); if (key_info.check_pressed) { SHORT true_pressed = get_key_state_(virtual_key) & kStateMaskPressed; auto pressing_record_iter = pressingRecords_.find(key_info.physical_key); bool now_pressed = pressing_record_iter != pressingRecords_.end(); bool pre_event_pressed = true_pressed; // Check if the main event is the key being checked to get the correct // target state. if (is_event_down) { // For down events, this key is the event key if they have the same // virtual key, because virtual key represents "functionality." // // In that case, normally Flutter should synthesize nothing since the // resulting event can adapt to the current state by dispatching either // a down or a repeat event. However, in certain cases (when Flutter has // just synchronized the key's toggling state) the event must not be a // repeat event. if (virtual_key == event_virtual_key) { if (event_key_can_be_repeat) { continue; } else { pre_event_pressed = false; } } } else { // For up events, this key is the event key if they have the same // physical key, because it is necessary to ensure that the physical // key is correctly released. // // In that case, although the previous state should be pressed, don't // synthesize a down event even if it's not. The later code will handle // such cases by skipping abrupt up events. Obviously don't synthesize // up events either. if (event_physical_key == key_info.physical_key) { continue; } } if (now_pressed != pre_event_pressed) { if (now_pressed) { pressingRecords_.erase(pressing_record_iter); } else { pressingRecords_[key_info.physical_key] = key_info.logical_key; } const char* empty_character = ""; SendEvent( SynthesizeSimpleEvent( now_pressed ? kFlutterKeyEventTypeUp : kFlutterKeyEventTypeDown, key_info.physical_key, key_info.logical_key, empty_character), nullptr, nullptr); } } } } void KeyboardKeyEmbedderHandler::SyncModifiersIfNeeded(int modifiers_state) { // TODO(bleroux): consider exposing these constants in flutter_key_map.g.cc? const uint64_t physical_shift_left = windowsToPhysicalMap_.at(kScanCodeShiftLeft); const uint64_t physical_shift_right = windowsToPhysicalMap_.at(kScanCodeShiftRight); const uint64_t logical_shift_left = windowsToLogicalMap_.at(kKeyCodeShiftLeft); const uint64_t physical_control_left = windowsToPhysicalMap_.at(kScanCodeControlLeft); const uint64_t physical_control_right = windowsToPhysicalMap_.at(kScanCodeControlRight); const uint64_t logical_control_left = windowsToLogicalMap_.at(kKeyCodeControlLeft); bool shift_pressed = (modifiers_state & kShift) != 0; SynthesizeIfNeeded(physical_shift_left, physical_shift_right, logical_shift_left, shift_pressed); bool control_pressed = (modifiers_state & kControl) != 0; SynthesizeIfNeeded(physical_control_left, physical_control_right, logical_control_left, control_pressed); } void KeyboardKeyEmbedderHandler::SynthesizeIfNeeded(uint64_t physical_left, uint64_t physical_right, uint64_t logical_left, bool is_pressed) { auto pressing_record_iter_left = pressingRecords_.find(physical_left); bool left_pressed = pressing_record_iter_left != pressingRecords_.end(); auto pressing_record_iter_right = pressingRecords_.find(physical_right); bool right_pressed = pressing_record_iter_right != pressingRecords_.end(); bool already_pressed = left_pressed || right_pressed; bool synthesize_down = is_pressed && !already_pressed; bool synthesize_up = !is_pressed && already_pressed; if (synthesize_down) { SendSynthesizeDownEvent(physical_left, logical_left); } if (synthesize_up && left_pressed) { uint64_t known_logical = pressing_record_iter_left->second; SendSynthesizeUpEvent(physical_left, known_logical); } if (synthesize_up && right_pressed) { uint64_t known_logical = pressing_record_iter_right->second; SendSynthesizeUpEvent(physical_right, known_logical); } } void KeyboardKeyEmbedderHandler::SendSynthesizeDownEvent(uint64_t physical, uint64_t logical) { SendEvent( SynthesizeSimpleEvent(kFlutterKeyEventTypeDown, physical, logical, ""), nullptr, nullptr); pressingRecords_[physical] = logical; }; void KeyboardKeyEmbedderHandler::SendSynthesizeUpEvent(uint64_t physical, uint64_t logical) { SendEvent( SynthesizeSimpleEvent(kFlutterKeyEventTypeUp, physical, logical, ""), nullptr, nullptr); pressingRecords_.erase(physical); }; void KeyboardKeyEmbedderHandler::HandleResponse(bool handled, void* user_data) { PendingResponse* pending = reinterpret_cast<PendingResponse*>(user_data); auto callback = std::move(pending->callback); callback(handled, pending->response_id); } void KeyboardKeyEmbedderHandler::InitCriticalKeys( MapVirtualKeyToScanCode map_virtual_key_to_scan_code) { auto createCheckedKey = [this, &map_virtual_key_to_scan_code]( UINT virtual_key, bool extended, bool check_pressed, bool check_toggled) -> CriticalKey { UINT scan_code = map_virtual_key_to_scan_code(virtual_key, extended); return CriticalKey{ .physical_key = GetPhysicalKey(scan_code, extended), .logical_key = GetLogicalKey(virtual_key, extended, scan_code), .check_pressed = check_pressed || check_toggled, .check_toggled = check_toggled, .toggled_on = check_toggled ? !!(get_key_state_(virtual_key) & kStateMaskToggled) : false, }; }; critical_keys_.emplace(VK_LSHIFT, createCheckedKey(VK_LSHIFT, false, true, false)); critical_keys_.emplace(VK_RSHIFT, createCheckedKey(VK_RSHIFT, false, true, false)); critical_keys_.emplace(VK_LCONTROL, createCheckedKey(VK_LCONTROL, false, true, false)); critical_keys_.emplace(VK_RCONTROL, createCheckedKey(VK_RCONTROL, true, true, false)); critical_keys_.emplace(VK_LMENU, createCheckedKey(VK_LMENU, false, true, false)); critical_keys_.emplace(VK_RMENU, createCheckedKey(VK_RMENU, true, true, false)); critical_keys_.emplace(VK_LWIN, createCheckedKey(VK_LWIN, true, true, false)); critical_keys_.emplace(VK_RWIN, createCheckedKey(VK_RWIN, true, true, false)); critical_keys_.emplace(VK_CAPITAL, createCheckedKey(VK_CAPITAL, false, true, true)); critical_keys_.emplace(VK_SCROLL, createCheckedKey(VK_SCROLL, false, true, true)); critical_keys_.emplace(VK_NUMLOCK, createCheckedKey(VK_NUMLOCK, true, true, true)); } void KeyboardKeyEmbedderHandler::ConvertUtf32ToUtf8_(char* out, char32_t ch) { if (ch == 0) { out[0] = '\0'; return; } std::string result = ConvertChar32ToUtf8(ch); strcpy_s(out, kCharacterCacheSize, result.c_str()); } FlutterKeyEvent KeyboardKeyEmbedderHandler::SynthesizeSimpleEvent( FlutterKeyEventType type, uint64_t physical, uint64_t logical, const char* character) { return FlutterKeyEvent{ .struct_size = sizeof(FlutterKeyEvent), .timestamp = static_cast<double>( std::chrono::duration_cast<std::chrono::microseconds>( std::chrono::high_resolution_clock::now().time_since_epoch()) .count()), .type = type, .physical = physical, .logical = logical, .character = character, .synthesized = true, }; } void KeyboardKeyEmbedderHandler::SendEvent(const FlutterKeyEvent& event, FlutterKeyEventCallback callback, void* user_data) { sent_any_events = true; perform_send_event_(event, callback, user_data); } } // namespace flutter
engine/shell/platform/windows/keyboard_key_embedder_handler.cc/0
{ "file_path": "engine/shell/platform/windows/keyboard_key_embedder_handler.cc", "repo_id": "engine", "token_count": 10201 }
382
// 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_SHELL_PLATFORM_WINDOWS_PLATFORM_VIEW_MANAGER_H_ #define FLUTTER_SHELL_PLATFORM_WINDOWS_PLATFORM_VIEW_MANAGER_H_ #include <memory> #include "flutter/shell/platform/common/client_wrapper/include/flutter/method_channel.h" #include "flutter/shell/platform/windows/flutter_windows_internal.h" #include "flutter/shell/platform/windows/task_runner.h" namespace flutter { // Possible reasons for change of keyboard focus. enum class FocusChangeDirection { kProgrammatic, // Un-directed focus change. kForward, // Keyboard focus moves forwards, e.g. TAB key. kBackward // Keyboard focus moves backwards, e.g. Shift+TAB. }; // The platform method handler for platform view related communication between // the engine and the framework. This base class is derived by a concrete class // (i.e. PlatformViewPlugin) to provide implementation of its abstract virtual // methods. class PlatformViewManager { public: PlatformViewManager(BinaryMessenger* binary_messenger); virtual ~PlatformViewManager(); // Add a new platform view instance to be lazily instantiated when it is next // composited. The manager will invoke Success when this method returns true, // and invoke Error otherwise. virtual bool AddPlatformView(PlatformViewId id, std::string_view type_name) = 0; // The framework may invoke this method when keyboard focus must be given to // the platform view. The manager will invoke Success when this method returns // true, and invoke Error otherwise. virtual bool FocusPlatformView(PlatformViewId id, FocusChangeDirection direction, bool focus) = 0; private: std::unique_ptr<MethodChannel<EncodableValue>> channel_; }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_WINDOWS_PLATFORM_VIEW_MANAGER_H_
engine/shell/platform/windows/platform_view_manager.h/0
{ "file_path": "engine/shell/platform/windows/platform_view_manager.h", "repo_id": "engine", "token_count": 651 }
383
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/windows/task_runner_window.h" #include <algorithm> #include "flutter/fml/logging.h" namespace flutter { TaskRunnerWindow::TaskRunnerWindow() { WNDCLASS window_class = RegisterWindowClass(); window_handle_ = CreateWindowEx(0, window_class.lpszClassName, L"", 0, 0, 0, 0, 0, HWND_MESSAGE, nullptr, window_class.hInstance, nullptr); if (window_handle_) { SetWindowLongPtr(window_handle_, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(this)); } else { auto error = GetLastError(); LPWSTR message = nullptr; size_t size = FormatMessageW( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), reinterpret_cast<LPWSTR>(&message), 0, NULL); OutputDebugString(message); LocalFree(message); } } TaskRunnerWindow::~TaskRunnerWindow() { if (window_handle_) { DestroyWindow(window_handle_); window_handle_ = nullptr; } UnregisterClass(window_class_name_.c_str(), nullptr); } std::shared_ptr<TaskRunnerWindow> TaskRunnerWindow::GetSharedInstance() { static std::weak_ptr<TaskRunnerWindow> instance; auto res = instance.lock(); if (!res) { // can't use make_shared with private contructor res.reset(new TaskRunnerWindow()); instance = res; } return res; } void TaskRunnerWindow::WakeUp() { if (!PostMessage(window_handle_, WM_NULL, 0, 0)) { FML_LOG(ERROR) << "Failed to post message to main thread."; } } void TaskRunnerWindow::AddDelegate(Delegate* delegate) { delegates_.push_back(delegate); SetTimer(std::chrono::nanoseconds::zero()); } void TaskRunnerWindow::RemoveDelegate(Delegate* delegate) { auto i = std::find(delegates_.begin(), delegates_.end(), delegate); if (i != delegates_.end()) { delegates_.erase(i); } } void TaskRunnerWindow::ProcessTasks() { auto next = std::chrono::nanoseconds::max(); auto delegates_copy(delegates_); for (auto delegate : delegates_copy) { // if not removed in the meanwhile if (std::find(delegates_.begin(), delegates_.end(), delegate) != delegates_.end()) { next = std::min(next, delegate->ProcessTasks()); } } SetTimer(next); } void TaskRunnerWindow::SetTimer(std::chrono::nanoseconds when) { if (when == std::chrono::nanoseconds::max()) { KillTimer(window_handle_, 0); } else { auto millis = std::chrono::duration_cast<std::chrono::milliseconds>(when); ::SetTimer(window_handle_, 0, millis.count() + 1, nullptr); } } WNDCLASS TaskRunnerWindow::RegisterWindowClass() { window_class_name_ = L"FlutterTaskRunnerWindow"; WNDCLASS window_class{}; window_class.hCursor = nullptr; window_class.lpszClassName = window_class_name_.c_str(); window_class.style = 0; window_class.cbClsExtra = 0; window_class.cbWndExtra = 0; window_class.hInstance = GetModuleHandle(nullptr); window_class.hIcon = nullptr; window_class.hbrBackground = 0; window_class.lpszMenuName = nullptr; window_class.lpfnWndProc = WndProc; RegisterClass(&window_class); return window_class; } LRESULT TaskRunnerWindow::HandleMessage(UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept { switch (message) { case WM_TIMER: case WM_NULL: ProcessTasks(); return 0; } return DefWindowProcW(window_handle_, message, wparam, lparam); } LRESULT TaskRunnerWindow::WndProc(HWND const window, UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept { if (auto* that = reinterpret_cast<TaskRunnerWindow*>( GetWindowLongPtr(window, GWLP_USERDATA))) { return that->HandleMessage(message, wparam, lparam); } else { return DefWindowProc(window, message, wparam, lparam); } } } // namespace flutter
engine/shell/platform/windows/task_runner_window.cc/0
{ "file_path": "engine/shell/platform/windows/task_runner_window.cc", "repo_id": "engine", "token_count": 1662 }
384
// 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_SHELL_PLATFORM_WINDOWS_TESTING_MOCK_WINDOW_BINDING_HANDLER_H_ #define FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_MOCK_WINDOW_BINDING_HANDLER_H_ #include "flutter/fml/macros.h" #include "flutter/shell/platform/windows/window_binding_handler.h" #include "flutter/third_party/accessibility/ax/platform/ax_platform_node_win.h" #include "gmock/gmock.h" namespace flutter { namespace testing { /// Mock for the |Window| base class. class MockWindowBindingHandler : public WindowBindingHandler { public: MockWindowBindingHandler(); virtual ~MockWindowBindingHandler(); MOCK_METHOD(void, SetView, (WindowBindingHandlerDelegate * view), (override)); MOCK_METHOD(HWND, GetWindowHandle, (), (override)); MOCK_METHOD(float, GetDpiScale, (), (override)); MOCK_METHOD(PhysicalWindowBounds, GetPhysicalWindowBounds, (), (override)); MOCK_METHOD(void, UpdateFlutterCursor, (const std::string& cursor_name), (override)); MOCK_METHOD(void, SetFlutterCursor, (HCURSOR cursor_name), (override)); MOCK_METHOD(void, OnCursorRectUpdated, (const Rect& rect), (override)); MOCK_METHOD(void, OnResetImeComposing, (), (override)); MOCK_METHOD(bool, OnBitmapSurfaceCleared, (), (override)); MOCK_METHOD(bool, OnBitmapSurfaceUpdated, (const void* allocation, size_t row_bytes, size_t height), (override)); MOCK_METHOD(PointerLocation, GetPrimaryPointerLocation, (), (override)); MOCK_METHOD(AlertPlatformNodeDelegate*, GetAlertDelegate, (), (override)); MOCK_METHOD(ui::AXPlatformNodeWin*, GetAlert, (), (override)); private: FML_DISALLOW_COPY_AND_ASSIGN(MockWindowBindingHandler); }; } // namespace testing } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_MOCK_WINDOW_BINDING_HANDLER_H_
engine/shell/platform/windows/testing/mock_window_binding_handler.h/0
{ "file_path": "engine/shell/platform/windows/testing/mock_window_binding_handler.h", "repo_id": "engine", "token_count": 737 }
385
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/windows/text_input_manager.h" #include <imm.h> #include <memory> #include "flutter/fml/logging.h" #include "flutter/fml/macros.h" namespace flutter { // RAII wrapper for the Win32 Input Method Manager context. class ImmContext { public: ImmContext(HWND window_handle) : context_(::ImmGetContext(window_handle)), window_handle_(window_handle) { FML_DCHECK(window_handle); } ~ImmContext() { if (context_ != nullptr) { ::ImmReleaseContext(window_handle_, context_); } } // Returns true if a valid IMM context has been obtained. bool IsValid() const { return context_ != nullptr; } // Returns the IMM context. HIMC get() { FML_DCHECK(context_); return context_; } private: HWND window_handle_; HIMC context_; FML_DISALLOW_COPY_AND_ASSIGN(ImmContext); }; void TextInputManager::SetWindowHandle(HWND window_handle) { window_handle_ = window_handle; } void TextInputManager::CreateImeWindow() { if (window_handle_ == nullptr) { return; } // Some IMEs ignore calls to ::ImmSetCandidateWindow() and use the position of // the current system caret instead via ::GetCaretPos(). In order to behave // as expected with these IMEs, we create a temporary system caret. if (!ime_active_) { ::CreateCaret(window_handle_, nullptr, 1, 1); } ime_active_ = true; // Set the position of the IME windows. UpdateImeWindow(); } void TextInputManager::DestroyImeWindow() { if (window_handle_ == nullptr) { return; } // Destroy the system caret created in CreateImeWindow(). if (ime_active_) { ::DestroyCaret(); } ime_active_ = false; } void TextInputManager::UpdateImeWindow() { if (window_handle_ == nullptr) { return; } ImmContext imm_context(window_handle_); if (imm_context.IsValid()) { MoveImeWindow(imm_context.get()); } } void TextInputManager::UpdateCaretRect(const Rect& rect) { caret_rect_ = rect; if (window_handle_ == nullptr) { return; } ImmContext imm_context(window_handle_); if (imm_context.IsValid()) { MoveImeWindow(imm_context.get()); } } long TextInputManager::GetComposingCursorPosition() const { if (window_handle_ == nullptr) { return false; } ImmContext imm_context(window_handle_); if (imm_context.IsValid()) { // Read the cursor position within the composing string. return ImmGetCompositionString(imm_context.get(), GCS_CURSORPOS, nullptr, 0); } return -1; } std::optional<std::u16string> TextInputManager::GetComposingString() const { return GetString(GCS_COMPSTR); } std::optional<std::u16string> TextInputManager::GetResultString() const { return GetString(GCS_RESULTSTR); } void TextInputManager::AbortComposing() { if (window_handle_ == nullptr || !ime_active_) { return; } ImmContext imm_context(window_handle_); if (imm_context.IsValid()) { // Cancel composing and close the candidates window. ::ImmNotifyIME(imm_context.get(), NI_COMPOSITIONSTR, CPS_CANCEL, 0); ::ImmNotifyIME(imm_context.get(), NI_CLOSECANDIDATE, 0, 0); // Clear the composing string. wchar_t composition_str[] = L""; wchar_t reading_str[] = L""; ::ImmSetCompositionStringW(imm_context.get(), SCS_SETSTR, composition_str, sizeof(wchar_t), reading_str, sizeof(wchar_t)); } } std::optional<std::u16string> TextInputManager::GetString(int type) const { if (window_handle_ == nullptr || !ime_active_) { return std::nullopt; } ImmContext imm_context(window_handle_); if (imm_context.IsValid()) { // Read the composing string length. const long compose_bytes = ::ImmGetCompositionString(imm_context.get(), type, nullptr, 0); const long compose_length = compose_bytes / sizeof(wchar_t); if (compose_length < 0) { return std::nullopt; } std::u16string text(compose_length, '\0'); ::ImmGetCompositionString(imm_context.get(), type, &text[0], compose_bytes); return text; } return std::nullopt; } void TextInputManager::MoveImeWindow(HIMC imm_context) { if (GetFocus() != window_handle_ || !ime_active_) { return; } LONG left = caret_rect_.left(); LONG top = caret_rect_.top(); LONG right = caret_rect_.right(); LONG bottom = caret_rect_.bottom(); ::SetCaretPos(left, bottom); // Set the position of composition text. COMPOSITIONFORM composition_form = {CFS_POINT, {left, top}}; ::ImmSetCompositionWindow(imm_context, &composition_form); // Set the position of candidate window. CANDIDATEFORM candidate_form = { 0, CFS_EXCLUDE, {left, bottom}, {left, top, right, bottom}}; ::ImmSetCandidateWindow(imm_context, &candidate_form); } } // namespace flutter
engine/shell/platform/windows/text_input_manager.cc/0
{ "file_path": "engine/shell/platform/windows/text_input_manager.cc", "repo_id": "engine", "token_count": 1795 }
386
// 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_SHELL_PLATFORM_WINDOWS_WINDOWS_PROC_TABLE_H_ #define FLUTTER_SHELL_PLATFORM_WINDOWS_WINDOWS_PROC_TABLE_H_ #include <optional> #include "flutter/fml/macros.h" #include "flutter/fml/native_library.h" namespace flutter { // Lookup table for Windows APIs that aren't available on all versions of // Windows, or for mocking Windows API calls. class WindowsProcTable { public: WindowsProcTable(); virtual ~WindowsProcTable(); // Retrieves the pointer type for a specified pointer. // // Used to react differently to touch or pen inputs. Returns false on failure. // Available on Windows 8 and newer, otherwise returns false. virtual BOOL GetPointerType(UINT32 pointer_id, POINTER_INPUT_TYPE* pointer_type) const; // Get the preferred languages for the thread, and optionally the process, // and system, in that order, depending on the flags. // // See: // https://learn.microsoft.com/windows/win32/api/winnls/nf-winnls-getthreadpreferreduilanguages virtual LRESULT GetThreadPreferredUILanguages(DWORD flags, PULONG count, PZZWSTR languages, PULONG length) const; // Get whether high contrast is enabled. // // Available on Windows 8 and newer, otherwise returns false. // // See: // https://learn.microsoft.com/windows/win32/winauto/high-contrast-parameter virtual bool GetHighContrastEnabled() const; // Get whether the system compositor, DWM, is enabled. // // See: // https://learn.microsoft.com/windows/win32/api/dwmapi/nf-dwmapi-dwmiscompositionenabled virtual bool DwmIsCompositionEnabled() const; // Issues a flush call that blocks the caller until all of the outstanding // surface updates have been made. // // See: // https://learn.microsoft.com/windows/win32/api/dwmapi/nf-dwmapi-dwmflush virtual HRESULT DwmFlush() const; private: using GetPointerType_ = BOOL __stdcall(UINT32 pointerId, POINTER_INPUT_TYPE* pointerType); // The User32.dll library, used to resolve functions at runtime. fml::RefPtr<fml::NativeLibrary> user32_; std::optional<GetPointerType_*> get_pointer_type_; FML_DISALLOW_COPY_AND_ASSIGN(WindowsProcTable); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_WINDOWS_WINDOWS_PROC_TABLE_H_
engine/shell/platform/windows/windows_proc_table.h/0
{ "file_path": "engine/shell/platform/windows/windows_proc_table.h", "repo_id": "engine", "token_count": 975 }
387
# Copyright 2013 The Flutter Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import("//flutter/build/dart/rules.gni") # Build a minimal snapshot that can be used to launch the VM service isolate. flutter_snapshot("vmservice_snapshot") { main_dart = "empty.dart" package_config = ".dart_tool/package_config.json" output_aot_lib = "libvmservice_snapshot.so" }
engine/shell/vmservice/BUILD.gn/0
{ "file_path": "engine/shell/vmservice/BUILD.gn", "repo_id": "engine", "token_count": 147 }
388
# Copyright 2013 The Flutter Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import("//flutter/common/config.gni") import("//flutter/shell/config.gni") import("testing.gni") config("dynamic_symbols") { if (is_clang && is_linux) { ldflags = [ "-rdynamic" ] } } source_set("testing_lib") { testonly = true sources = [ "assertions.h", "debugger_detection.cc", "debugger_detection.h", "display_list_testing.cc", "display_list_testing.h", "logger_listener.cc", "logger_listener.h", "mock_canvas.cc", "mock_canvas.h", "post_task_sync.cc", "post_task_sync.h", "stream_capture.cc", "stream_capture.h", "test_args.cc", "test_args.h", "test_timeout_listener.cc", "test_timeout_listener.h", "testing.cc", "testing.h", "thread_test.cc", "thread_test.h", ] public_deps = [ "//flutter/display_list", "//flutter/fml", "//flutter/third_party/googletest:gmock", "//flutter/third_party/googletest:gtest", ] public_configs = [ "//flutter:config" ] } source_set("testing") { testonly = true sources = [ "run_all_unittests.cc" ] if (enable_unittests && is_linux) { # So that we can call gtk_init in main(). configs += [ "//flutter/shell/platform/linux/config:gtk" ] } public_deps = [ ":testing_lib" ] public_configs = [ ":dynamic_symbols" ] } source_set("dart") { testonly = true sources = [ "dart_isolate_runner.cc", "dart_isolate_runner.h", "elf_loader.cc", "elf_loader.h", "test_dart_native_resolver.cc", "test_dart_native_resolver.h", ] public_deps = [ ":testing_lib", "$dart_src/runtime/bin:elf_loader", "//flutter/common", "//flutter/runtime", "//flutter/runtime:libdart", "//flutter/skia", "//flutter/third_party/tonic", ] } source_set("skia") { testonly = true sources = [ "assertions_skia.cc", "assertions_skia.h", "canvas_test.h", ] public_deps = [ ":testing_lib", "//flutter/skia", ] } dart_snapshot_kernel("vmservice_kernel") { dart_main = rebase_path("//flutter/shell/vmservice/empty.dart", root_build_dir) dart_kernel = "$target_gen_dir/assets/vmservice_kernel.bin" } dart_snapshot_aot("vmservice_snapshot") { dart_kernel = "$target_gen_dir/assets/vmservice_kernel.bin" dart_elf_filename = "libvmservice_snapshot.so" deps = [ ":vmservice_kernel" ] } source_set("fixture_test") { testonly = true sources = [ "dart_fixture.cc", "dart_fixture.h", "fixture_test.cc", "fixture_test.h", ] public_deps = [ ":dart", "//flutter/common", "//flutter/runtime", ] if (flutter_runtime_mode == "profile") { public_deps += [ ":vmservice_snapshot" ] } } if (is_mac || is_ios) { source_set("autoreleasepool_test") { testonly = true sources = [ "autoreleasepool_test.h" ] deps = [ "//flutter/fml", "//flutter/third_party/googletest:gtest", ] } } if (enable_unittests && shell_enable_vulkan) { source_set("vulkan") { testonly = true sources = [ "test_vulkan_context.cc", "test_vulkan_context.h", "test_vulkan_image.cc", "test_vulkan_image.h", "test_vulkan_surface.cc", "test_vulkan_surface.h", ] defines = [ "TEST_VULKAN_PROCS" ] deps = [ ":skia", "//flutter/flutter_vma:flutter_skia_vma", "//flutter/fml", "//flutter/shell/common", "//flutter/vulkan", "//flutter/vulkan/procs", ] if (!is_fuchsia) { deps += [ "//flutter/third_party/swiftshader" ] configs += [ "//flutter/third_party/swiftshader:swiftshader_config" ] } } } if (enable_unittests) { test_fixtures("testing_fixtures") { fixtures = [] } # The //flutter/testing library provides utility methods to other test targets. # This test target tests the testing utilities. executable("testing_unittests") { testonly = true sources = [ "mock_canvas_unittests.cc" ] deps = [ ":skia", ":testing", ":testing_fixtures", "//flutter/runtime:libdart", ] if (shell_enable_metal) { sources += [ "test_metal_surface_unittests.cc" ] deps += [ ":metal" ] } if (shell_enable_vulkan) { deps += [ "//flutter/vulkan" ] } } } # All targets on all platforms should be able to use the Metal utilities. On # platforms where Metal is not available, the tests must be skipped or # implemented to use another available client rendering API. This is usually # either OpenGL which is portably implemented via SwiftShader or the software # backend. This way, all tests compile on all platforms but the Metal backend # is exercised on platforms where Metal itself is available. # # On iOS, this is enabled to allow for Metal tests to run within a test app if (is_mac || is_ios) { source_set("metal") { if (shell_enable_metal) { sources = [ "test_metal_context.h", "test_metal_context.mm", "test_metal_surface.cc", "test_metal_surface.h", "test_metal_surface_impl.h", "test_metal_surface_impl.mm", ] deps = [ ":skia", "//flutter/fml", ] # Skia's Vulkan support is enabled for all platforms (except iOS), and so parts of # Skia's graphics context reference Vulkan symbols. if (shell_enable_vulkan) { deps += [ "//flutter/vulkan" ] } } testonly = true } } # We only use SwiftShader on unittests use_swiftshader = enable_unittests && shell_enable_gl if (use_swiftshader) { source_set("opengl") { testonly = true sources = [ "test_gl_surface.cc", "test_gl_surface.h", ] deps = [ ":skia", "//flutter/fml", ] configs -= [ "//build/config/clang:extra_warnings" ] configs += [ "//flutter/third_party/angle:gl_prototypes", "//flutter/third_party/swiftshader:swiftshader_config", ] deps += [ "//flutter/third_party/angle:libEGL_static", "//flutter/third_party/angle:libGLESv2_static", "//flutter/third_party/swiftshader", ] } }
engine/testing/BUILD.gn/0
{ "file_path": "engine/testing/BUILD.gn", "repo_id": "engine", "token_count": 2721 }
389
# Android Background Image A test application that verifies Picture.toImage in the background on Android.
engine/testing/android_background_image/README.md/0
{ "file_path": "engine/testing/android_background_image/README.md", "repo_id": "engine", "token_count": 23 }
390
// 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_ASSERTIONS_SKIA_H_ #define FLUTTER_TESTING_ASSERTIONS_SKIA_H_ #include <ostream> #include "third_party/skia/include/core/SkClipOp.h" #include "third_party/skia/include/core/SkM44.h" #include "third_party/skia/include/core/SkMatrix.h" #include "third_party/skia/include/core/SkPaint.h" #include "third_party/skia/include/core/SkPath.h" #include "third_party/skia/include/core/SkPoint3.h" #include "third_party/skia/include/core/SkRRect.h" #include "third_party/skia/include/core/SkSamplingOptions.h" namespace std { extern std::ostream& operator<<(std::ostream& os, const SkClipOp& o); extern std::ostream& operator<<(std::ostream& os, const SkMatrix& m); extern std::ostream& operator<<(std::ostream& os, const SkM44& m); extern std::ostream& operator<<(std::ostream& os, const SkVector3& v); extern std::ostream& operator<<(std::ostream& os, const SkIRect& r); extern std::ostream& operator<<(std::ostream& os, const SkRect& r); extern std::ostream& operator<<(std::ostream& os, const SkRRect& r); extern std::ostream& operator<<(std::ostream& os, const SkPath& r); extern std::ostream& operator<<(std::ostream& os, const SkPoint& r); extern std::ostream& operator<<(std::ostream& os, const SkISize& size); extern std::ostream& operator<<(std::ostream& os, const SkColor4f& r); extern std::ostream& operator<<(std::ostream& os, const SkPaint& r); extern std::ostream& operator<<(std::ostream& os, const SkSamplingOptions& s); } // namespace std #endif // FLUTTER_TESTING_ASSERTIONS_SKIA_H_
engine/testing/assertions_skia.h/0
{ "file_path": "engine/testing/assertions_skia.h", "repo_id": "engine", "token_count": 622 }
391
// 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:io'; import 'dart:math'; import 'dart:typed_data'; import 'dart:ui'; import 'package:litetest/litetest.dart'; import 'package:path/path.dart' as path; import 'package:vector_math/vector_math_64.dart'; import 'goldens.dart'; import 'impeller_enabled.dart'; typedef CanvasCallback = void Function(Canvas canvas); Future<Image> createImage(int width, int height) { final Completer<Image> completer = Completer<Image>(); decodeImageFromPixels( Uint8List.fromList(List<int>.generate( width * height * 4, (int pixel) => pixel % 255, )), width, height, PixelFormat.rgba8888, (Image image) { completer.complete(image); }, ); return completer.future; } void testCanvas(CanvasCallback callback) { try { callback(Canvas(PictureRecorder(), Rect.zero)); } catch (error) { } // ignore: empty_catches } Future<Image> toImage(CanvasCallback callback, int width, int height) { final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder, Rect.fromLTRB(0, 0, width.toDouble(), height.toDouble())); callback(canvas); final Picture picture = recorder.endRecording(); return picture.toImage(width, height); } void testNoCrashes() { test('canvas APIs should not crash', () async { final Paint paint = Paint(); const Rect rect = Rect.fromLTRB(double.nan, double.nan, double.nan, double.nan); final RRect rrect = RRect.fromRectAndCorners(rect); const Offset offset = Offset(double.nan, double.nan); final Path path = Path(); const Color color = Color(0x00000000); final Paragraph paragraph = ParagraphBuilder(ParagraphStyle()).build(); final PictureRecorder recorder = PictureRecorder(); final Canvas recorderCanvas = Canvas(recorder); recorderCanvas.scale(1.0, 1.0); final Picture picture = recorder.endRecording(); final Image image = await picture.toImage(1, 1); try { Canvas(PictureRecorder()); } catch (error) { } // ignore: empty_catches try { Canvas(PictureRecorder(), rect); } catch (error) { } // ignore: empty_catches try { PictureRecorder() ..endRecording() ..endRecording() ..endRecording(); } catch (error) { } // ignore: empty_catches testCanvas((Canvas canvas) => canvas.clipPath(path)); testCanvas((Canvas canvas) => canvas.clipRect(rect)); testCanvas((Canvas canvas) => canvas.clipRRect(rrect)); testCanvas((Canvas canvas) => canvas.drawArc(rect, 0.0, 0.0, false, paint)); testCanvas((Canvas canvas) => canvas.drawAtlas(image, <RSTransform>[], <Rect>[], <Color>[], BlendMode.src, rect, paint)); testCanvas((Canvas canvas) => canvas.drawCircle(offset, double.nan, paint)); testCanvas((Canvas canvas) => canvas.drawColor(color, BlendMode.src)); testCanvas((Canvas canvas) => canvas.drawDRRect(rrect, rrect, paint)); testCanvas((Canvas canvas) => canvas.drawImage(image, offset, paint)); testCanvas((Canvas canvas) => canvas.drawImageNine(image, rect, rect, paint)); testCanvas((Canvas canvas) => canvas.drawImageRect(image, rect, rect, paint)); testCanvas((Canvas canvas) => canvas.drawLine(offset, offset, paint)); testCanvas((Canvas canvas) => canvas.drawOval(rect, paint)); testCanvas((Canvas canvas) => canvas.drawPaint(paint)); testCanvas((Canvas canvas) => canvas.drawParagraph(paragraph, offset)); testCanvas((Canvas canvas) => canvas.drawPath(path, paint)); testCanvas((Canvas canvas) => canvas.drawPicture(picture)); testCanvas((Canvas canvas) => canvas.drawPoints(PointMode.points, <Offset>[], paint)); testCanvas((Canvas canvas) => canvas.drawRawAtlas(image, Float32List(0), Float32List(0), Int32List(0), BlendMode.src, rect, paint)); testCanvas((Canvas canvas) => canvas.drawRawPoints(PointMode.points, Float32List(0), paint)); testCanvas((Canvas canvas) => canvas.drawRect(rect, paint)); testCanvas((Canvas canvas) => canvas.drawRRect(rrect, paint)); testCanvas((Canvas canvas) => canvas.drawShadow(path, color, double.nan, false)); testCanvas((Canvas canvas) => canvas.drawShadow(path, color, double.nan, true)); testCanvas((Canvas canvas) => canvas.drawVertices(Vertices(VertexMode.triangles, <Offset>[]), BlendMode.screen, paint)); testCanvas((Canvas canvas) => canvas.getSaveCount()); testCanvas((Canvas canvas) => canvas.restore()); testCanvas((Canvas canvas) => canvas.rotate(double.nan)); testCanvas((Canvas canvas) => canvas.save()); testCanvas((Canvas canvas) => canvas.saveLayer(rect, paint)); testCanvas((Canvas canvas) => canvas.saveLayer(null, paint)); testCanvas((Canvas canvas) => canvas.scale(double.nan, double.nan)); testCanvas((Canvas canvas) => canvas.skew(double.nan, double.nan)); testCanvas((Canvas canvas) => canvas.transform(Float64List(16))); testCanvas((Canvas canvas) => canvas.translate(double.nan, double.nan)); testCanvas((Canvas canvas) => canvas.drawVertices(Vertices(VertexMode.triangles, <Offset>[], indices: <int>[]), BlendMode.screen, paint)); testCanvas((Canvas canvas) => canvas.drawVertices(Vertices(VertexMode.triangles, <Offset>[])..dispose(), BlendMode.screen, paint)); // Regression test for https://github.com/flutter/flutter/issues/115143 testCanvas((Canvas canvas) => canvas.drawPaint(Paint()..imageFilter = const ColorFilter.mode(Color(0x00000000), BlendMode.xor))); // Regression test for https://github.com/flutter/flutter/issues/120278 testCanvas((Canvas canvas) => canvas.drawPaint(Paint()..imageFilter = ImageFilter.compose( outer: ImageFilter.matrix(Matrix4.identity().storage), inner: ImageFilter.blur()))); }); } const String kFlutterBuildDirectory = 'kFlutterBuildDirectory'; String get _flutterBuildPath { const String buildPath = String.fromEnvironment(kFlutterBuildDirectory); if (buildPath.isEmpty) { throw StateError('kFlutterBuildDirectory -D variable is not set.'); } return buildPath; } void main() async { final ImageComparer comparer = await ImageComparer.create(); testNoCrashes(); test('Simple .toImage', () async { final Image image = await toImage((Canvas canvas) { final Path circlePath = Path() ..addOval( Rect.fromCircle(center: const Offset(40.0, 40.0), radius: 20.0)); final Paint paint = Paint() ..isAntiAlias = false ..style = PaintingStyle.fill; canvas.drawPath(circlePath, paint); }, 100, 100); expect(image.width, equals(100)); expect(image.height, equals(100)); await comparer.addGoldenImage(image, 'canvas_test_toImage.png'); }); Gradient makeGradient() { return Gradient.linear( Offset.zero, const Offset(100, 100), const <Color>[Color(0xFF4C4D52), Color(0xFF202124)], ); } test('Simple gradient, which is implicitly dithered', () async { final Image image = await toImage((Canvas canvas) { final Paint paint = Paint()..shader = makeGradient(); canvas.drawPaint(paint); }, 100, 100); expect(image.width, equals(100)); expect(image.height, equals(100)); await comparer.addGoldenImage(image, 'canvas_test_dithered_gradient.png'); }); test('Null values allowed for drawAtlas methods', () async { final Image image = await createImage(100, 100); final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); const Rect rect = Rect.fromLTWH(0, 0, 100, 100); final RSTransform transform = RSTransform(1, 0, 0, 0); const Color color = Color(0x00000000); final Paint paint = Paint(); canvas.drawAtlas(image, <RSTransform>[transform], <Rect>[rect], <Color>[color], BlendMode.src, rect, paint); canvas.drawAtlas(image, <RSTransform>[transform], <Rect>[rect], <Color>[color], BlendMode.src, null, paint); canvas.drawAtlas(image, <RSTransform>[transform], <Rect>[rect], <Color>[], null, rect, paint); canvas.drawAtlas(image, <RSTransform>[transform], <Rect>[rect], null, null, rect, paint); canvas.drawRawAtlas(image, Float32List(0), Float32List(0), Int32List(0), BlendMode.src, rect, paint); canvas.drawRawAtlas(image, Float32List(0), Float32List(0), Int32List(0), BlendMode.src, null, paint); canvas.drawRawAtlas(image, Float32List(0), Float32List(0), null, null, rect, paint); expectAssertion(() => canvas.drawAtlas(image, <RSTransform>[transform], <Rect>[rect], <Color>[color], null, rect, paint)); }); test('Data lengths must match for drawAtlas methods', () async { final Image image = await createImage(100, 100); final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); const Rect rect = Rect.fromLTWH(0, 0, 100, 100); final RSTransform transform = RSTransform(1, 0, 0, 0); const Color color = Color(0x00000000); final Paint paint = Paint(); canvas.drawAtlas(image, <RSTransform>[transform], <Rect>[rect], <Color>[color], BlendMode.src, rect, paint); canvas.drawAtlas(image, <RSTransform>[transform, transform], <Rect>[rect, rect], <Color>[color, color], BlendMode.src, rect, paint); canvas.drawAtlas(image, <RSTransform>[transform], <Rect>[rect], <Color>[], null, rect, paint); canvas.drawAtlas(image, <RSTransform>[transform], <Rect>[rect], null, null, rect, paint); canvas.drawRawAtlas(image, Float32List(0), Float32List(0), Int32List(0), BlendMode.src, rect, paint); canvas.drawRawAtlas(image, Float32List(4), Float32List(4), Int32List(1), BlendMode.src, rect, paint); canvas.drawRawAtlas(image, Float32List(4), Float32List(4), null, null, rect, paint); expectArgumentError(() => canvas.drawAtlas(image, <RSTransform>[transform], <Rect>[], <Color>[color], BlendMode.src, rect, paint)); expectArgumentError(() => canvas.drawAtlas(image, <RSTransform>[], <Rect>[rect], <Color>[color], BlendMode.src, rect, paint)); expectArgumentError(() => canvas.drawAtlas(image, <RSTransform>[transform], <Rect>[rect], <Color>[color, color], BlendMode.src, rect, paint)); expectArgumentError(() => canvas.drawAtlas(image, <RSTransform>[transform], <Rect>[rect, rect], <Color>[color], BlendMode.src, rect, paint)); expectArgumentError(() => canvas.drawAtlas(image, <RSTransform>[transform, transform], <Rect>[rect], <Color>[color], BlendMode.src, rect, paint)); expectArgumentError(() => canvas.drawRawAtlas(image, Float32List(3), Float32List(3), null, null, rect, paint)); expectArgumentError(() => canvas.drawRawAtlas(image, Float32List(4), Float32List(0), null, null, rect, paint)); expectArgumentError(() => canvas.drawRawAtlas(image, Float32List(0), Float32List(4), null, null, rect, paint)); expectArgumentError(() => canvas.drawRawAtlas(image, Float32List(4), Float32List(4), Int32List(2), BlendMode.src, rect, paint)); }); test('Canvas preserves perspective data in Matrix4', () async { const double rotateAroundX = pi / 6; // 30 degrees const double rotateAroundY = pi / 9; // 20 degrees const int width = 150; const int height = 150; const Color black = Color.fromARGB(255, 0, 0, 0); const Color green = Color.fromARGB(255, 0, 255, 0); void paint(Canvas canvas, CanvasCallback rotate) { canvas.translate(width * 0.5, height * 0.5); rotate(canvas); const double width3 = width / 3.0; const double width5 = width / 5.0; const double width10 = width / 10.0; canvas.drawRect(const Rect.fromLTRB(-width3, -width3, width3, width3), Paint()..color = green); canvas.drawRect(const Rect.fromLTRB(-width5, -width5, -width10, width5), Paint()..color = black); canvas.drawRect(const Rect.fromLTRB(-width5, -width5, width5, -width10), Paint()..color = black); } final Image incrementalMatrixImage = await toImage((Canvas canvas) { paint(canvas, (Canvas canvas) { final Matrix4 matrix = Matrix4.identity(); matrix.setEntry(3, 2, 0.001); canvas.transform(matrix.storage); matrix.setRotationX(rotateAroundX); canvas.transform(matrix.storage); matrix.setRotationY(rotateAroundY); canvas.transform(matrix.storage); }); }, width, height); final Image combinedMatrixImage = await toImage((Canvas canvas) { paint(canvas, (Canvas canvas) { final Matrix4 matrix = Matrix4.identity(); matrix.setEntry(3, 2, 0.001); matrix.rotateX(rotateAroundX); matrix.rotateY(rotateAroundY); canvas.transform(matrix.storage); }); }, width, height); final bool areEqual = await comparer.fuzzyCompareImages(incrementalMatrixImage, combinedMatrixImage); expect(areEqual, true); }); test('Path effects from Paragraphs do not affect further rendering', () async { void drawText(Canvas canvas, String content, Offset offset, {TextDecorationStyle style = TextDecorationStyle.solid}) { final ParagraphBuilder builder = ParagraphBuilder(ParagraphStyle()); builder.pushStyle(TextStyle( decoration: TextDecoration.underline, decorationColor: const Color(0xFF0000FF), fontFamily: 'Ahem', fontSize: 10, color: const Color(0xFF000000), decorationStyle: style, )); builder.addText(content); final Paragraph paragraph = builder.build(); paragraph.layout(const ParagraphConstraints(width: 100)); canvas.drawParagraph(paragraph, offset); } final Image image = await toImage((Canvas canvas) { canvas.drawColor(const Color(0xFFFFFFFF), BlendMode.srcOver); final Paint paint = Paint() ..style = PaintingStyle.stroke ..strokeWidth = 5; drawText(canvas, 'Hello World', const Offset(20, 10)); canvas.drawCircle(const Offset(150, 25), 15, paint..color = const Color(0xFF00FF00)); drawText(canvas, 'Regular text', const Offset(20, 60)); canvas.drawCircle(const Offset(150, 75), 15, paint..color = const Color(0xFFFFFF00)); drawText(canvas, 'Dotted text', const Offset(20, 110), style: TextDecorationStyle.dotted); canvas.drawCircle(const Offset(150, 125), 15, paint..color = const Color(0xFFFF0000)); drawText(canvas, 'Dashed text', const Offset(20, 160), style: TextDecorationStyle.dashed); canvas.drawCircle(const Offset(150, 175), 15, paint..color = const Color(0xFFFF0000)); drawText(canvas, 'Wavy text', const Offset(20, 210), style: TextDecorationStyle.wavy); canvas.drawCircle(const Offset(150, 225), 15, paint..color = const Color(0xFFFF0000)); }, 200, 250); expect(image.width, equals(200)); expect(image.height, equals(250)); await comparer.addGoldenImage(image, 'dotted_path_effect_mixed_with_stroked_geometry.png'); }); test('Gradients with matrices in Paragraphs render correctly', () async { final Image image = await toImage((Canvas canvas) { final Paint p = Paint(); final Float64List transform = Float64List.fromList(<double>[ 86.80000129342079, 0.0, 0.0, 0.0, 0.0, 94.5, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 60.0, 224.310302734375, 0.0, 1.0 ]); p.shader = Gradient.radial( const Offset(2.5, 0.33), 0.8, <Color>[ const Color(0xffff0000), const Color(0xff00ff00), const Color(0xff0000ff), const Color(0xffff00ff) ], <double>[0.0, 0.3, 0.7, 0.9], TileMode.mirror, transform, const Offset(2.55, 0.4)); final ParagraphBuilder builder = ParagraphBuilder(ParagraphStyle()); builder.pushStyle(TextStyle( foreground: p, fontSize: 200, )); builder.addText('Woodstock!'); final Paragraph paragraph = builder.build(); paragraph.layout(const ParagraphConstraints(width: 1000)); canvas.drawParagraph(paragraph, const Offset(10, 150)); }, 600, 400); expect(image.width, equals(600)); expect(image.height, equals(400)); await comparer.addGoldenImage(image, 'text_with_gradient_with_matrix.png'); }); test('toImageSync - too big', () async { PictureRecorder recorder = PictureRecorder(); Canvas canvas = Canvas(recorder); canvas.drawPaint(Paint()..color = const Color(0xFF123456)); final Picture picture = recorder.endRecording(); final Image image = picture.toImageSync(300000, 4000000); picture.dispose(); expect(image.width, 300000); expect(image.height, 4000000); recorder = PictureRecorder(); canvas = Canvas(recorder); if (impellerEnabled) { // Impeller tries to automagically scale this. See // https://github.com/flutter/flutter/issues/128885 canvas.drawImage(image, Offset.zero, Paint()); return; } // On a slower CI machine, the raster thread may get behind the UI thread // here. However, once the image is in an error state it will immediately // throw on subsequent attempts. bool caughtException = false; for (int iterations = 0; iterations < 1000; iterations += 1) { try { canvas.drawImage(image, Offset.zero, Paint()); } on PictureRasterizationException catch (e) { caughtException = true; expect( e.message, contains('unable to create bitmap render target at specified size ${image.width}x${image.height}'), ); break; } // Let the event loop turn. await Future<void>.delayed(const Duration(milliseconds: 1)); } expect(caughtException, true); expect( () => canvas.drawImageRect(image, Rect.zero, Rect.zero, Paint()), throwsException, ); expect( () => canvas.drawImageNine(image, Rect.zero, Rect.zero, Paint()), throwsException, ); expect( () => canvas.drawAtlas(image, <RSTransform>[], <Rect>[], null, null, null, Paint()), throwsException, ); }); test('toImageSync - succeeds', () async { PictureRecorder recorder = PictureRecorder(); Canvas canvas = Canvas(recorder); canvas.drawPaint(Paint()..color = const Color(0xFF123456)); final Picture picture = recorder.endRecording(); final Image image = picture.toImageSync(30, 40); picture.dispose(); expect(image.width, 30); expect(image.height, 40); recorder = PictureRecorder(); canvas = Canvas(recorder); expect( () => canvas.drawImage(image, Offset.zero, Paint()), returnsNormally, ); expect( () => canvas.drawImageRect(image, Rect.zero, Rect.zero, Paint()), returnsNormally, ); expect( () => canvas.drawImageNine(image, Rect.zero, Rect.zero, Paint()), returnsNormally, ); expect( () => canvas.drawAtlas(image, <RSTransform>[], <Rect>[], null, null, null, Paint()), returnsNormally, ); }); test('toImageSync - toByteData', () async { const Color color = Color(0xFF123456); final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); canvas.drawPaint(Paint()..color = color); final Picture picture = recorder.endRecording(); final Image image = picture.toImageSync(6, 8); picture.dispose(); expect(image.width, 6); expect(image.height, 8); final ByteData? data = await image.toByteData(); expect(data, isNotNull); expect(data!.lengthInBytes, 6 * 8 * 4); expect(data.buffer.asUint8List()[0], 0x12); expect(data.buffer.asUint8List()[1], 0x34); expect(data.buffer.asUint8List()[2], 0x56); expect(data.buffer.asUint8List()[3], 0xFF); }); test('toImage and toImageSync have identical contents', () async { // Note: on linux this stil seems to be different. // TODO(jonahwilliams): https://github.com/flutter/flutter/issues/108835 if (Platform.isLinux) { return; } final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); canvas.drawRect( const Rect.fromLTWH(20, 20, 100, 100), Paint()..color = const Color(0xA0FF6D00), ); final Picture picture = recorder.endRecording(); final Image toImageImage = await picture.toImage(200, 200); final Image toImageSyncImage = picture.toImageSync(200, 200); // To trigger observable difference in alpha, draw image // on a second canvas. Future<ByteData> drawOnCanvas(Image image) async { final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); canvas.drawPaint(Paint()..color = const Color(0x4FFFFFFF)); canvas.drawImage(image, Offset.zero, Paint()); final Image resultImage = await recorder.endRecording().toImage(200, 200); return (await resultImage.toByteData())!; } final ByteData dataSync = await drawOnCanvas(toImageImage); final ByteData data = await drawOnCanvas(toImageSyncImage); expect(data, listEquals(dataSync)); }); test('Canvas.drawParagraph throws when Paragraph.layout was not called', () async { // Regression test for https://github.com/flutter/flutter/issues/97172 bool assertsEnabled = false; assert(() { assertsEnabled = true; return true; }()); Object? error; try { await toImage((Canvas canvas) { final ParagraphBuilder builder = ParagraphBuilder(ParagraphStyle()); builder.addText('Woodstock!'); final Paragraph woodstock = builder.build(); canvas.drawParagraph(woodstock, const Offset(0, 50)); }, 100, 100); } catch (e) { error = e; } if (assertsEnabled) { expect(error, isNotNull); } else { expect(error, isNull); } }); Future<Image> drawText(String text) { return toImage((Canvas canvas) { final ParagraphBuilder builder = ParagraphBuilder(ParagraphStyle( fontFamily: 'RobotoSerif', fontStyle: FontStyle.normal, fontWeight: FontWeight.normal, fontSize: 15.0, )); builder.pushStyle(TextStyle(color: const Color(0xFF0000FF))); builder.addText(text); final Paragraph paragraph = builder.build(); paragraph.layout(const ParagraphConstraints(width: 20 * 5.0)); canvas.drawParagraph(paragraph, Offset.zero); }, 100, 100); } test('Canvas.drawParagraph renders tab as space instead of tofu', () async { // Skia renders a tofu if the font does not have a glyph for a character. // However, Flutter opts-in to a Skia feature to render tabs as a single space. // See: https://github.com/flutter/flutter/issues/79153 final File file = File(path.join(_flutterBuildPath, 'flutter', 'third_party', 'txt', 'assets', 'Roboto-Regular.ttf')); final Uint8List fontData = await file.readAsBytes(); await loadFontFromList(fontData, fontFamily: 'RobotoSerif'); // The backspace character, \b, does not have a corresponding glyph and is rendered as a tofu. final Image tabImage = await drawText('>\t<'); final Image spaceImage = await drawText('> <'); final Image tofuImage = await drawText('>\b<'); // The tab's image should be identical to the space's image but not the tofu's image. final bool tabToSpaceComparison = await comparer.fuzzyCompareImages(tabImage, spaceImage); final bool tabToTofuComparison = await comparer.fuzzyCompareImages(tabImage, tofuImage); expect(tabToSpaceComparison, isTrue); expect(tabToTofuComparison, isFalse); }); test('drawRect, drawOval, and clipRect render with unsorted rectangles', () async { final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); canvas.drawColor(const Color(0xFFE0E0E0), BlendMode.src); void draw(Rect rect, double x, double y, Color color) { final Paint paint = Paint() ..color = color ..strokeWidth = 5.0; final Rect tallThin = Rect.fromLTRB( min(rect.left, rect.right) - 10, rect.top, min(rect.left, rect.right) - 10, rect.bottom, ); final Rect wideThin = Rect.fromLTRB( rect.left, min(rect.top, rect.bottom) - 10, rect.right, min(rect.top, rect.bottom) - 10, ); canvas.save(); canvas.translate(x, y); paint.style = PaintingStyle.fill; canvas.drawRect(rect, paint); canvas.drawRect(tallThin, paint); canvas.drawRect(wideThin, paint); canvas.save(); canvas.translate(0, 100); paint.style = PaintingStyle.stroke; canvas.drawRect(rect, paint); canvas.drawRect(tallThin, paint); canvas.drawRect(wideThin, paint); canvas.restore(); canvas.save(); canvas.translate(100, 0); paint.style = PaintingStyle.fill; canvas.drawOval(rect, paint); canvas.drawOval(tallThin, paint); canvas.drawOval(wideThin, paint); canvas.restore(); canvas.save(); canvas.translate(100, 100); paint.style = PaintingStyle.stroke; canvas.drawOval(rect, paint); canvas.drawOval(tallThin, paint); canvas.drawOval(wideThin, paint); canvas.restore(); canvas.save(); canvas.translate(50, 50); canvas.save(); canvas.clipRect(rect); canvas.drawPaint(paint); canvas.restore(); canvas.save(); canvas.clipRect(tallThin); canvas.drawPaint(paint); canvas.restore(); canvas.save(); canvas.clipRect(wideThin); canvas.drawPaint(paint); canvas.restore(); canvas.restore(); canvas.restore(); } draw(const Rect.fromLTRB(10, 10, 40, 40), 50, 50, const Color(0xFF2196F3)); draw(const Rect.fromLTRB(40, 10, 10, 40), 250, 50, const Color(0xFF4CAF50)); draw(const Rect.fromLTRB(10, 40, 40, 10), 50, 250, const Color(0xFF9C27B0)); draw(const Rect.fromLTRB(40, 40, 10, 10), 250, 250, const Color(0xFFFF9800)); final Picture picture = recorder.endRecording(); final Image image = await picture.toImage(450, 450); await comparer.addGoldenImage(image, 'render_unordered_rects.png'); }); Matcher closeToTransform(Float64List expected) => (dynamic v) { Expect.type<Float64List>(v); final Float64List value = v as Float64List; expect(expected.length, equals(16)); expect(value.length, equals(16)); for (int r = 0; r < 4; r++) { for (int c = 0; c < 4; c++) { final double vActual = value[r*4 + c]; final double vExpected = expected[r*4 + c]; if ((vActual - vExpected).abs() > 1e-10) { Expect.fail('matrix mismatch at $r, $c, $vActual not close to $vExpected'); } } } }; Matcher notCloseToTransform(Float64List expected) => (dynamic v) { Expect.type<Float64List>(v); final Float64List value = v as Float64List; expect(expected.length, equals(16)); expect(value.length, equals(16)); for (int r = 0; r < 4; r++) { for (int c = 0; c < 4; c++) { final double vActual = value[r*4 + c]; final double vExpected = expected[r*4 + c]; if ((vActual - vExpected).abs() > 1e-10) { return; } } } Expect.fail('$value is too close to $expected'); }; test('Canvas.translate affects canvas.getTransform', () async { final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); canvas.translate(12, 14.5); final Float64List matrix = Matrix4.translationValues(12, 14.5, 0).storage; final Float64List curMatrix = canvas.getTransform(); expect(curMatrix, closeToTransform(matrix)); canvas.translate(10, 10); final Float64List newCurMatrix = canvas.getTransform(); expect(newCurMatrix, notCloseToTransform(matrix)); expect(curMatrix, closeToTransform(matrix)); }); test('Canvas.scale affects canvas.getTransform', () async { final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); canvas.scale(12, 14.5); final Float64List matrix = Matrix4.diagonal3Values(12, 14.5, 1).storage; final Float64List curMatrix = canvas.getTransform(); expect(curMatrix, closeToTransform(matrix)); canvas.scale(10, 10); final Float64List newCurMatrix = canvas.getTransform(); expect(newCurMatrix, notCloseToTransform(matrix)); expect(curMatrix, closeToTransform(matrix)); }); test('Canvas.rotate affects canvas.getTransform', () async { final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); canvas.rotate(pi); final Float64List matrix = Matrix4.rotationZ(pi).storage; final Float64List curMatrix = canvas.getTransform(); expect(curMatrix, closeToTransform(matrix)); canvas.rotate(pi / 2); final Float64List newCurMatrix = canvas.getTransform(); expect(newCurMatrix, notCloseToTransform(matrix)); expect(curMatrix, closeToTransform(matrix)); }); test('Canvas.skew affects canvas.getTransform', () async { final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); canvas.skew(12, 14.5); final Float64List matrix = (Matrix4.identity()..setEntry(0, 1, 12)..setEntry(1, 0, 14.5)).storage; final Float64List curMatrix = canvas.getTransform(); expect(curMatrix, closeToTransform(matrix)); canvas.skew(10, 10); final Float64List newCurMatrix = canvas.getTransform(); expect(newCurMatrix, notCloseToTransform(matrix)); expect(curMatrix, closeToTransform(matrix)); }); test('Canvas.transform affects canvas.getTransform', () async { final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); final Float64List matrix = (Matrix4.identity()..translate(12.0, 14.5)..scale(12.0, 14.5)).storage; canvas.transform(matrix); final Float64List curMatrix = canvas.getTransform(); expect(curMatrix, closeToTransform(matrix)); canvas.translate(10, 10); final Float64List newCurMatrix = canvas.getTransform(); expect(newCurMatrix, notCloseToTransform(matrix)); expect(curMatrix, closeToTransform(matrix)); }); Matcher closeToRect(Rect expected) => (dynamic v) { Expect.type<Rect>(v); final Rect value = v as Rect; expect(value.left, closeTo(expected.left, 1e-6)); expect(value.top, closeTo(expected.top, 1e-6)); expect(value.right, closeTo(expected.right, 1e-6)); expect(value.bottom, closeTo(expected.bottom, 1e-6)); }; Matcher notCloseToRect(Rect expected) => (dynamic v) { Expect.type<Rect>(v); final Rect value = v as Rect; if ((value.left - expected.left).abs() > 1e-6 || (value.top - expected.top).abs() > 1e-6 || (value.right - expected.right).abs() > 1e-6 || (value.bottom - expected.bottom).abs() > 1e-6) { return; } Expect.fail('$value is too close to $expected'); }; test('Canvas.clipRect affects canvas.getClipBounds', () async { void testRect(Rect clipRect, bool doAA) { final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); canvas.clipRect(clipRect, doAntiAlias: doAA); final Rect clipSortedBounds = Rect.fromLTRB( min(clipRect.left, clipRect.right), min(clipRect.top, clipRect.bottom), max(clipRect.left, clipRect.right), max(clipRect.top, clipRect.bottom), ); Rect clipExpandedBounds; if (doAA) { clipExpandedBounds = Rect.fromLTRB( clipSortedBounds.left.floorToDouble(), clipSortedBounds.top.floorToDouble(), clipSortedBounds.right.ceilToDouble(), clipSortedBounds.bottom.ceilToDouble(), ); } else { clipExpandedBounds = clipSortedBounds; } // Save initial return values for testing restored values final Rect initialLocalBounds = canvas.getLocalClipBounds(); final Rect initialDestinationBounds = canvas.getDestinationClipBounds(); expect(initialLocalBounds, closeToRect(clipExpandedBounds)); expect(initialDestinationBounds, closeToRect(clipExpandedBounds)); canvas.save(); canvas.clipRect(const Rect.fromLTRB(0, 0, 15, 15)); // Both clip bounds have changed expect(canvas.getLocalClipBounds(), notCloseToRect(clipExpandedBounds)); expect(canvas.getDestinationClipBounds(), notCloseToRect(clipExpandedBounds)); // Previous return values have not changed expect(initialLocalBounds, closeToRect(clipExpandedBounds)); expect(initialDestinationBounds, closeToRect(clipExpandedBounds)); canvas.restore(); // save/restore returned the values to their original values expect(canvas.getLocalClipBounds(), initialLocalBounds); expect(canvas.getDestinationClipBounds(), initialDestinationBounds); canvas.save(); canvas.scale(2, 2); final Rect scaledExpandedBounds = Rect.fromLTRB( clipExpandedBounds.left / 2.0, clipExpandedBounds.top / 2.0, clipExpandedBounds.right / 2.0, clipExpandedBounds.bottom / 2.0, ); expect(canvas.getLocalClipBounds(), closeToRect(scaledExpandedBounds)); // Destination bounds are unaffected by transform expect(canvas.getDestinationClipBounds(), closeToRect(clipExpandedBounds)); canvas.restore(); // save/restore returned the values to their original values expect(canvas.getLocalClipBounds(), initialLocalBounds); expect(canvas.getDestinationClipBounds(), initialDestinationBounds); } testRect(const Rect.fromLTRB(10.2, 11.3, 20.4, 25.7), false); testRect(const Rect.fromLTRB(10.2, 11.3, 20.4, 25.7), true); // LR swapped testRect(const Rect.fromLTRB(20.4, 11.3, 10.2, 25.7), false); testRect(const Rect.fromLTRB(20.4, 11.3, 10.2, 25.7), true); // TB swapped testRect(const Rect.fromLTRB(10.2, 25.7, 20.4, 11.3), false); testRect(const Rect.fromLTRB(10.2, 25.7, 20.4, 11.3), true); // LR and TB swapped testRect(const Rect.fromLTRB(20.4, 25.7, 10.2, 11.3), false); testRect(const Rect.fromLTRB(20.4, 25.7, 10.2, 11.3), true); }); test('Canvas.clipRect with matrix affects canvas.getClipBounds', () async { final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); const Rect clipBounds1 = Rect.fromLTRB(0.0, 0.0, 10.0, 10.0); const Rect clipBounds2 = Rect.fromLTRB(10.0, 10.0, 20.0, 20.0); canvas.save(); canvas.clipRect(clipBounds1, doAntiAlias: false); canvas.translate(0, 10.0); canvas.clipRect(clipBounds1, doAntiAlias: false); expect(canvas.getDestinationClipBounds().isEmpty, isTrue); canvas.restore(); canvas.save(); canvas.clipRect(clipBounds1, doAntiAlias: false); canvas.translate(-10.0, -10.0); canvas.clipRect(clipBounds2, doAntiAlias: false); expect(canvas.getDestinationClipBounds(), clipBounds1); canvas.restore(); }); test('Canvas.clipRRect(doAA=true) affects canvas.getClipBounds', () async { final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); const Rect clipBounds = Rect.fromLTRB(10.2, 11.3, 20.4, 25.7); const Rect clipExpandedBounds = Rect.fromLTRB(10, 11, 21, 26); final RRect clip = RRect.fromRectAndRadius(clipBounds, const Radius.circular(3)); canvas.clipRRect(clip); // Save initial return values for testing restored values final Rect initialLocalBounds = canvas.getLocalClipBounds(); final Rect initialDestinationBounds = canvas.getDestinationClipBounds(); expect(initialLocalBounds, closeToRect(clipExpandedBounds)); expect(initialDestinationBounds, closeToRect(clipExpandedBounds)); canvas.save(); canvas.clipRect(const Rect.fromLTRB(0, 0, 15, 15)); // Both clip bounds have changed expect(canvas.getLocalClipBounds(), notCloseToRect(clipExpandedBounds)); expect(canvas.getDestinationClipBounds(), notCloseToRect(clipExpandedBounds)); // Previous return values have not changed expect(initialLocalBounds, closeToRect(clipExpandedBounds)); expect(initialDestinationBounds, closeToRect(clipExpandedBounds)); canvas.restore(); // save/restore returned the values to their original values expect(canvas.getLocalClipBounds(), initialLocalBounds); expect(canvas.getDestinationClipBounds(), initialDestinationBounds); canvas.save(); canvas.scale(2, 2); const Rect scaledExpandedBounds = Rect.fromLTRB(5, 5.5, 10.5, 13); expect(canvas.getLocalClipBounds(), closeToRect(scaledExpandedBounds)); // Destination bounds are unaffected by transform expect(canvas.getDestinationClipBounds(), closeToRect(clipExpandedBounds)); canvas.restore(); // save/restore returned the values to their original values expect(canvas.getLocalClipBounds(), initialLocalBounds); expect(canvas.getDestinationClipBounds(), initialDestinationBounds); }); test('Canvas.clipRRect(doAA=false) affects canvas.getClipBounds', () async { final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); const Rect clipBounds = Rect.fromLTRB(10.2, 11.3, 20.4, 25.7); final RRect clip = RRect.fromRectAndRadius(clipBounds, const Radius.circular(3)); canvas.clipRRect(clip, doAntiAlias: false); // Save initial return values for testing restored values final Rect initialLocalBounds = canvas.getLocalClipBounds(); final Rect initialDestinationBounds = canvas.getDestinationClipBounds(); expect(initialLocalBounds, closeToRect(clipBounds)); expect(initialDestinationBounds, closeToRect(clipBounds)); canvas.save(); canvas.clipRect(const Rect.fromLTRB(0, 0, 15, 15), doAntiAlias: false); // Both clip bounds have changed expect(canvas.getLocalClipBounds(), notCloseToRect(clipBounds)); expect(canvas.getDestinationClipBounds(), notCloseToRect(clipBounds)); // Previous return values have not changed expect(initialLocalBounds, closeToRect(clipBounds)); expect(initialDestinationBounds, closeToRect(clipBounds)); canvas.restore(); // save/restore returned the values to their original values expect(canvas.getLocalClipBounds(), initialLocalBounds); expect(canvas.getDestinationClipBounds(), initialDestinationBounds); canvas.save(); canvas.scale(2, 2); const Rect scaledClipBounds = Rect.fromLTRB(5.1, 5.65, 10.2, 12.85); expect(canvas.getLocalClipBounds(), closeToRect(scaledClipBounds)); // Destination bounds are unaffected by transform expect(canvas.getDestinationClipBounds(), closeToRect(clipBounds)); canvas.restore(); // save/restore returned the values to their original values expect(canvas.getLocalClipBounds(), initialLocalBounds); expect(canvas.getDestinationClipBounds(), initialDestinationBounds); }); test('Canvas.clipRRect with matrix affects canvas.getClipBounds', () async { final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); const Rect clipBounds1 = Rect.fromLTRB(0.0, 0.0, 10.0, 10.0); const Rect clipBounds2 = Rect.fromLTRB(10.0, 10.0, 20.0, 20.0); final RRect clip1 = RRect.fromRectAndRadius(clipBounds1, const Radius.circular(3)); final RRect clip2 = RRect.fromRectAndRadius(clipBounds2, const Radius.circular(3)); canvas.save(); canvas.clipRRect(clip1, doAntiAlias: false); canvas.translate(0, 10.0); canvas.clipRRect(clip1, doAntiAlias: false); expect(canvas.getDestinationClipBounds().isEmpty, isTrue); canvas.restore(); canvas.save(); canvas.clipRRect(clip1, doAntiAlias: false); canvas.translate(-10.0, -10.0); canvas.clipRRect(clip2, doAntiAlias: false); expect(canvas.getDestinationClipBounds(), clipBounds1); canvas.restore(); }); test('Canvas.clipPath(doAA=true) affects canvas.getClipBounds', () async { final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); const Rect clipBounds = Rect.fromLTRB(10.2, 11.3, 20.4, 25.7); const Rect clipExpandedBounds = Rect.fromLTRB(10, 11, 21, 26); final Path clip = Path()..addRect(clipBounds)..addOval(clipBounds); canvas.clipPath(clip); // Save initial return values for testing restored values final Rect initialLocalBounds = canvas.getLocalClipBounds(); final Rect initialDestinationBounds = canvas.getDestinationClipBounds(); expect(initialLocalBounds, closeToRect(clipExpandedBounds)); expect(initialDestinationBounds, closeToRect(clipExpandedBounds)); canvas.save(); canvas.clipRect(const Rect.fromLTRB(0, 0, 15, 15)); // Both clip bounds have changed expect(canvas.getLocalClipBounds(), notCloseToRect(clipExpandedBounds)); expect(canvas.getDestinationClipBounds(), notCloseToRect(clipExpandedBounds)); // Previous return values have not changed expect(initialLocalBounds, closeToRect(clipExpandedBounds)); expect(initialDestinationBounds, closeToRect(clipExpandedBounds)); canvas.restore(); // save/restore returned the values to their original values expect(canvas.getLocalClipBounds(), initialLocalBounds); expect(canvas.getDestinationClipBounds(), initialDestinationBounds); canvas.save(); canvas.scale(2, 2); const Rect scaledExpandedBounds = Rect.fromLTRB(5, 5.5, 10.5, 13); expect(canvas.getLocalClipBounds(), closeToRect(scaledExpandedBounds)); // Destination bounds are unaffected by transform expect(canvas.getDestinationClipBounds(), closeToRect(clipExpandedBounds)); canvas.restore(); // save/restore returned the values to their original values expect(canvas.getLocalClipBounds(), initialLocalBounds); expect(canvas.getDestinationClipBounds(), initialDestinationBounds); }); test('Canvas.clipPath(doAA=false) affects canvas.getClipBounds', () async { final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); const Rect clipBounds = Rect.fromLTRB(10.2, 11.3, 20.4, 25.7); final Path clip = Path()..addRect(clipBounds)..addOval(clipBounds); canvas.clipPath(clip, doAntiAlias: false); // Save initial return values for testing restored values final Rect initialLocalBounds = canvas.getLocalClipBounds(); final Rect initialDestinationBounds = canvas.getDestinationClipBounds(); expect(initialLocalBounds, closeToRect(clipBounds)); expect(initialDestinationBounds, closeToRect(clipBounds)); canvas.save(); canvas.clipRect(const Rect.fromLTRB(0, 0, 15, 15), doAntiAlias: false); // Both clip bounds have changed expect(canvas.getLocalClipBounds(), notCloseToRect(clipBounds)); expect(canvas.getDestinationClipBounds(), notCloseToRect(clipBounds)); // Previous return values have not changed expect(initialLocalBounds, closeToRect(clipBounds)); expect(initialDestinationBounds, closeToRect(clipBounds)); canvas.restore(); // save/restore returned the values to their original values expect(canvas.getLocalClipBounds(), initialLocalBounds); expect(canvas.getDestinationClipBounds(), initialDestinationBounds); canvas.save(); canvas.scale(2, 2); const Rect scaledClipBounds = Rect.fromLTRB(5.1, 5.65, 10.2, 12.85); expect(canvas.getLocalClipBounds(), closeToRect(scaledClipBounds)); // Destination bounds are unaffected by transform expect(canvas.getDestinationClipBounds(), closeToRect(clipBounds)); canvas.restore(); // save/restore returned the values to their original values expect(canvas.getLocalClipBounds(), initialLocalBounds); expect(canvas.getDestinationClipBounds(), initialDestinationBounds); }); test('Canvas.clipPath with matrix affects canvas.getClipBounds', () async { final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); const Rect clipBounds1 = Rect.fromLTRB(0.0, 0.0, 10.0, 10.0); const Rect clipBounds2 = Rect.fromLTRB(10.0, 10.0, 20.0, 20.0); final Path clip1 = Path()..addRect(clipBounds1)..addOval(clipBounds1); final Path clip2 = Path()..addRect(clipBounds2)..addOval(clipBounds2); canvas.save(); canvas.clipPath(clip1, doAntiAlias: false); canvas.translate(0, 10.0); canvas.clipPath(clip1, doAntiAlias: false); expect(canvas.getDestinationClipBounds().isEmpty, isTrue); canvas.restore(); canvas.save(); canvas.clipPath(clip1, doAntiAlias: false); canvas.translate(-10.0, -10.0); canvas.clipPath(clip2, doAntiAlias: false); expect(canvas.getDestinationClipBounds(), clipBounds1); canvas.restore(); }); test('Canvas.clipRect(diff) does not affect canvas.getClipBounds', () async { final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); const Rect clipBounds = Rect.fromLTRB(10.2, 11.3, 20.4, 25.7); canvas.clipRect(clipBounds, doAntiAlias: false); // Save initial return values for testing restored values final Rect initialLocalBounds = canvas.getLocalClipBounds(); final Rect initialDestinationBounds = canvas.getDestinationClipBounds(); expect(initialLocalBounds, closeToRect(clipBounds)); expect(initialDestinationBounds, closeToRect(clipBounds)); canvas.clipRect(const Rect.fromLTRB(0, 0, 15, 15), clipOp: ClipOp.difference, doAntiAlias: false); expect(canvas.getLocalClipBounds(), initialLocalBounds); expect(canvas.getDestinationClipBounds(), initialDestinationBounds); }); test('RestoreToCount can work', () async { final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); canvas.save(); canvas.save(); canvas.save(); canvas.save(); canvas.save(); expect(canvas.getSaveCount(), equals(6)); canvas.restoreToCount(2); expect(canvas.getSaveCount(), equals(2)); canvas.restore(); expect(canvas.getSaveCount(), equals(1)); }); test('RestoreToCount count less than 1, the stack should be reset', () async { final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); canvas.save(); canvas.save(); canvas.save(); canvas.save(); canvas.save(); expect(canvas.getSaveCount(), equals(6)); canvas.restoreToCount(0); expect(canvas.getSaveCount(), equals(1)); }); test('RestoreToCount count greater than current [getSaveCount], nothing would happend', () async { final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); canvas.save(); canvas.save(); canvas.save(); canvas.save(); canvas.save(); expect(canvas.getSaveCount(), equals(6)); canvas.restoreToCount(canvas.getSaveCount() + 1); expect(canvas.getSaveCount(), equals(6)); }); test('TextDecoration renders non-solid lines', () async { final File file = File(path.join(_flutterBuildPath, 'flutter', 'third_party', 'txt', 'assets', 'Roboto-Regular.ttf')); final Uint8List fontData = await file.readAsBytes(); await loadFontFromList(fontData, fontFamily: 'RobotoSlab'); final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); for (final (int index, TextDecorationStyle style) in TextDecorationStyle.values.indexed) { final ParagraphBuilder builder = ParagraphBuilder(ParagraphStyle()); builder.pushStyle(TextStyle( decoration: TextDecoration.underline, decorationStyle: style, decorationThickness: 1.0, decorationColor: const Color(0xFFFF0000), fontFamily: 'RobotoSlab', fontSize: 24.0, foreground: Paint()..color = const Color(0xFF0000FF), )); builder.addText(style.name); final Paragraph paragraph = builder.build(); paragraph.layout(const ParagraphConstraints(width: 1000)); // Draw and layout based on the index vertically. canvas.drawParagraph(paragraph, Offset(0, index * 40.0)); } final Picture picture = recorder.endRecording(); final Image image = await picture.toImage(200, 200); await comparer.addGoldenImage(image, 'text_decoration.png'); }); } Matcher listEquals(ByteData expected) => (dynamic v) { Expect.type<ByteData>(v); final ByteData value = v as ByteData; expect(value.lengthInBytes, expected.lengthInBytes); for (int i = 0; i < value.lengthInBytes; i++) { expect(value.getUint8(i), expected.getUint8(i)); } };
engine/testing/dart/canvas_test.dart/0
{ "file_path": "engine/testing/dart/canvas_test.dart", "repo_id": "engine", "token_count": 17904 }
392
// 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:io'; import 'dart:typed_data'; import 'dart:ui'; import 'package:litetest/litetest.dart'; import 'package:path/path.dart' as path; void main() { test('basic image descriptor - encoded - greyscale', () async { final Uint8List bytes = await readFile('2x2.png'); final ImmutableBuffer buffer = await ImmutableBuffer.fromUint8List(bytes); final ImageDescriptor descriptor = await ImageDescriptor.encoded(buffer); expect(descriptor.width, 2); expect(descriptor.height, 2); expect(descriptor.bytesPerPixel, 1); final Codec codec = await descriptor.instantiateCodec(); expect(codec.frameCount, 1); }); test('basic image descriptor - encoded - square', () async { final Uint8List bytes = await readFile('square.png'); final ImmutableBuffer buffer = await ImmutableBuffer.fromUint8List(bytes); final ImageDescriptor descriptor = await ImageDescriptor.encoded(buffer); expect(descriptor.width, 10); expect(descriptor.height, 10); expect(descriptor.bytesPerPixel, 4); final Codec codec = await descriptor.instantiateCodec(); expect(codec.frameCount, 1); }); test('basic image descriptor - encoded - animated', () async { final Uint8List bytes = await _getSkiaResource('test640x479.gif').readAsBytes(); final ImmutableBuffer buffer = await ImmutableBuffer.fromUint8List(bytes); final ImageDescriptor descriptor = await ImageDescriptor.encoded(buffer); expect(descriptor.width, 640); expect(descriptor.height, 479); expect(descriptor.bytesPerPixel, 4); final Codec codec = await descriptor.instantiateCodec(); expect(codec.frameCount, 4); expect(codec.repetitionCount, -1); }); test('basic image descriptor - raw', () async { final Uint8List bytes = Uint8List.fromList(List<int>.filled(16, 0xFFABCDEF)); final ImmutableBuffer buffer = await ImmutableBuffer.fromUint8List(bytes); final ImageDescriptor descriptor = ImageDescriptor.raw( buffer, width: 4, height: 4, rowBytes: 4 * 4, pixelFormat: PixelFormat.rgba8888, ); expect(descriptor.width, 4); expect(descriptor.height, 4); expect(descriptor.bytesPerPixel, 4); final Codec codec = await descriptor.instantiateCodec(); expect(codec.frameCount, 1); }); test('HEIC image', () async { final Uint8List bytes = await readFile('grill_chicken.heic'); final ImmutableBuffer buffer = await ImmutableBuffer.fromUint8List(bytes); final ImageDescriptor descriptor = await ImageDescriptor.encoded(buffer); expect(descriptor.width, 300); expect(descriptor.height, 400); expect(descriptor.bytesPerPixel, 4); final Codec codec = await descriptor.instantiateCodec(); expect(codec.frameCount, 1); }, skip: !(Platform.isAndroid || Platform.isIOS || Platform.isMacOS || Platform.isWindows)); } Future<Uint8List> readFile(String fileName, ) async { final File file = File(path.join('flutter', 'testing', 'resources', fileName)); return file.readAsBytes(); } /// Returns a File handle to a file in the skia/resources directory. File _getSkiaResource(String fileName) { // As Platform.script is not working for flutter_tester // (https://github.com/flutter/flutter/issues/12847), this is currently // assuming the curent working directory is engine/src. // This is fragile and should be changed once the Platform.script issue is // resolved. final String assetPath = path.join( 'flutter', 'third_party', 'skia', 'resources', 'images', fileName, ); return File(assetPath); }
engine/testing/dart/image_descriptor_test.dart/0
{ "file_path": "engine/testing/dart/image_descriptor_test.dart", "repo_id": "engine", "token_count": 1251 }
393
// 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:developer' as developer; import 'dart:typed_data'; import 'dart:ui'; import 'package:litetest/litetest.dart'; import 'package:vm_service/vm_service.dart' as vms; import 'package:vm_service/vm_service_io.dart'; import '../impeller_enabled.dart'; void main() { test('Capture an SKP ', () async { final developer.ServiceProtocolInfo info = await developer.Service.getInfo(); if (info.serverUri == null) { fail('This test must not be run with --disable-vm-service.'); } final vms.VmService vmService = await vmServiceConnectUri( 'ws://localhost:${info.serverUri!.port}${info.serverUri!.path}ws', ); final Completer<void> completer = Completer<void>(); PlatformDispatcher.instance.onBeginFrame = (Duration timeStamp) { final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); canvas.drawRect(const Rect.fromLTRB(10, 10, 20, 20), Paint()); final Picture picture = recorder.endRecording(); final SceneBuilder builder = SceneBuilder(); builder.addPicture(Offset.zero, picture); final Scene scene = builder.build(); PlatformDispatcher.instance.implicitView!.render(scene); scene.dispose(); completer.complete(); }; PlatformDispatcher.instance.scheduleFrame(); await completer.future; try { final vms.Response response = await vmService.callServiceExtension('_flutter.screenshotSkp'); expect(impellerEnabled, false); final String base64data = response.json!['skp'] as String; expect(base64data, isNotNull); expect(base64data, isNotEmpty); final Uint8List decoded = base64Decode(base64data); expect(decoded.sublist(0, 8), 'skiapict'.codeUnits); } on vms.RPCError catch (e) { expect(impellerEnabled, true); expect(e.toString(), contains('Cannot capture SKP screenshot with Impeller enabled.')); } await vmService.dispose(); }); }
engine/testing/dart/observatory/skp_test.dart/0
{ "file_path": "engine/testing/dart/observatory/skp_test.dart", "repo_id": "engine", "token_count": 778 }
394
// 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:path/path.dart' as path; String _flutterBuildDirectoryPath() { assert(Platform.environment.containsKey('FLUTTER_BUILD_DIRECTORY')); return Platform.environment['FLUTTER_BUILD_DIRECTORY']!; } const String _testPath = 'gen/flutter/lib/ui/fixtures/shaders'; /// Gets the [Directory] shader files that are generated by `lib/ui/fixtures/shaders`. /// /// `folderName` is a leaf folder within the generated directory. Directory shaderDirectory(String leafFolderName) { return Directory(path.joinAll(<String>[ ...path.split(_flutterBuildDirectoryPath()), ...path.split(_testPath), leafFolderName, ])); }
engine/testing/dart/shader_test_file_utils.dart/0
{ "file_path": "engine/testing/dart/shader_test_file_utils.dart", "repo_id": "engine", "token_count": 255 }
395
// 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_ELF_LOADER_H_ #define FLUTTER_TESTING_ELF_LOADER_H_ #include <memory> #include "flutter/common/settings.h" #include "flutter/fml/macros.h" #include "third_party/dart/runtime/bin/elf_loader.h" namespace flutter { namespace testing { inline constexpr const char* kDefaultAOTAppELFFileName = "app_elf_snapshot.so"; // This file name is what gen_snapshot defaults to. It is based off of the // name of the base file, with the `2` indicating that this split corresponds // to loading unit id of 2. The base module id is 1 and is omitted as it is not // considered a split. If dart changes the naming convention, this should be // changed to match, however, this is considered unlikely to happen. inline constexpr const char* kDefaultAOTAppELFSplitFileName = "app_elf_snapshot.so-2.part.so"; struct LoadedELFDeleter { void operator()(Dart_LoadedElf* elf) { ::Dart_UnloadELF(elf); } }; using UniqueLoadedELF = std::unique_ptr<Dart_LoadedElf, LoadedELFDeleter>; struct ELFAOTSymbols { UniqueLoadedELF loaded_elf; const uint8_t* vm_snapshot_data = nullptr; const uint8_t* vm_snapshot_instrs = nullptr; const uint8_t* vm_isolate_data = nullptr; const uint8_t* vm_isolate_instrs = nullptr; }; //------------------------------------------------------------------------------ /// @brief Attempts to resolve AOT symbols from the portable ELF loader. /// This location is automatically resolved from the fixtures /// generator. This only returns valid symbols when the VM is /// configured for AOT. /// /// @param[in] elf_filename The AOT ELF filename from the fixtures generator. /// /// @return The loaded ELF symbols. /// ELFAOTSymbols LoadELFSymbolFromFixturesIfNeccessary(std::string elf_filename); //------------------------------------------------------------------------------ /// @brief Attempts to resolve split loading unit AOT symbols from the /// portable ELF loader. If the dart code does not make use of /// deferred libraries, then there will be no split .so to load. /// This only returns valid symbols when the VM is configured for /// AOT. /// /// @param[in] elf_split_filename The split AOT ELF filename from the fixtures /// generator. /// /// @return The loaded ELF symbols. /// ELFAOTSymbols LoadELFSplitSymbolFromFixturesIfNeccessary( std::string elf_split_filename); //------------------------------------------------------------------------------ /// @brief Prepare the settings objects various AOT mappings resolvers with /// the symbols already loaded. This method does nothing in non-AOT /// runtime modes. /// /// @warning The symbols must not be collected till all shell instantiations /// made using the settings object are collected. /// /// @param[in/out] settings The settings whose AOT resolvers to populate. /// @param[in] symbols The symbols used to populate the settings object. /// /// @return If the settings object was correctly updated. /// bool PrepareSettingsForAOTWithSymbols(Settings& settings, const ELFAOTSymbols& symbols); } // namespace testing } // namespace flutter #endif // FLUTTER_TESTING_ELF_LOADER_H_
engine/testing/elf_loader.h/0
{ "file_path": "engine/testing/elf_loader.h", "repo_id": "engine", "token_count": 1125 }
396
# iOS Unit Tests These are the unit tests for iOS engine. They can be executed locally and are also run in LUCI builds. ## Running Tests from command line To build and run the iOS tests, use the `run_tests` script from the `src` directory. ```sh flutter/testing/run_tests.py --type=objc ``` And if you're on Apple Silicon: ```sh ./flutter/testing/run_tests.py \ --type=objc \ --ios-variant ios_debug_sim_unopt_arm64 ``` The `.xcresult` is automatically removed after testing ends. To change this: ```sh export FLUTTER_TEST_OUTPUTS_DIR=~/Desktop ``` To learn more: ``` flutter/testing/run_tests.py --help ``` ## Running Tests from Xcode After the `ios_test_flutter` target is built you can also run the tests inside of Xcode with `testing/ios/IosUnitTests/IosUnitTests.xcodeproj`. When you load the test project [IosUnitTests.xcodeproj](IosUnitTests.xcodeproj) into Xcode after running `run_tests.py`, only a few basic tests will appear initially. You have to run the test suite once in Xcode for the rest to appear. Select "iPhone 11" as the device, and press `command-u` to start all the tests running. Once the tests are done running, the tests that ran will appear in the sidebar, and you can pick the specific one you want to debug/run. If you modify the test or under-test files, you'll have to run [`run_tests.py`](../../run_tests.py) again. ## Adding Tests When you add a new unit test file, also add a reference to that file in [`shell/platform/darwin/ios/BUILD.gn`](../../../shell/platform/darwin/ios/BUILD.gn), under the `sources` list of the `ios_test_flutter` target. Once it's there, it will execute with the other tests.
engine/testing/ios/IosUnitTests/README.md/0
{ "file_path": "engine/testing/ios/IosUnitTests/README.md", "repo_id": "engine", "token_count": 539 }
397
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/testing/post_task_sync.h" #include "flutter/fml/synchronization/waitable_event.h" namespace flutter { namespace testing { void PostTaskSync(const fml::RefPtr<fml::TaskRunner>& task_runner, const std::function<void()>& function) { fml::AutoResetWaitableEvent latch; task_runner->PostTask([&] { function(); latch.Signal(); }); latch.Wait(); } } // namespace testing } // namespace flutter
engine/testing/post_task_sync.cc/0
{ "file_path": "engine/testing/post_task_sync.cc", "repo_id": "engine", "token_count": 211 }
398
// 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 <iostream> #include <optional> #include <string> #include "flutter/fml/backtrace.h" #include "flutter/fml/build_config.h" #include "flutter/fml/command_line.h" #include "flutter/testing/debugger_detection.h" #include "flutter/testing/test_args.h" #include "flutter/testing/test_timeout_listener.h" #include "gtest/gtest.h" #ifdef FML_OS_IOS #include <asl.h> #endif // FML_OS_IOS std::optional<fml::TimeDelta> GetTestTimeout() { const auto& command_line = flutter::testing::GetArgsForProcess(); std::string timeout_seconds; if (!command_line.GetOptionValue("timeout", &timeout_seconds)) { // No timeout specified. Default to 300s. return fml::TimeDelta::FromSeconds(300u); } const auto seconds = std::stoi(timeout_seconds); if (seconds < 1) { return std::nullopt; } return fml::TimeDelta::FromSeconds(seconds); } int main(int argc, char** argv) { fml::InstallCrashHandler(); flutter::testing::SetArgsForProcess(argc, argv); #ifdef FML_OS_IOS asl_log_descriptor(NULL, NULL, ASL_LEVEL_NOTICE, STDOUT_FILENO, ASL_LOG_DESCRIPTOR_WRITE); asl_log_descriptor(NULL, NULL, ASL_LEVEL_ERR, STDERR_FILENO, ASL_LOG_DESCRIPTOR_WRITE); #endif // FML_OS_IOS ::testing::InitGoogleTest(&argc, argv); GTEST_FLAG_SET(death_test_style, "threadsafe"); // Check if the user has specified a timeout. const auto timeout = GetTestTimeout(); if (!timeout.has_value()) { FML_LOG(INFO) << "Timeouts disabled via a command line flag."; return RUN_ALL_TESTS(); } // Check if the user is debugging the process. if (flutter::testing::GetDebuggerStatus() == flutter::testing::DebuggerStatus::kAttached) { FML_LOG(INFO) << "Debugger is attached. Suspending test timeouts."; return RUN_ALL_TESTS(); } auto timeout_listener = new flutter::testing::TestTimeoutListener(timeout.value()); auto& listeners = ::testing::UnitTest::GetInstance()->listeners(); listeners.Append(timeout_listener); auto result = RUN_ALL_TESTS(); delete listeners.Release(timeout_listener); return result; }
engine/testing/run_all_unittests.cc/0
{ "file_path": "engine/testing/run_all_unittests.cc", "repo_id": "engine", "token_count": 828 }
399
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 org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(AndroidJUnit4.class) @LargeTest public final class DrawSolidBlueScreenTest { @Rule @NonNull public ActivityTestRule<PlatformViewsActivity> activityRule = new ActivityTestRule<>( PlatformViewsActivity.class, /*initialTouchMode=*/ false, /*launchActivity=*/ false); @Test public void test() throws Exception { Intent intent = new Intent(Intent.ACTION_MAIN); intent.putExtra("scenario_name", "solid_blue"); ScreenshotUtil.capture(activityRule.launchActivity(intent), "DrawSolidBlueScreenTest"); } }
engine/testing/scenario_app/android/app/src/androidTest/java/dev/flutter/scenariosui/DrawSolidBlueScreenTest.java/0
{ "file_path": "engine/testing/scenario_app/android/app/src/androidTest/java/dev/flutter/scenariosui/DrawSolidBlueScreenTest.java", "repo_id": "engine", "token_count": 294 }
400
// 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 static io.flutter.Build.API_LEVELS; import android.content.res.AssetFileDescriptor; import android.graphics.Canvas; import android.graphics.ImageFormat; import android.graphics.LinearGradient; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.Shader.TileMode; import android.hardware.HardwareBuffer; import android.media.Image; import android.media.ImageReader; import android.media.ImageWriter; import android.media.MediaCodec; import android.media.MediaExtractor; import android.media.MediaFormat; import android.os.Build.VERSION; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; import android.util.Log; import android.view.Gravity; import android.view.Surface; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.FrameLayout.LayoutParams; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import androidx.core.util.Supplier; import io.flutter.view.TextureRegistry; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Map; import java.util.Objects; import java.util.concurrent.CountDownLatch; public class ExternalTextureFlutterActivity extends TestActivity { static final String TAG = "Scenarios"; private static final int SURFACE_WIDTH = 192; private static final int SURFACE_HEIGHT = 256; private SurfaceRenderer flutterRenderer; // Latch used to ensure both SurfaceRenderers produce a frame before taking a screenshot. private final CountDownLatch firstFrameLatch = new CountDownLatch(1); private long textureId = 0; private TextureRegistry.SurfaceProducer surfaceProducer; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); String surfaceRenderer = getIntent().getStringExtra("surface_renderer"); assert surfaceRenderer != null; flutterRenderer = selectSurfaceRenderer(surfaceRenderer, getIntent().getExtras()); // Create and place a SurfaceView above the Flutter content. SurfaceView surfaceView = new SurfaceView(getContext()); surfaceView.setZOrderMediaOverlay(true); surfaceView.setMinimumWidth(SURFACE_WIDTH); surfaceView.setMinimumHeight(SURFACE_HEIGHT); FrameLayout frameLayout = new FrameLayout(getContext()); frameLayout.addView( surfaceView, new LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL)); addContentView( frameLayout, new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); SurfaceHolder surfaceHolder = surfaceView.getHolder(); surfaceHolder.setFixedSize(SURFACE_WIDTH, SURFACE_HEIGHT); } @Override public void waitUntilFlutterRendered() { super.waitUntilFlutterRendered(); try { firstFrameLatch.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } } private SurfaceRenderer selectSurfaceRenderer(String surfaceRenderer, Bundle extras) { switch (surfaceRenderer) { case "image": if (VERSION.SDK_INT >= API_LEVELS.API_23) { // CanvasSurfaceRenderer doesn't work correctly when used with ImageSurfaceRenderer. // Use MediaSurfaceRenderer for now. return new ImageSurfaceRenderer( selectSurfaceRenderer("media", extras), extras.getParcelable("crop")); } else { throw new RuntimeException("ImageSurfaceRenderer not supported"); } case "media": return new MediaSurfaceRenderer(this::createMediaExtractor, extras.getInt("rotation", 0)); case "canvas": default: return new CanvasSurfaceRenderer(); } } private MediaExtractor createMediaExtractor() { // Sample Video generated with FFMPEG. // ffmpeg -loop 1 -i ~/engine/src/flutter/lib/ui/fixtures/DashInNooglerHat.jpg -c:v libx264 // -profile:v main -level:v 5.2 -t 1 -r 1 -vf scale=192:256 -b:v 1M sample.mp4 try { MediaExtractor extractor = new MediaExtractor(); try (AssetFileDescriptor afd = getAssets().openFd("sample.mp4")) { extractor.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength()); } return extractor; } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e); } } @Override public void onPause() { flutterRenderer.destroy(); surfaceProducer.release(); super.onPause(); } @Override public void onFlutterUiDisplayed() { surfaceProducer = Objects.requireNonNull(getFlutterEngine()).getRenderer().createSurfaceProducer(); surfaceProducer.setSize(SURFACE_WIDTH, SURFACE_HEIGHT); flutterRenderer.attach(surfaceProducer.getSurface(), firstFrameLatch); flutterRenderer.repaint(); textureId = surfaceProducer.id(); super.onFlutterUiDisplayed(); } @Override protected void getScenarioParams(@NonNull Map<String, Object> args) { super.getScenarioParams(args); args.put("texture_id", textureId); args.put("texture_width", SURFACE_WIDTH); args.put("texture_height", SURFACE_HEIGHT); } private interface SurfaceRenderer { void attach(Surface surface, CountDownLatch onFirstFrame); void repaint(); void destroy(); } /** Paints a simple gradient onto the attached Surface. */ private static class CanvasSurfaceRenderer implements SurfaceRenderer { private Surface surface; private CountDownLatch onFirstFrame; protected CanvasSurfaceRenderer() {} @Override public void attach(Surface surface, CountDownLatch onFirstFrame) { this.surface = surface; this.onFirstFrame = onFirstFrame; } @Override public void repaint() { Canvas canvas = VERSION.SDK_INT >= API_LEVELS.API_23 ? surface.lockHardwareCanvas() : surface.lockCanvas(null); Paint paint = new Paint(); paint.setShader( new LinearGradient( 0.0f, 0.0f, canvas.getWidth(), canvas.getHeight(), new int[] { // Cyan (#00FFFF) 0xFF00FFFF, // Magenta (#FF00FF) 0xFFFF00FF, // Yellow (#FFFF00) 0xFFFFFF00, }, null, TileMode.REPEAT)); canvas.drawPaint(paint); surface.unlockCanvasAndPost(canvas); if (onFirstFrame != null) { onFirstFrame.countDown(); onFirstFrame = null; } } @Override public void destroy() {} } /** Decodes a sample video into the attached Surface. */ private static class MediaSurfaceRenderer implements SurfaceRenderer { private final Supplier<MediaExtractor> extractorSupplier; private final int rotation; private CountDownLatch onFirstFrame; private Surface surface; private MediaExtractor extractor; private MediaFormat format; private Thread decodeThread; protected MediaSurfaceRenderer(Supplier<MediaExtractor> extractorSupplier, int rotation) { this.extractorSupplier = extractorSupplier; this.rotation = rotation; } @Override public void attach(Surface surface, CountDownLatch onFirstFrame) { this.surface = surface; this.onFirstFrame = onFirstFrame; extractor = extractorSupplier.get(); format = extractor.getTrackFormat(0); // NOTE: MediaFormat.KEY_ROTATION was not available until 23+, but the key is still handled on // API 21+. format.setInteger("rotation-degrees", rotation); decodeThread = new Thread(this::decodeThreadMain); decodeThread.start(); } private void decodeThreadMain() { try { MediaCodec codec = MediaCodec.createDecoderByType( Objects.requireNonNull(format.getString(MediaFormat.KEY_MIME))); codec.configure(format, surface, null, 0); codec.start(); // Track 0 is always the video track, since the sample video doesn't contain audio. extractor.selectTrack(0); MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo(); boolean seenEOS = false; long startTimeNs = System.nanoTime(); int frameCount = 0; while (true) { // Move samples (video frames) from the extractor into the decoder, as long as we haven't // consumed all samples. if (!seenEOS) { int inputBufferIndex = codec.dequeueInputBuffer(-1); ByteBuffer inputBuffer = codec.getInputBuffer(inputBufferIndex); assert inputBuffer != null; int sampleSize = extractor.readSampleData(inputBuffer, 0); if (sampleSize >= 0) { long presentationTimeUs = extractor.getSampleTime(); codec.queueInputBuffer(inputBufferIndex, 0, sampleSize, presentationTimeUs, 0); extractor.advance(); } else { codec.queueInputBuffer( inputBufferIndex, 0, 0, 0, MediaCodec.BUFFER_FLAG_END_OF_STREAM); seenEOS = true; } } // Then consume decoded video frames from the decoder. These frames are automatically // pushed to the attached Surface, so this schedules them for present. int outputBufferIndex = codec.dequeueOutputBuffer(bufferInfo, 10000); boolean lastBuffer = (bufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0; if (outputBufferIndex >= 0) { if (bufferInfo.size > 0) { if (onFirstFrame != null) { onFirstFrame.countDown(); onFirstFrame = null; } Log.w(TAG, "Presenting frame " + frameCount); frameCount++; codec.releaseOutputBuffer( outputBufferIndex, startTimeNs + (bufferInfo.presentationTimeUs * 1000)); } } // Exit the loop if there are no more frames available. if (lastBuffer) { break; } } codec.stop(); codec.release(); extractor.release(); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e); } } @Override public void repaint() {} @Override public void destroy() { try { decodeThread.join(); } catch (InterruptedException e) { e.printStackTrace(); throw new RuntimeException(e); } } } /** * Takes frames from the inner SurfaceRenderer and feeds it through an ImageReader and ImageWriter * pair. */ @RequiresApi(API_LEVELS.API_23) private static class ImageSurfaceRenderer implements SurfaceRenderer { private final SurfaceRenderer inner; private final Rect crop; private CountDownLatch onFirstFrame; private ImageReader reader; private ImageWriter writer; private Handler handler; private HandlerThread handlerThread; private boolean canReadImage = true; private boolean canWriteImage = true; protected ImageSurfaceRenderer(SurfaceRenderer inner, Rect crop) { this.inner = inner; this.crop = crop; } @Override public void attach(Surface surface, CountDownLatch onFirstFrame) { this.onFirstFrame = onFirstFrame; if (VERSION.SDK_INT >= API_LEVELS.API_29) { // On Android Q+, use PRIVATE image format. // Also let the frame producer know the images will // be sampled from by the GPU. writer = ImageWriter.newInstance(surface, 3, ImageFormat.PRIVATE); reader = ImageReader.newInstance( SURFACE_WIDTH, SURFACE_HEIGHT, ImageFormat.PRIVATE, 2, HardwareBuffer.USAGE_GPU_SAMPLED_IMAGE); } else { // Before Android Q, this will change the format of the surface to match the images. writer = ImageWriter.newInstance(surface, 3); reader = ImageReader.newInstance(SURFACE_WIDTH, SURFACE_HEIGHT, writer.getFormat(), 2); } inner.attach(reader.getSurface(), null); handlerThread = new HandlerThread("image reader/writer thread"); handlerThread.start(); handler = new Handler(handlerThread.getLooper()); reader.setOnImageAvailableListener(this::onImageAvailable, handler); writer.setOnImageReleasedListener(this::onImageReleased, handler); } private void onImageAvailable(ImageReader reader) { Log.v(TAG, "Image available"); if (!canWriteImage) { // If the ImageWriter hasn't released the latest image, don't attempt to enqueue another // image. // Otherwise the reader writer pair locks up if the writer runs behind, as the reader runs // out of images and the writer has no more space for images. canReadImage = true; return; } canReadImage = false; Image image = reader.acquireLatestImage(); image.setCropRect(crop); try { canWriteImage = false; writer.queueInputImage(image); } catch (IllegalStateException e) { // If the output surface disconnects, this method will be interrupted with an // IllegalStateException. // Simply log and return. Log.i(TAG, "Surface disconnected from ImageWriter", e); image.close(); } Log.v(TAG, "Output image"); if (onFirstFrame != null) { onFirstFrame.countDown(); onFirstFrame = null; } } private void tryAcquireImage() { if (canReadImage) { onImageAvailable(reader); } } private void onImageReleased(ImageWriter imageWriter) { Log.v(TAG, "Image released"); if (!canWriteImage) { canWriteImage = true; if (canReadImage) { // Try acquire the image in a handler message, as we may have another call to // onImageAvailable in the thread's message queue. handler.post(this::tryAcquireImage); } } } @Override public void repaint() { inner.repaint(); } @Override public void destroy() { Log.i(TAG, "Destroying ImageSurfaceRenderer"); inner.destroy(); handler.post(this::destroyReaderWriter); } private void destroyReaderWriter() { writer.close(); Log.i(TAG, "ImageWriter destroyed"); reader.close(); Log.i(TAG, "ImageReader destroyed"); handlerThread.quitSafely(); } } }
engine/testing/scenario_app/android/app/src/main/java/dev/flutter/scenarios/ExternalTextureFlutterActivity.java/0
{ "file_path": "engine/testing/scenario_app/android/app/src/main/java/dev/flutter/scenarios/ExternalTextureFlutterActivity.java", "repo_id": "engine", "token_count": 5836 }
401
# This is a Gradle generated file for dependency locking. # Manual edits can break the build and are not advised. # This file is expected to be part of source control. androidx.databinding:databinding-common:7.4.2=classpath androidx.databinding:databinding-compiler-common:7.4.2=classpath com.android.databinding:baseLibrary:7.4.2=classpath com.android.tools.analytics-library:crash:30.4.2=classpath com.android.tools.analytics-library:protos:30.4.2=classpath com.android.tools.analytics-library:shared:30.4.2=classpath com.android.tools.analytics-library:tracker:30.4.2=classpath com.android.tools.build.jetifier:jetifier-core:1.0.0-beta10=classpath com.android.tools.build.jetifier:jetifier-processor:1.0.0-beta10=classpath com.android.tools.build:aapt2-proto:7.4.2-8841542=classpath com.android.tools.build:aaptcompiler:7.4.2=classpath com.android.tools.build:apksig:7.4.2=classpath com.android.tools.build:apkzlib:7.4.2=classpath com.android.tools.build:builder-model:7.4.2=classpath com.android.tools.build:builder-test-api:7.4.2=classpath com.android.tools.build:builder:7.4.2=classpath com.android.tools.build:bundletool:1.11.4=classpath com.android.tools.build:gradle-api:7.4.2=classpath com.android.tools.build:gradle-settings-api:7.4.2=classpath com.android.tools.build:gradle:7.4.2=classpath com.android.tools.build:manifest-merger:30.4.2=classpath com.android.tools.build:transform-api:2.0.0-deprecated-use-gradle-api=classpath com.android.tools.ddms:ddmlib:30.4.2=classpath com.android.tools.layoutlib:layoutlib-api:30.4.2=classpath com.android.tools.lint:lint-model:30.4.2=classpath com.android.tools.lint:lint-typedef-remover:30.4.2=classpath com.android.tools.utp:android-device-provider-ddmlib-proto:30.4.2=classpath com.android.tools.utp:android-device-provider-gradle-proto:30.4.2=classpath com.android.tools.utp:android-test-plugin-host-additional-test-output-proto:30.4.2=classpath com.android.tools.utp:android-test-plugin-host-coverage-proto:30.4.2=classpath com.android.tools.utp:android-test-plugin-host-retention-proto:30.4.2=classpath com.android.tools.utp:android-test-plugin-result-listener-gradle-proto:30.4.2=classpath com.android.tools:annotations:30.4.2=classpath com.android.tools:common:30.4.2=classpath com.android.tools:dvlib:30.4.2=classpath com.android.tools:repository:30.4.2=classpath com.android.tools:sdk-common:30.4.2=classpath com.android.tools:sdklib:30.4.2=classpath com.android:signflinger:7.4.2=classpath com.android:zipflinger:7.4.2=classpath com.facebook.testing.screenshot:plugin:0.12.0=classpath com.github.gundy:semver4j:0.16.4=classpath com.google.android:annotations:4.1.1.4=classpath com.google.api.grpc:proto-google-common-protos:2.0.1=classpath com.google.auto.value:auto-value-annotations:1.6.2=classpath com.google.code.findbugs:jsr305:3.0.2=classpath com.google.code.gson:gson:2.8.9=classpath com.google.crypto.tink:tink:1.3.0-rc2=classpath com.google.dagger:dagger:2.28.3=classpath com.google.errorprone:error_prone_annotations:2.4.0=classpath com.google.flatbuffers:flatbuffers-java:1.12.0=classpath com.google.guava:failureaccess:1.0.1=classpath com.google.guava:guava:30.1-jre=classpath com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=classpath com.google.j2objc:j2objc-annotations:1.3=classpath com.google.jimfs:jimfs:1.1=classpath com.google.protobuf:protobuf-java-util:3.17.2=classpath com.google.protobuf:protobuf-java:3.17.2=classpath com.google.testing.platform:core-proto:0.0.8-alpha08=classpath com.googlecode.juniversalchardet:juniversalchardet:1.0.3=classpath com.squareup:javapoet:1.10.0=classpath com.squareup:javawriter:2.5.0=classpath com.sun.activation:javax.activation:1.2.0=classpath com.sun.istack:istack-commons-runtime:3.0.8=classpath com.sun.xml.fastinfoset:FastInfoset:1.2.16=classpath commons-codec:commons-codec:1.11=classpath commons-io:commons-io:2.4=classpath commons-logging:commons-logging:1.2=classpath de.undercouch:gradle-download-task:4.1.1=classpath io.grpc:grpc-api:1.39.0=classpath io.grpc:grpc-context:1.39.0=classpath io.grpc:grpc-core:1.39.0=classpath io.grpc:grpc-netty:1.39.0=classpath io.grpc:grpc-protobuf-lite:1.39.0=classpath io.grpc:grpc-protobuf:1.39.0=classpath io.grpc:grpc-stub:1.39.0=classpath io.netty:netty-buffer:4.1.52.Final=classpath io.netty:netty-codec-http2:4.1.52.Final=classpath io.netty:netty-codec-http:4.1.52.Final=classpath io.netty:netty-codec-socks:4.1.52.Final=classpath io.netty:netty-codec:4.1.52.Final=classpath io.netty:netty-common:4.1.52.Final=classpath io.netty:netty-handler-proxy:4.1.52.Final=classpath io.netty:netty-handler:4.1.52.Final=classpath io.netty:netty-resolver:4.1.52.Final=classpath io.netty:netty-transport:4.1.52.Final=classpath io.perfmark:perfmark-api:0.23.0=classpath jakarta.activation:jakarta.activation-api:1.2.1=classpath jakarta.xml.bind:jakarta.xml.bind-api:2.3.2=classpath javax.annotation:javax.annotation-api:1.3.2=classpath javax.inject:javax.inject:1=classpath net.java.dev.jna:jna-platform:5.6.0=classpath net.java.dev.jna:jna:5.6.0=classpath net.sf.jopt-simple:jopt-simple:4.9=classpath net.sf.kxml:kxml2:2.3.0=classpath org.apache.commons:commons-compress:1.20=classpath org.apache.httpcomponents:httpclient:4.5.13=classpath org.apache.httpcomponents:httpcore:4.4.13=classpath org.apache.httpcomponents:httpmime:4.5.6=classpath org.bitbucket.b_c:jose4j:0.7.0=classpath org.bouncycastle:bcpkix-jdk15on:1.67=classpath org.bouncycastle:bcprov-jdk15on:1.67=classpath org.checkerframework:checker-qual:3.5.0=classpath org.codehaus.mojo:animal-sniffer-annotations:1.19=classpath org.glassfish.jaxb:jaxb-runtime:2.3.2=classpath org.glassfish.jaxb:txw2:2.3.2=classpath org.jdom:jdom2:2.0.6=classpath org.jetbrains.intellij.deps:trove4j:1.0.20200330=classpath org.jetbrains.kotlin:kotlin-android-extensions:1.6.10=classpath org.jetbrains.kotlin:kotlin-annotation-processing-gradle:1.6.10=classpath org.jetbrains.kotlin:kotlin-build-common:1.6.10=classpath org.jetbrains.kotlin:kotlin-compiler-embeddable:1.6.10=classpath org.jetbrains.kotlin:kotlin-compiler-runner:1.6.10=classpath org.jetbrains.kotlin:kotlin-daemon-client:1.6.10=classpath org.jetbrains.kotlin:kotlin-daemon-embeddable:1.6.10=classpath org.jetbrains.kotlin:kotlin-gradle-plugin-api:1.6.10=classpath org.jetbrains.kotlin:kotlin-gradle-plugin-model:1.6.10=classpath org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.10=classpath org.jetbrains.kotlin:kotlin-klib-commonizer-api:1.6.10=classpath org.jetbrains.kotlin:kotlin-native-utils:1.6.10=classpath org.jetbrains.kotlin:kotlin-project-model:1.6.10=classpath org.jetbrains.kotlin:kotlin-reflect:1.7.10=classpath org.jetbrains.kotlin:kotlin-scripting-common:1.6.10=classpath org.jetbrains.kotlin:kotlin-scripting-compiler-embeddable:1.6.10=classpath org.jetbrains.kotlin:kotlin-scripting-compiler-impl-embeddable:1.6.10=classpath org.jetbrains.kotlin:kotlin-scripting-jvm:1.6.10=classpath org.jetbrains.kotlin:kotlin-stdlib-common:1.7.10=classpath org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.7.10=classpath org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.7.10=classpath org.jetbrains.kotlin:kotlin-stdlib:1.7.10=classpath org.jetbrains.kotlin:kotlin-tooling-metadata:1.6.10=classpath org.jetbrains.kotlin:kotlin-util-io:1.6.10=classpath org.jetbrains.kotlin:kotlin-util-klib:1.6.10=classpath org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.5.0=classpath org.jetbrains:annotations:13.0=classpath org.json:json:20180813=classpath org.jvnet.staxex:stax-ex:1.8.1=classpath org.ow2.asm:asm-analysis:9.2=classpath org.ow2.asm:asm-commons:9.2=classpath org.ow2.asm:asm-tree:9.2=classpath org.ow2.asm:asm-util:9.2=classpath org.ow2.asm:asm:9.2=classpath org.slf4j:slf4j-api:1.7.30=classpath org.tensorflow:tensorflow-lite-metadata:0.1.0-rc2=classpath xerces:xercesImpl:2.12.0=classpath xml-apis:xml-apis:1.4.01=classpath empty=
engine/testing/scenario_app/android/buildscript-gradle.lockfile/0
{ "file_path": "engine/testing/scenario_app/android/buildscript-gradle.lockfile", "repo_id": "engine", "token_count": 3476 }
402
# Scenario App: iOS Tests As mentioned in the [top-level README](../README.md), this directory contains the iOS-specific native code and tests for the [scenario app](../lib). To run the tests, you will need to build the engine with the appropriate configuration. For example, after building `ios_debug_sim_unopt` (to run on Intel Macs) or `ios_debug_sim_unopt_arm64` (to run on ARM Macs), run: ```sh # From the root of the engine repository $ ./testing/run_ios_tests.sh ios_debug_sim_unopt ``` or ```sh # From the root of the engine repository $ ./testing/run_ios_tests.sh ios_debug_sim_unopt_arm64 ``` To run or debug in Xcode, open the xcodeproj file located in `<engine_out_dir>/ios_debug_sim_unopt/scenario_app/Scenarios/Scenarios.xcodeproj`. ## CI Configuration See [`ci/builders/mac_unopt.json`](../../../../ci/builders/mac_unopt.json), and grep for `run_ios_tests.sh`. ## iOS Platform View Tests For PlatformView tests on iOS, edit the dictionaries in [AppDelegate.m](Scenarios/Scenarios/AppDelegate.m) and [GoldenTestManager.m](Scenarios/ScenariosUITests/GoldenTestManager.m) so that the correct golden image can be found. Also, add a [GoldenPlatformViewTests](Scenarios/ScenariosUITests/GoldenPlatformViewTests.h) in [PlatformViewUITests.m](Scenarios/ScenariosUITests/PlatformViewUITests.m). If `PlatformViewRotation` is failing, make sure `Simulator app Device > Rotate Device Automatically` is selected, or run: ```bash defaults write com.apple.iphonesimulator RotateWindowWhenSignaledByGuest -int 1 ``` ## Generating Golden Images on iOS Screenshots are saved as [XCTAttachment](https://developer.apple.com/documentation/xctest/activities_and_attachments/adding_attachments_to_tests_and_activities?language=objc)'s. A path in the form of `/Users/$USER/Library/Developer/Xcode/DerivedData/Scenarios-$HASH` will be printed to the console. Inside that directory there is a directory `./Build/Products/Debug-iphonesimulator/ScenariosUITests-Runner.app/PlugIns/ScenariosUITests.xctest/` which is where all the images that were compared against golden reside.
engine/testing/scenario_app/ios/README.md/0
{ "file_path": "engine/testing/scenario_app/ios/README.md", "repo_id": "engine", "token_count": 684 }
403
// 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 FLUTTER_TESTING_SCENARIO_APP_IOS_SCENARIOS_SCENARIOS_CONTINUOUSTEXTURE_H_ #define FLUTTER_TESTING_SCENARIO_APP_IOS_SCENARIOS_SCENARIOS_CONTINUOUSTEXTURE_H_ #import <Flutter/Flutter.h> #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN // A texture plugin that ready textures continuously. @interface ContinuousTexture : NSObject <FlutterPlugin> @end // The testing texture used by |ContinuousTexture| @interface FlutterScenarioTestTexture : NSObject <FlutterTexture> @end NS_ASSUME_NONNULL_END #endif // FLUTTER_TESTING_SCENARIO_APP_IOS_SCENARIOS_SCENARIOS_CONTINUOUSTEXTURE_H_
engine/testing/scenario_app/ios/Scenarios/Scenarios/ContinuousTexture.h/0
{ "file_path": "engine/testing/scenario_app/ios/Scenarios/Scenarios/ContinuousTexture.h", "repo_id": "engine", "token_count": 282 }
404
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import <Flutter/Flutter.h> #import <XCTest/XCTest.h> #import "AppDelegate.h" @interface FlutterEngineTest : XCTestCase @end @implementation FlutterEngineTest extern NSNotificationName const FlutterViewControllerWillDealloc; - (void)testIsolateId { FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:nil]; XCTAssertNil(engine.isolateId); [self keyValueObservingExpectationForObject:engine keyPath:@"isolateId" handler:nil]; XCTAssertTrue([engine runWithEntrypoint:nil]); [self waitForExpectationsWithTimeout:30.0 handler:nil]; XCTAssertNotNil(engine.isolateId); XCTAssertTrue([engine.isolateId hasPrefix:@"isolates/"]); [engine destroyContext]; XCTAssertNil(engine.isolateId); } - (void)testChannelSetup { FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:nil]; XCTAssertNil(engine.navigationChannel); XCTAssertNil(engine.platformChannel); XCTAssertNil(engine.lifecycleChannel); XCTAssertTrue([engine run]); XCTAssertNotNil(engine.navigationChannel); XCTAssertNotNil(engine.platformChannel); XCTAssertNotNil(engine.lifecycleChannel); [engine destroyContext]; XCTAssertNil(engine.navigationChannel); XCTAssertNil(engine.platformChannel); XCTAssertNil(engine.lifecycleChannel); } // https://github.com/flutter/flutter/issues/123776 - (void)testReleaseViewControllerAfterDestroyContextInHeadlessMode { FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" project:nil allowHeadlessExecution:YES]; XCTAssertNil(engine.navigationChannel); XCTAssertNil(engine.platformChannel); XCTAssertNil(engine.lifecycleChannel); XCTAssertTrue([engine run]); XCTAssertNotNil(engine.navigationChannel); XCTAssertNotNil(engine.platformChannel); XCTAssertNotNil(engine.lifecycleChannel); XCTestExpectation* expectation = [[XCTestExpectation alloc] initWithDescription:@"notification called"]; @autoreleasepool { FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; [engine setViewController:viewController]; [engine destroyContext]; [[NSNotificationCenter defaultCenter] addObserverForName:FlutterViewControllerWillDealloc object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification* _Nonnull note) { [expectation fulfill]; }]; viewController = nil; } [self waitForExpectations:@[ expectation ] timeout:30.0]; XCTAssertNil(engine.navigationChannel); XCTAssertNil(engine.platformChannel); XCTAssertNil(engine.lifecycleChannel); } @end
engine/testing/scenario_app/ios/Scenarios/ScenariosTests/FlutterEngineTest.m/0
{ "file_path": "engine/testing/scenario_app/ios/Scenarios/ScenariosTests/FlutterEngineTest.m", "repo_id": "engine", "token_count": 1424 }
405
// 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 <XCTest/XCTest.h> static const NSInteger kSecondsToWaitForPlatformView = 30; @interface PlatformViewGestureRecognizerTests : XCTestCase @end @implementation PlatformViewGestureRecognizerTests - (void)setUp { self.continueAfterFailure = NO; } - (void)testRejectPolicyUtilTouchesEnded { XCUIApplication* app = [[XCUIApplication alloc] init]; app.launchArguments = @[ @"--gesture-reject-after-touches-ended" ]; [app launch]; NSPredicate* predicateToFindPlatformView = [NSPredicate predicateWithBlock:^BOOL(id _Nullable evaluatedObject, NSDictionary<NSString*, id>* _Nullable bindings) { XCUIElement* element = evaluatedObject; return [element.identifier hasPrefix:@"platform_view"]; }]; XCUIElement* textView = [app.otherElements elementMatchingPredicate:predicateToFindPlatformView].textViews.firstMatch; if (![textView waitForExistenceWithTimeout:kSecondsToWaitForPlatformView]) { NSLog(@"%@", app.debugDescription); XCTFail(@"Failed due to not able to find any textView with %@ seconds", @(kSecondsToWaitForPlatformView)); } XCTAssertNotNil(textView); XCTAssertEqualObjects(textView.label, @""); NSPredicate* predicate = [NSPredicate predicateWithFormat:@"label == %@", @"-gestureTouchesBegan-gestureTouchesEnded"]; XCTNSPredicateExpectation* exception = [[XCTNSPredicateExpectation alloc] initWithPredicate:predicate object:textView]; [textView tap]; [self waitForExpectations:@[ exception ] timeout:kSecondsToWaitForPlatformView]; XCTAssertEqualObjects(textView.label, @"-gestureTouchesBegan-gestureTouchesEnded"); } - (void)testRejectPolicyEager { XCUIApplication* app = [[XCUIApplication alloc] init]; app.launchArguments = @[ @"--gesture-reject-eager" ]; [app launch]; NSPredicate* predicateToFindPlatformView = [NSPredicate predicateWithBlock:^BOOL(id _Nullable evaluatedObject, NSDictionary<NSString*, id>* _Nullable bindings) { XCUIElement* element = evaluatedObject; return [element.identifier hasPrefix:@"platform_view"]; }]; XCUIElement* textView = [app.otherElements elementMatchingPredicate:predicateToFindPlatformView].textViews.firstMatch; if (![textView waitForExistenceWithTimeout:kSecondsToWaitForPlatformView]) { NSLog(@"%@", app.debugDescription); XCTFail(@"Failed due to not able to find any textView with %@ seconds", @(kSecondsToWaitForPlatformView)); } XCTAssertNotNil(textView); XCTAssertEqualObjects(textView.label, @""); NSPredicate* predicate = [NSPredicate predicateWithBlock:^BOOL(id _Nullable evaluatedObject, NSDictionary<NSString*, id>* _Nullable bindings) { XCUIElement* view = (XCUIElement*)evaluatedObject; return [view.label containsString:@"-gestureTouchesBegan"]; }]; XCTNSPredicateExpectation* exception = [[XCTNSPredicateExpectation alloc] initWithPredicate:predicate object:textView]; [textView tap]; [self waitForExpectations:@[ exception ] timeout:kSecondsToWaitForPlatformView]; XCTAssertTrue([textView.label containsString:@"-gestureTouchesBegan"]); } - (void)testAccept { XCUIApplication* app = [[XCUIApplication alloc] init]; app.launchArguments = @[ @"--gesture-accept" ]; [app launch]; NSPredicate* predicateToFindPlatformView = [NSPredicate predicateWithBlock:^BOOL(id _Nullable evaluatedObject, NSDictionary<NSString*, id>* _Nullable bindings) { XCUIElement* element = evaluatedObject; return [element.identifier hasPrefix:@"platform_view"]; }]; XCUIElement* textView = [app.otherElements elementMatchingPredicate:predicateToFindPlatformView].textViews.firstMatch; if (![textView waitForExistenceWithTimeout:kSecondsToWaitForPlatformView]) { NSLog(@"%@", app.debugDescription); XCTFail(@"Failed due to not able to find any textView with %@ seconds", @(kSecondsToWaitForPlatformView)); } XCTAssertNotNil(textView); XCTAssertEqualObjects(textView.label, @""); NSPredicate* predicate = [NSPredicate predicateWithFormat:@"label == %@", @"-gestureTouchesBegan-gestureTouchesEnded-platformViewTapped"]; XCTNSPredicateExpectation* exception = [[XCTNSPredicateExpectation alloc] initWithPredicate:predicate object:textView]; [textView tap]; [self waitForExpectations:@[ exception ] timeout:kSecondsToWaitForPlatformView]; XCTAssertEqualObjects(textView.label, @"-gestureTouchesBegan-gestureTouchesEnded-platformViewTapped"); } - (void)testGestureWithMaskViewBlockingPlatformView { XCUIApplication* app = [[XCUIApplication alloc] init]; app.launchArguments = @[ @"--gesture-accept", @"--maskview-blocking" ]; [app launch]; NSPredicate* predicateToFindPlatformView = [NSPredicate predicateWithBlock:^BOOL(id _Nullable evaluatedObject, NSDictionary<NSString*, id>* _Nullable bindings) { XCUIElement* element = evaluatedObject; return [element.identifier hasPrefix:@"platform_view"]; }]; XCUIElement* textView = [app.otherElements elementMatchingPredicate:predicateToFindPlatformView].textViews.firstMatch; if (![textView waitForExistenceWithTimeout:kSecondsToWaitForPlatformView]) { NSLog(@"%@", app.debugDescription); XCTFail(@"Failed due to not able to find any platformView with %@ seconds", @(kSecondsToWaitForPlatformView)); } XCTAssertNotNil(textView); XCTAssertEqualObjects(textView.label, @""); NSPredicate* predicate = [NSPredicate predicateWithFormat:@"label == %@", @"-gestureTouchesBegan-gestureTouchesEnded-platformViewTapped"]; XCTNSPredicateExpectation* exception = [[XCTNSPredicateExpectation alloc] initWithPredicate:predicate object:textView]; XCUICoordinate* coordinate = [self getNormalizedCoordinate:app point:CGVectorMake(textView.frame.origin.x + 10, textView.frame.origin.y + 10)]; [coordinate tap]; [self waitForExpectations:@[ exception ] timeout:kSecondsToWaitForPlatformView]; XCTAssertEqualObjects(textView.label, @"-gestureTouchesBegan-gestureTouchesEnded-platformViewTapped"); } - (XCUICoordinate*)getNormalizedCoordinate:(XCUIApplication*)app point:(CGVector)vector { XCUICoordinate* appZero = [app coordinateWithNormalizedOffset:CGVectorMake(0, 0)]; XCUICoordinate* coordinate = [appZero coordinateWithOffset:vector]; return coordinate; } - (void)testGestureWithOverlappingPlatformViews { XCUIApplication* app = [[XCUIApplication alloc] init]; app.launchArguments = @[ @"--gesture-accept-with-overlapping-platform-views" ]; [app launch]; XCUIElement* foreground = app.otherElements[@"platform_view[0]"]; XCTAssertEqual(foreground.frame.origin.x, 50); XCTAssertEqual(foreground.frame.origin.y, 50); XCTAssertEqual(foreground.frame.size.width, 50); XCTAssertEqual(foreground.frame.size.height, 50); XCTAssertTrue([foreground waitForExistenceWithTimeout:kSecondsToWaitForPlatformView]); XCUIElement* background = app.otherElements[@"platform_view[1]"]; XCTAssertEqual(background.frame.origin.x, 0); XCTAssertEqual(background.frame.origin.y, 0); XCTAssertEqual(background.frame.size.width, 150); XCTAssertEqual(background.frame.size.height, 150); XCTAssertTrue([background waitForExistenceWithTimeout:kSecondsToWaitForPlatformView]); XCUIElement* textView = foreground.textViews.firstMatch; XCTAssertTrue(textView.exists); XCTAssertTrue(foreground.isHittable); [foreground tap]; XCTAssertEqualObjects(textView.label, @"-gestureTouchesBegan-gestureTouchesEnded-platformViewTapped"); } @end
engine/testing/scenario_app/ios/Scenarios/ScenariosUITests/PlatformViewGestureRecognizerTests.m/0
{ "file_path": "engine/testing/scenario_app/ios/Scenarios/ScenariosUITests/PlatformViewGestureRecognizerTests.m", "repo_id": "engine", "token_count": 3202 }
406
// 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'; /// A scenario to run for testing. abstract class Scenario { /// Creates a new scenario using a specific FlutterView instance. Scenario(this.view); /// The FlutterView used by this scenario. May be mocked. final FlutterView view; /// [true] if a screenshot is taken in the next frame. bool _didScheduleScreenshot = false; /// Called by the program when a frame is ready to be drawn. /// /// See [PlatformDispatcher.onBeginFrame] for more details. void onBeginFrame(Duration duration) {} /// Called by the program when the microtasks from [onBeginFrame] have been /// flushed. /// /// See [PlatformDispatcher.onDrawFrame] for more details. void onDrawFrame() { if (_didScheduleScreenshot) { view.platformDispatcher.sendPlatformMessage('take_screenshot', null, null); return; } Future<void>.delayed(const Duration(seconds: 2), () { _didScheduleScreenshot = true; view.platformDispatcher.scheduleFrame(); }); } /// Called when the current scenario has been unmount due to a /// new scenario being mount. void unmount() { _didScheduleScreenshot = false; } /// Called by the program when the window metrics have changed. /// /// See [PlatformDispatcher.onMetricsChanged]. void onMetricsChanged() {} /// Called by the program when a pointer event is received. /// /// See [PlatformDispatcher.onPointerDataPacket]. void onPointerDataPacket(PointerDataPacket packet) {} }
engine/testing/scenario_app/lib/src/scenario.dart/0
{ "file_path": "engine/testing/scenario_app/lib/src/scenario.dart", "repo_id": "engine", "token_count": 495 }
407
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/testing/test_dart_native_resolver.h" #include <mutex> #include <vector> #include "flutter/fml/logging.h" #include "third_party/tonic/logging/dart_error.h" #include "tonic/converter/dart_converter.h" namespace flutter { namespace testing { TestDartNativeResolver::TestDartNativeResolver() = default; TestDartNativeResolver::~TestDartNativeResolver() = default; void TestDartNativeResolver::AddNativeCallback(const std::string& name, Dart_NativeFunction callback) { native_callbacks_[name] = callback; } void TestDartNativeResolver::AddFfiNativeCallback(const std::string& name, void* callback_ptr) { ffi_native_callbacks_[name] = callback_ptr; } Dart_NativeFunction TestDartNativeResolver::ResolveCallback( const std::string& name) const { auto found = native_callbacks_.find(name); if (found == native_callbacks_.end()) { return nullptr; } return found->second; } void* TestDartNativeResolver::ResolveFfiCallback( const std::string& name) const { auto found = ffi_native_callbacks_.find(name); if (found == ffi_native_callbacks_.end()) { return nullptr; } return found->second; } static std::mutex gIsolateResolversMutex; static std::map<Dart_Isolate, std::weak_ptr<TestDartNativeResolver>> gIsolateResolvers; Dart_NativeFunction TestDartNativeResolver::DartNativeEntryResolverCallback( Dart_Handle dart_name, int num_of_arguments, bool* auto_setup_scope) { auto name = tonic::StdStringFromDart(dart_name); std::scoped_lock lock(gIsolateResolversMutex); auto found = gIsolateResolvers.find(Dart_CurrentIsolate()); if (found == gIsolateResolvers.end()) { FML_LOG(ERROR) << "Could not resolve native method for :" << name; return nullptr; } if (auto resolver = found->second.lock()) { return resolver->ResolveCallback(name); } else { gIsolateResolvers.erase(found); } FML_LOG(ERROR) << "Could not resolve native method for :" << name; return nullptr; } static const uint8_t* DartNativeEntrySymbolCallback( Dart_NativeFunction function) { return reinterpret_cast<const uint8_t*>("¯\\_(ツ)_/¯"); } void* TestDartNativeResolver::FfiNativeResolver(const char* name, uintptr_t args_n) { std::scoped_lock lock(gIsolateResolversMutex); auto found = gIsolateResolvers.find(Dart_CurrentIsolate()); if (found == gIsolateResolvers.end()) { FML_LOG(ERROR) << "Could not resolve native method for :" << name; return nullptr; } if (auto resolver = found->second.lock()) { return resolver->ResolveFfiCallback(name); } else { gIsolateResolvers.erase(found); } FML_LOG(ERROR) << "Could not resolve native method for :" << name; return nullptr; } void TestDartNativeResolver::SetNativeResolverForIsolate() { FML_CHECK(!Dart_IsError(Dart_RootLibrary())); auto result = Dart_SetNativeResolver(Dart_RootLibrary(), DartNativeEntryResolverCallback, DartNativeEntrySymbolCallback); FML_CHECK(!tonic::CheckAndHandleError(result)) << "Could not set native resolver in test."; result = Dart_SetFfiNativeResolver(Dart_RootLibrary(), &FfiNativeResolver); FML_CHECK(!tonic::CheckAndHandleError(result)) << "Could not set FFI native resolver in test."; std::scoped_lock lock(gIsolateResolversMutex); gIsolateResolvers[Dart_CurrentIsolate()] = shared_from_this(); std::vector<Dart_Isolate> isolates_with_dead_resolvers; for (const auto& entry : gIsolateResolvers) { if (!entry.second.lock()) { isolates_with_dead_resolvers.push_back(entry.first); } } for (const auto& dead_isolate : isolates_with_dead_resolvers) { gIsolateResolvers.erase(dead_isolate); } } } // namespace testing } // namespace flutter
engine/testing/test_dart_native_resolver.cc/0
{ "file_path": "engine/testing/test_dart_native_resolver.cc", "repo_id": "engine", "token_count": 1583 }
408
// 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_VULKAN_IMAGE_H_ #define FLUTTER_TESTING_TEST_VULKAN_IMAGE_H_ #include "flutter/fml/macros.h" #include "flutter/fml/memory/ref_ptr.h" #include "flutter/vulkan/procs/vulkan_handle.h" #include "third_party/skia/include/core/SkSize.h" namespace flutter { namespace testing { class TestVulkanContext; /// Captures the lifetime of a test VkImage along with its bound memory. class TestVulkanImage { public: TestVulkanImage(TestVulkanImage&& other); TestVulkanImage& operator=(TestVulkanImage&& other); ~TestVulkanImage(); VkImage GetImage(); private: TestVulkanImage(); // The lifetime of the Vulkan state must exceed memory/image handles. fml::RefPtr<TestVulkanContext> context_; vulkan::VulkanHandle<VkImage> image_; vulkan::VulkanHandle<VkDeviceMemory> memory_; FML_DISALLOW_COPY_AND_ASSIGN(TestVulkanImage); friend TestVulkanContext; }; } // namespace testing } // namespace flutter #endif // FLUTTER_TESTING_TEST_VULKAN_IMAGE_H_
engine/testing/test_vulkan_image.h/0
{ "file_path": "engine/testing/test_vulkan_image.h", "repo_id": "engine", "token_count": 408 }
409
Flutter Accessibility Library ============== This accessibility library is a fork of the [chromium](https://www.chromium.org) accessibility code at commit [4579d5538f06c5ef615a15bc67ebb9ac0523a973](https://chromium.googlesource.com/chromium/src/+/4579d5538f06c5ef615a15bc67ebb9ac0523a973). For the main ax code, the following parts were not imported: `fuzz_corpus`, `extensions` and `DEPS` files. `ax/`: https://source.chromium.org/chromium/chromium/src/+/master:ui/accessibility/ `ax_build/`: https://source.chromium.org/chromium/chromium/src/+/master:build/ `base/`: https://source.chromium.org/chromium/chromium/src/+/master:base/ `gfx/`: https://source.chromium.org/chromium/chromium/src/+/master:ui/gfx/ Update to this Library ============== Bug fixes to the forked files in the four directories should proceed as usual. New features or changes that change the behaviors of these classes are discouraged. If you do need to make such change, please log the change at the end of this file.
engine/third_party/accessibility/README.md/0
{ "file_path": "engine/third_party/accessibility/README.md", "repo_id": "engine", "token_count": 326 }
410
// 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_enum_util.h" #include <string> #include <vector> #include "gtest/gtest.h" #include "ax_enums.h" #include "ax_node_data.h" namespace ui { // Templatized function that tests that for a mojom enum // such as ax::mojom::Role, ax::mojom::Event, etc. we can // call ToString() on the enum to get a string, and then // ParseEnumName() on the string to get back the original // value. Also tests what happens when we call ToString // or ParseEnumName on a bogus value. template <typename T> void TestEnumStringConversion( T(ParseFunction)(const char*), int32_t(step)(int32_t) = [](int32_t val) { return val + 1; }) { // Check every valid enum value. for (int i = static_cast<int>(T::kMinValue); i <= static_cast<int>(T::kMaxValue); i = step(i)) { T src = static_cast<T>(i); std::string str = ToString(src); auto dst = ParseFunction(str.c_str()); EXPECT_EQ(src, dst); } // Parse a bogus string. EXPECT_EQ(T::kNone, ParseFunction("bogus")); // Convert a bogus value to a string. int out_of_range_value = static_cast<int>(T::kMaxValue) + 1; EXPECT_STREQ("", ToString(static_cast<T>(out_of_range_value))); } // Templatized function that tries calling a setter on AXNodeData // such as AddIntAttribute, AddFloatAttribute - with each possible // enum value. // // This variant is for cases where the value type is an object. template <typename T, typename U> void TestAXNodeDataSetter(void (AXNodeData::*Setter)(T, const U&), const U& value) { AXNodeData node_data; for (int i = static_cast<int>(T::kMinValue) + 1; i <= static_cast<int>(T::kMaxValue); ++i) { T attr = static_cast<T>(i); ((node_data).*(Setter))(attr, value); } EXPECT_TRUE(!node_data.ToString().empty()); } // Same as TextAXNodeData, above, but This variant is for // cases where the value type is POD. template <typename T, typename U> void TestAXNodeDataSetter(void (AXNodeData::*Setter)(T, U), U value) { AXNodeData node_data; for (int i = static_cast<int>(T::kMinValue) + 1; i <= static_cast<int>(T::kMaxValue); ++i) { T attr = static_cast<T>(i); ((node_data).*(Setter))(attr, value); } EXPECT_TRUE(!node_data.ToString().empty()); } TEST(AXEnumUtilTest, Event) { TestEnumStringConversion<ax::mojom::Event>(ParseEvent); } TEST(AXEnumUtilTest, Role) { TestEnumStringConversion<ax::mojom::Role>(ParseRole); } TEST(AXEnumUtilTest, State) { TestEnumStringConversion<ax::mojom::State>(ParseState); } TEST(AXEnumUtilTest, Action) { TestEnumStringConversion<ax::mojom::Action>(ParseAction); } TEST(AXEnumUtilTest, ActionFlags) { TestEnumStringConversion<ax::mojom::ActionFlags>(ParseActionFlags); } TEST(AXEnumUtilTest, DefaultActionVerb) { TestEnumStringConversion<ax::mojom::DefaultActionVerb>( ParseDefaultActionVerb); } TEST(AXEnumUtilTest, Mutation) { TestEnumStringConversion<ax::mojom::Mutation>(ParseMutation); } TEST(AXEnumUtilTest, StringAttribute) { TestEnumStringConversion<ax::mojom::StringAttribute>(ParseStringAttribute); TestAXNodeDataSetter<ax::mojom::StringAttribute>( &AXNodeData::AddStringAttribute, std::string()); } TEST(AXEnumUtilTest, IntAttribute) { TestEnumStringConversion<ax::mojom::IntAttribute>(ParseIntAttribute); TestAXNodeDataSetter<ax::mojom::IntAttribute>(&AXNodeData::AddIntAttribute, 0); } TEST(AXEnumUtilTest, FloatAttribute) { TestEnumStringConversion<ax::mojom::FloatAttribute>(ParseFloatAttribute); TestAXNodeDataSetter<ax::mojom::FloatAttribute>( &AXNodeData::AddFloatAttribute, 0.0f); } TEST(AXEnumUtilTest, BoolAttribute) { TestEnumStringConversion<ax::mojom::BoolAttribute>(ParseBoolAttribute); TestAXNodeDataSetter<ax::mojom::BoolAttribute>(&AXNodeData::AddBoolAttribute, false); } TEST(AXEnumUtilTest, IntListAttribute) { TestEnumStringConversion<ax::mojom::IntListAttribute>(ParseIntListAttribute); TestAXNodeDataSetter<ax::mojom::IntListAttribute>( &AXNodeData::AddIntListAttribute, std::vector<int32_t>()); } TEST(AXEnumUtilTest, StringListAttribute) { TestEnumStringConversion<ax::mojom::StringListAttribute>( ParseStringListAttribute); TestAXNodeDataSetter<ax::mojom::StringListAttribute>( &AXNodeData::AddStringListAttribute, std::vector<std::string>()); } TEST(AXEnumUtilTest, MarkerType) { TestEnumStringConversion<ax::mojom::MarkerType>( ParseMarkerType, [](int32_t val) { return val == 0 ? 1 : // 8 (Composition) is // explicitly skipped in // ax_enums.mojom. val == 4 ? 16 : val * 2; }); } TEST(AXEnumUtilTest, Text_Decoration_Style) { TestEnumStringConversion<ax::mojom::TextDecorationStyle>( ParseTextDecorationStyle); } TEST(AXEnumUtilTest, ListStyle) { TestEnumStringConversion<ax::mojom::ListStyle>(ParseListStyle); } TEST(AXEnumUtilTest, MoveDirection) { TestEnumStringConversion<ax::mojom::MoveDirection>(ParseMoveDirection); } TEST(AXEnumUtilTest, Command) { TestEnumStringConversion<ax::mojom::Command>(ParseCommand); } TEST(AXEnumUtilTest, TextAlign) { TestEnumStringConversion<ax::mojom::TextAlign>(ParseTextAlign); } TEST(AXEnumUtilTest, TextBoundary) { TestEnumStringConversion<ax::mojom::TextBoundary>(ParseTextBoundary); } TEST(AXEnumUtilTest, TextDirection) { TestEnumStringConversion<ax::mojom::WritingDirection>(ParseTextDirection); } TEST(AXEnumUtilTest, TextPosition) { TestEnumStringConversion<ax::mojom::TextPosition>(ParseTextPosition); } TEST(AXEnumUtilTest, TextStyle) { TestEnumStringConversion<ax::mojom::TextStyle>(ParseTextStyle); } TEST(AXEnumUtilTest, AriaCurrentState) { TestEnumStringConversion<ax::mojom::AriaCurrentState>(ParseAriaCurrentState); } TEST(AXEnumUtilTest, HasPopup) { TestEnumStringConversion<ax::mojom::HasPopup>(ParseHasPopup); } TEST(AXEnumUtilTest, InvalidState) { TestEnumStringConversion<ax::mojom::InvalidState>(ParseInvalidState); } TEST(AXEnumUtilTest, Restriction) { TestEnumStringConversion<ax::mojom::Restriction>(ParseRestriction); } TEST(AXEnumUtilTest, CheckedState) { TestEnumStringConversion<ax::mojom::CheckedState>(ParseCheckedState); } TEST(AXEnumUtilTest, SortDirection) { TestEnumStringConversion<ax::mojom::SortDirection>(ParseSortDirection); } TEST(AXEnumUtilTest, NameFrom) { TestEnumStringConversion<ax::mojom::NameFrom>(ParseNameFrom); } TEST(AXEnumUtilTest, DescriptionFrom) { TestEnumStringConversion<ax::mojom::DescriptionFrom>(ParseDescriptionFrom); } TEST(AXEnumUtilTest, EventFrom) { TestEnumStringConversion<ax::mojom::EventFrom>(ParseEventFrom); } TEST(AXEnumUtilTest, Gesture) { TestEnumStringConversion<ax::mojom::Gesture>(ParseGesture); } TEST(AXEnumUtilTest, TextAffinity) { TestEnumStringConversion<ax::mojom::TextAffinity>(ParseTextAffinity); } TEST(AXEnumUtilTest, TreeOrder) { TestEnumStringConversion<ax::mojom::TreeOrder>(ParseTreeOrder); } TEST(AXEnumUtilTest, ImageAnnotationStatus) { TestEnumStringConversion<ax::mojom::ImageAnnotationStatus>( ParseImageAnnotationStatus); } TEST(AXEnumUtilTest, Dropeffect) { TestEnumStringConversion<ax::mojom::Dropeffect>(ParseDropeffect); } } // namespace ui
engine/third_party/accessibility/ax/ax_enum_util_unittest.cc/0
{ "file_path": "engine/third_party/accessibility/ax/ax_enum_util_unittest.cc", "repo_id": "engine", "token_count": 3017 }
411