diff --git a/RNTester/android/app/src/main/java/com/facebook/react/uiapp/RNTesterActivity.java b/RNTester/android/app/src/main/java/com/facebook/react/uiapp/RNTesterActivity.java index 8a90535223f..a5e1f0a3523 100644 --- a/RNTester/android/app/src/main/java/com/facebook/react/uiapp/RNTesterActivity.java +++ b/RNTester/android/app/src/main/java/com/facebook/react/uiapp/RNTesterActivity.java @@ -1,18 +1,14 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uiapp; import android.os.Bundle; - import com.facebook.react.ReactActivity; import com.facebook.react.ReactActivityDelegate; - import javax.annotation.Nullable; public class RNTesterActivity extends ReactActivity { @@ -31,10 +27,11 @@ public class RNTesterActivity extends ReactActivity { // Get remote param before calling super which uses it Bundle bundle = mActivity.getIntent().getExtras(); if (bundle != null && bundle.containsKey(PARAM_ROUTE)) { - String routeUri = new StringBuilder("rntester://example/") - .append(bundle.getString(PARAM_ROUTE)) - .append("Example") - .toString(); + String routeUri = + new StringBuilder("rntester://example/") + .append(bundle.getString(PARAM_ROUTE)) + .append("Example") + .toString(); mInitialProps = new Bundle(); mInitialProps.putString("exampleFromAppetizeParams", routeUri); } diff --git a/RNTester/android/app/src/main/java/com/facebook/react/uiapp/RNTesterApplication.java b/RNTester/android/app/src/main/java/com/facebook/react/uiapp/RNTesterApplication.java index a6601115ad9..bbfbd557417 100644 --- a/RNTester/android/app/src/main/java/com/facebook/react/uiapp/RNTesterApplication.java +++ b/RNTester/android/app/src/main/java/com/facebook/react/uiapp/RNTesterApplication.java @@ -1,49 +1,44 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uiapp; import android.app.Application; - import com.facebook.react.BuildConfig; import com.facebook.react.ReactApplication; import com.facebook.react.ReactNativeHost; import com.facebook.react.ReactPackage; import com.facebook.react.shell.MainReactPackage; import com.facebook.react.views.text.ReactFontManager; - import java.util.Arrays; import java.util.List; public class RNTesterApplication extends Application implements ReactApplication { - private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) { - @Override - public String getJSMainModuleName() { - return "RNTester/js/RNTesterApp.android"; - } + private final ReactNativeHost mReactNativeHost = + new ReactNativeHost(this) { + @Override + public String getJSMainModuleName() { + return "RNTester/js/RNTesterApp.android"; + } - @Override - public String getBundleAssetName() { - return "RNTesterApp.android.bundle"; - } + @Override + public String getBundleAssetName() { + return "RNTesterApp.android.bundle"; + } - @Override - public boolean getUseDeveloperSupport() { - return BuildConfig.DEBUG; - } + @Override + public boolean getUseDeveloperSupport() { + return BuildConfig.DEBUG; + } - @Override - public List getPackages() { - return Arrays.asList( - new MainReactPackage() - ); - } - }; + @Override + public List getPackages() { + return Arrays.asList(new MainReactPackage()); + } + }; @Override public void onCreate() { diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/testing/AbstractScrollViewTestCase.java b/ReactAndroid/src/androidTest/java/com/facebook/react/testing/AbstractScrollViewTestCase.java index efd2ab6f1f6..9dc252668bb 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/testing/AbstractScrollViewTestCase.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/testing/AbstractScrollViewTestCase.java @@ -1,25 +1,21 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.testing; +import com.facebook.react.bridge.BaseJavaModule; +import com.facebook.react.bridge.JavaScriptModule; +import com.facebook.react.bridge.ReactMethod; import java.util.ArrayList; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; -import com.facebook.react.bridge.BaseJavaModule; -import com.facebook.react.bridge.ReactMethod; -import com.facebook.react.bridge.JavaScriptModule; -import com.facebook.react.testing.ReactInstanceSpecForTest; -import com.facebook.react.testing.ReactAppInstrumentationTestCase; - /** - * Shared by {@link ReactScrollViewTestCase} and {@link ReactHorizontalScrollViewTestCase}. - * See also ScrollViewTestModule.js + * Shared by {@link ReactScrollViewTestCase} and {@link ReactHorizontalScrollViewTestCase}. See also + * ScrollViewTestModule.js */ public abstract class AbstractScrollViewTestCase extends ReactAppInstrumentationTestCase { @@ -38,8 +34,7 @@ public abstract class AbstractScrollViewTestCase extends ReactAppInstrumentation @Override protected ReactInstanceSpecForTest createReactInstanceSpecForTest() { mScrollListenerModule = new ScrollListenerModule(); - return super.createReactInstanceSpecForTest() - .addNativeModule(mScrollListenerModule); + return super.createReactInstanceSpecForTest().addNativeModule(mScrollListenerModule); } // See ScrollViewListenerModule.js diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/testing/AssertModule.java b/ReactAndroid/src/androidTest/java/com/facebook/react/testing/AssertModule.java index 16ac3f8182c..d5a4f5376fd 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/testing/AssertModule.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/testing/AssertModule.java @@ -1,23 +1,19 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.testing; -import javax.annotation.Nullable; - -import com.facebook.react.bridge.BaseJavaModule; -import com.facebook.react.bridge.ReactMethod; - import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertTrue; -/** - * NativeModule for tests that allows assertions from JS to propagate to Java. - */ +import com.facebook.react.bridge.BaseJavaModule; +import com.facebook.react.bridge.ReactMethod; +import javax.annotation.Nullable; + +/** NativeModule for tests that allows assertions from JS to propagate to Java. */ public class AssertModule extends BaseJavaModule { private boolean mGotSuccess; diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/testing/FakeAsyncLocalStorage.java b/ReactAndroid/src/androidTest/java/com/facebook/react/testing/FakeAsyncLocalStorage.java index 34e1c2f19ff..762d37f316a 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/testing/FakeAsyncLocalStorage.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/testing/FakeAsyncLocalStorage.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.testing; import com.facebook.react.bridge.Arguments; @@ -14,12 +13,11 @@ import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.WritableMap; -/** - * Dummy implementation of storage module, used for testing - */ +/** Dummy implementation of storage module, used for testing */ public final class FakeAsyncLocalStorage extends BaseJavaModule { private static WritableMap errorMessage; + static { errorMessage = Arguments.createMap(); errorMessage.putString("message", "Fake Async Local Storage"); diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/testing/FakeWebSocketModule.java b/ReactAndroid/src/androidTest/java/com/facebook/react/testing/FakeWebSocketModule.java index 52d0467e4a0..0800f24b45e 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/testing/FakeWebSocketModule.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/testing/FakeWebSocketModule.java @@ -1,22 +1,18 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.testing; -import javax.annotation.Nullable; - import com.facebook.react.bridge.BaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableMap; +import javax.annotation.Nullable; -/** - * Dummy implementation of storage module, used for testing - */ +/** Dummy implementation of storage module, used for testing */ public final class FakeWebSocketModule extends BaseJavaModule { @Override @@ -31,21 +27,17 @@ public final class FakeWebSocketModule extends BaseJavaModule { @ReactMethod public void connect( - final String url, - @Nullable final ReadableArray protocols, - @Nullable final ReadableMap headers, - final int id) { - } + final String url, + @Nullable final ReadableArray protocols, + @Nullable final ReadableMap headers, + final int id) {} @ReactMethod - public void close(int code, String reason, int id) { - } + public void close(int code, String reason, int id) {} @ReactMethod - public void send(String message, int id) { - } + public void send(String message, int id) {} @ReactMethod - public void sendBinary(String base64String, int id) { - } + public void sendBinary(String base64String, int id) {} } diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/testing/InstanceSpecForTestPackage.java b/ReactAndroid/src/androidTest/java/com/facebook/react/testing/InstanceSpecForTestPackage.java index 4e939977167..8edc2a6be5c 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/testing/InstanceSpecForTestPackage.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/testing/InstanceSpecForTestPackage.java @@ -1,21 +1,16 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.testing; -import java.util.List; - -import android.view.View; - +import com.facebook.react.ReactPackage; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; -import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.uimanager.ViewManager; -import com.facebook.react.ReactPackage; +import java.util.List; /** * This class wraps {@class ReactInstanceSpecForTest} in {@class ReactPackage} interface. diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/testing/IntRecordingModule.java b/ReactAndroid/src/androidTest/java/com/facebook/react/testing/IntRecordingModule.java index 1650611acb9..f29f9d54c62 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/testing/IntRecordingModule.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/testing/IntRecordingModule.java @@ -1,23 +1,21 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.testing; +import com.facebook.react.bridge.BaseJavaModule; +import com.facebook.react.bridge.ReactMethod; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -import com.facebook.react.bridge.BaseJavaModule; -import com.facebook.react.bridge.ReactMethod; - /** - * Native module provides single method {@link #record} which records its single int argument - * in calls array + * Native module provides single method {@link #record} which records its single int argument in + * calls array */ public class IntRecordingModule extends BaseJavaModule { diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/testing/JSIntegrationTestChecker.java b/ReactAndroid/src/androidTest/java/com/facebook/react/testing/JSIntegrationTestChecker.java index 478cd0d2ea2..32a855a64a9 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/testing/JSIntegrationTestChecker.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/testing/JSIntegrationTestChecker.java @@ -1,26 +1,23 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.testing; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - import com.facebook.react.bridge.BaseJavaModule; import com.facebook.react.bridge.Callback; import com.facebook.react.bridge.ReactMethod; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; /** - * This class is used to verify that some JS integration tests have completed successfully. - * The JS integration tests can be started from a ReactIntegrationTestCase and upon - * finishing successfully the {@link JSIntegrationTestChecker#testDone()} method will be called. - * To verify if the test has completed successfully, call {#link JSIntegrationTestChecker#await()} - * to wait for the test to run, and {#link JSIntegrationTestChecker#isTestDone()} to check if it - * completed successfully. + * This class is used to verify that some JS integration tests have completed successfully. The JS + * integration tests can be started from a ReactIntegrationTestCase and upon finishing successfully + * the {@link JSIntegrationTestChecker#testDone()} method will be called. To verify if the test has + * completed successfully, call {#link JSIntegrationTestChecker#await()} to wait for the test to + * run, and {#link JSIntegrationTestChecker#isTestDone()} to check if it completed successfully. */ public class JSIntegrationTestChecker extends BaseJavaModule { @@ -41,8 +38,7 @@ public class JSIntegrationTestChecker extends BaseJavaModule { } @ReactMethod - public void verifySnapshot(Callback callback) { - } + public void verifySnapshot(Callback callback) {} public boolean await(long ms) { try { diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/testing/MultipleFailureException.java b/ReactAndroid/src/androidTest/java/com/facebook/react/testing/MultipleFailureException.java index 533fa1aa49a..93ca3008879 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/testing/MultipleFailureException.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/testing/MultipleFailureException.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.testing; import java.io.PrintWriter; diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/testing/ReactAppInstrumentationTestCase.java b/ReactAndroid/src/androidTest/java/com/facebook/react/testing/ReactAppInstrumentationTestCase.java index 18f35707ac5..2c3c5866514 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/testing/ReactAppInstrumentationTestCase.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/testing/ReactAppInstrumentationTestCase.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.testing; import android.content.Intent; @@ -19,11 +18,9 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import javax.annotation.Nullable; -/** - * Base class for instrumentation tests that runs React based react application in UI mode - */ -public abstract class ReactAppInstrumentationTestCase extends - ActivityInstrumentationTestCase2 implements IdleWaiter { +/** Base class for instrumentation tests that runs React based react application in UI mode */ +public abstract class ReactAppInstrumentationTestCase + extends ActivityInstrumentationTestCase2 implements IdleWaiter { public ReactAppInstrumentationTestCase() { super(ReactAppTestActivity.class); @@ -38,9 +35,7 @@ public abstract class ReactAppInstrumentationTestCase extends setActivityIntent(intent); final ReactAppTestActivity activity = getActivity(); activity.loadApp( - getReactApplicationKeyUnderTest(), - createReactInstanceSpecForTest(), - getEnableDevSupport()); + getReactApplicationKeyUnderTest(), createReactInstanceSpecForTest(), getEnableDevSupport()); waitForBridgeAndUIIdle(); } @@ -56,8 +51,8 @@ public abstract class ReactAppInstrumentationTestCase extends } /** - * This method isn't safe since it doesn't factor in layout-only view removal. Use - * {@link #getViewByTestId(String)} instead. + * This method isn't safe since it doesn't factor in layout-only view removal. Use {@link + * #getViewByTestId(String)} instead. */ @Deprecated public T getViewAtPath(int... path) { @@ -65,8 +60,8 @@ public abstract class ReactAppInstrumentationTestCase extends } public T getViewByTestId(String testID) { - return (T) ReactTestHelper - .getViewWithReactTestId((ViewGroup) getRootView().getParent(), testID); + return (T) + ReactTestHelper.getViewWithReactTestId((ViewGroup) getRootView().getParent(), testID); } public SingleTouchGestureGenerator createGestureGenerator() { @@ -87,31 +82,32 @@ public abstract class ReactAppInstrumentationTestCase extends final CountDownLatch latch = new CountDownLatch(1); final BitmapHolder bitmapHolder = new BitmapHolder(); - final Runnable getScreenshotRunnable = new Runnable() { + final Runnable getScreenshotRunnable = + new Runnable() { - private static final int MAX_TRIES = 1000; - // This is the constant used in the support library for APIs that don't have Choreographer - private static final int FRAME_DELAY_MS = 10; + private static final int MAX_TRIES = 1000; + // This is the constant used in the support library for APIs that don't have Choreographer + private static final int FRAME_DELAY_MS = 10; - private int mNumRuns = 0; + private int mNumRuns = 0; - @Override - public void run() { - mNumRuns++; - ReactAppTestActivity activity = getActivity(); - if (!activity.isScreenshotReady()) { - if (mNumRuns > MAX_TRIES) { - throw new RuntimeException( - "Waited " + MAX_TRIES + " frames to get screenshot but it's still not ready!"); + @Override + public void run() { + mNumRuns++; + ReactAppTestActivity activity = getActivity(); + if (!activity.isScreenshotReady()) { + if (mNumRuns > MAX_TRIES) { + throw new RuntimeException( + "Waited " + MAX_TRIES + " frames to get screenshot but it's still not ready!"); + } + activity.postDelayed(this, FRAME_DELAY_MS); + return; + } + + bitmapHolder.bitmap = getActivity().getCurrentScreenshot(); + latch.countDown(); } - activity.postDelayed(this, FRAME_DELAY_MS); - return; - } - - bitmapHolder.bitmap = getActivity().getCurrentScreenshot(); - latch.countDown(); - } - }; + }; getActivity().runOnUiThread(getScreenshotRunnable); try { @@ -125,8 +121,8 @@ public abstract class ReactAppInstrumentationTestCase extends } /** - * Implement this method to provide application key to be launched. List of available - * application is located in TestBundle.js file + * Implement this method to provide application key to be launched. List of available application + * is located in TestBundle.js file */ protected abstract String getReactApplicationKeyUnderTest(); @@ -138,9 +134,7 @@ public abstract class ReactAppInstrumentationTestCase extends return false; } - /** - * Override this method to provide extra native modules to be loaded before the app starts - */ + /** Override this method to provide extra native modules to be loaded before the app starts */ protected ReactInstanceSpecForTest createReactInstanceSpecForTest() { return new ReactInstanceSpecForTest(); } @@ -149,9 +143,7 @@ public abstract class ReactAppInstrumentationTestCase extends return getActivity().getReactContext(); } - /** - * Helper class to pass the bitmap between execution scopes in {@link #getScreenshot()}. - */ + /** Helper class to pass the bitmap between execution scopes in {@link #getScreenshot()}. */ private static class BitmapHolder { public @Nullable volatile Bitmap bitmap; diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/testing/ReactAppTestActivity.java b/ReactAndroid/src/androidTest/java/com/facebook/react/testing/ReactAppTestActivity.java index 1982602dc54..2318f236a7e 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/testing/ReactAppTestActivity.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/testing/ReactAppTestActivity.java @@ -11,15 +11,14 @@ import static com.facebook.react.bridge.UiThreadUtil.runOnUiThread; import android.content.Intent; import android.graphics.Bitmap; import android.os.Bundle; -import androidx.fragment.app.FragmentActivity; import android.view.View; import android.view.ViewTreeObserver; import android.widget.FrameLayout; +import androidx.fragment.app.FragmentActivity; import com.facebook.infer.annotation.Assertions; import com.facebook.react.ReactInstanceManager; import com.facebook.react.ReactInstanceManagerBuilder; import com.facebook.react.ReactRootView; -import com.facebook.react.bridge.JSIModule; import com.facebook.react.bridge.JSIModulePackage; import com.facebook.react.bridge.JSIModuleProvider; import com.facebook.react.bridge.JSIModuleSpec; @@ -35,17 +34,13 @@ import com.facebook.react.modules.core.PermissionListener; import com.facebook.react.shell.MainReactPackage; import com.facebook.react.testing.idledetection.ReactBridgeIdleSignaler; import com.facebook.react.testing.idledetection.ReactIdleDetectionUtil; -import com.facebook.react.uimanager.UIManagerModule; -import com.facebook.react.uimanager.ViewManager; import com.facebook.react.uimanager.ViewManagerRegistry; -import com.facebook.react.uimanager.events.EventDispatcher; import java.util.Arrays; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import javax.annotation.Nullable; - public class ReactAppTestActivity extends FragmentActivity implements DefaultHardwareBackBtnHandler, PermissionAwareActivity { @@ -190,14 +185,16 @@ public class ReactAppTestActivity extends FragmentActivity .startReactApplication(mReactInstanceManager, appKey, initialProps); } }); - try { - waitForBridgeAndUIIdle(); - waitForLayout(5000); - } catch (InterruptedException e) { - throw new RuntimeException("Layout never occurred for component " + appKey, e);} + try { + waitForBridgeAndUIIdle(); + waitForLayout(5000); + } catch (InterruptedException e) { + throw new RuntimeException("Layout never occurred for component " + appKey, e); + } } - public void loadBundle(final ReactInstanceSpecForTest spec, String bundleName, boolean useDevSupport) { + public void loadBundle( + final ReactInstanceSpecForTest spec, String bundleName, boolean useDevSupport) { mBridgeIdleSignaler = new ReactBridgeIdleSignaler(); @@ -215,11 +212,11 @@ public class ReactAppTestActivity extends FragmentActivity builder.addPackage(new MainReactPackage()); } /** - * The {@link ReactContext#mCurrentActivity} never to be set if initial lifecycle state is resumed. - * So we should call {@link ReactInstanceManagerBuilder#setCurrentActivity}. + * The {@link ReactContext#mCurrentActivity} never to be set if initial lifecycle state is + * resumed. So we should call {@link ReactInstanceManagerBuilder#setCurrentActivity}. * - * Finally,{@link ReactInstanceManagerBuilder#build()} will create instance of {@link ReactInstanceManager}. - * And also will set {@link ReactContext#mCurrentActivity}. + *

Finally,{@link ReactInstanceManagerBuilder#build()} will create instance of {@link + * ReactInstanceManager}. And also will set {@link ReactContext#mCurrentActivity}. */ builder.setCurrentActivity(this); builder @@ -250,11 +247,15 @@ public class ReactAppTestActivity extends FragmentActivity @Override public UIManager get() { ViewManagerRegistry viewManagerRegistry = - new ViewManagerRegistry( - mReactInstanceManager.getOrCreateViewManagers(reactApplicationContext)); + new ViewManagerRegistry( + mReactInstanceManager.getOrCreateViewManagers( + reactApplicationContext)); FabricUIManagerFactory factory = spec.getFabricUIManagerFactory(); - return factory != null ? factory.getFabricUIManager(reactApplicationContext, viewManagerRegistry, jsContext) : null; + return factory != null + ? factory.getFabricUIManager( + reactApplicationContext, viewManagerRegistry, jsContext) + : null; } }; } diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/testing/ReactInstanceSpecForTest.java b/ReactAndroid/src/androidTest/java/com/facebook/react/testing/ReactInstanceSpecForTest.java index f26917dc3de..6b92b88e73c 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/testing/ReactInstanceSpecForTest.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/testing/ReactInstanceSpecForTest.java @@ -53,7 +53,8 @@ public class ReactInstanceSpecForTest { return this; } - public ReactInstanceSpecForTest setFabricUIManagerFactory(@Nullable FabricUIManagerFactory fabricUIManagerFactory) { + public ReactInstanceSpecForTest setFabricUIManagerFactory( + @Nullable FabricUIManagerFactory fabricUIManagerFactory) { mFabricUIManagerFactory = fabricUIManagerFactory; return this; } diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/testing/ReactIntegrationTestCase.java b/ReactAndroid/src/androidTest/java/com/facebook/react/testing/ReactIntegrationTestCase.java index af5f72a0098..73d57e00181 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/testing/ReactIntegrationTestCase.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/testing/ReactIntegrationTestCase.java @@ -1,24 +1,16 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.testing; -import com.facebook.react.modules.core.ReactChoreographer; -import javax.annotation.Nullable; +import static org.mockito.Mockito.mock; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.Semaphore; -import java.util.concurrent.TimeUnit; - -import android.app.Application; import android.test.AndroidTestCase; import android.view.View; import android.view.ViewGroup; - import com.facebook.infer.annotation.Assertions; import com.facebook.react.bridge.BaseJavaModule; import com.facebook.react.bridge.CatalystInstance; @@ -29,26 +21,27 @@ import com.facebook.react.bridge.SoftAssertions; import com.facebook.react.bridge.UiThreadUtil; import com.facebook.react.common.futures.SimpleSettableFuture; import com.facebook.react.devsupport.interfaces.DevSupportManager; +import com.facebook.react.modules.core.ReactChoreographer; import com.facebook.react.modules.core.Timing; import com.facebook.react.testing.idledetection.ReactBridgeIdleSignaler; import com.facebook.react.testing.idledetection.ReactIdleDetectionUtil; import com.facebook.soloader.SoLoader; - -import static org.mockito.Mockito.mock; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; +import javax.annotation.Nullable; /** - * Use this class for writing integration tests of catalyst. This class will run all JNI call - * within separate android looper, thus you don't need to care about starting your own looper. + * Use this class for writing integration tests of catalyst. This class will run all JNI call within + * separate android looper, thus you don't need to care about starting your own looper. * - * Keep in mind that all JS remote method calls and script load calls are asynchronous and you + *

Keep in mind that all JS remote method calls and script load calls are asynchronous and you * should not expect them to return results immediately. * - * In order to write catalyst integration: - * 1) Make {@link ReactIntegrationTestCase} a base class of your test case - * 2) Use {@link ReactTestHelper#catalystInstanceBuilder()} - * instead of {@link com.facebook.react.bridge.CatalystInstanceImpl.Builder} to build catalyst - * instance for testing purposes - * + *

In order to write catalyst integration: 1) Make {@link ReactIntegrationTestCase} a base class + * of your test case 2) Use {@link ReactTestHelper#catalystInstanceBuilder()} instead of {@link + * com.facebook.react.bridge.CatalystInstanceImpl.Builder} to build catalyst instance for testing + * purposes */ public abstract class ReactIntegrationTestCase extends AndroidTestCase { @@ -76,22 +69,23 @@ public abstract class ReactIntegrationTestCase extends AndroidTestCase { mInstance = null; final SimpleSettableFuture semaphore = new SimpleSettableFuture<>(); - UiThreadUtil.runOnUiThread(new Runnable() { - @Override - public void run() { - if (contextToDestroy != null) { - contextToDestroy.destroy(); - } - semaphore.set(null); - } - }); + UiThreadUtil.runOnUiThread( + new Runnable() { + @Override + public void run() { + if (contextToDestroy != null) { + contextToDestroy.destroy(); + } + semaphore.set(null); + } + }); semaphore.getOrThrow(); } } /** - * This method isn't safe since it doesn't factor in layout-only view removal. Use - * {@link #getViewByTestId} instead. + * This method isn't safe since it doesn't factor in layout-only view removal. Use {@link + * #getViewByTestId} instead. */ @Deprecated public T getViewAtPath(ViewGroup rootView, int... path) { @@ -165,14 +159,12 @@ public abstract class ReactIntegrationTestCase extends AndroidTestCase { public void waitForIdleSync() { return; // TODO: re-enable after cleanup of android-x migration - //InstrumentationRegistry.getInstrumentation().waitForIdleSync(); + // InstrumentationRegistry.getInstrumentation().waitForIdleSync(); } public void waitForBridgeAndUIIdle() { ReactIdleDetectionUtil.waitForBridgeAndUIIdle( - Assertions.assertNotNull(mBridgeIdleSignaler), - getContext(), - IDLE_TIMEOUT_MS); + Assertions.assertNotNull(mBridgeIdleSignaler), getContext(), IDLE_TIMEOUT_MS); } @Override diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/testing/ReactSettingsForTests.java b/ReactAndroid/src/androidTest/java/com/facebook/react/testing/ReactSettingsForTests.java index 20945f5316f..511c7f97620 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/testing/ReactSettingsForTests.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/testing/ReactSettingsForTests.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.testing; import com.facebook.react.modules.debug.interfaces.DeveloperSettings; @@ -47,7 +46,5 @@ public class ReactSettingsForTests implements DeveloperSettings { } @Override - public void setRemoteJSDebugEnabled(boolean remoteJSDebugEnabled) { - - } + public void setRemoteJSDebugEnabled(boolean remoteJSDebugEnabled) {} } diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/testing/ReactTestAppShell.java b/ReactAndroid/src/androidTest/java/com/facebook/react/testing/ReactTestAppShell.java index 8ec1cf9ab0e..095442752f2 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/testing/ReactTestAppShell.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/testing/ReactTestAppShell.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.testing; import com.facebook.buck.android.support.exopackage.ApplicationLike; @@ -15,9 +14,9 @@ import com.facebook.soloader.SoLoader; /** * Application class for the Catalyst Launcher to allow it to work as an exopackage. * - * Any app-specific code that should run before secondary dex files are loaded - * (like setting up crash reporting) should go in onBaseContextAttached. - * Anything that should run after secondary dex should go in CatalystApplicationImpl.onCreate. + *

Any app-specific code that should run before secondary dex files are loaded (like setting up + * crash reporting) should go in onBaseContextAttached. Anything that should run after secondary dex + * should go in CatalystApplicationImpl.onCreate. */ public class ReactTestAppShell extends ExopackageApplication { diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/testing/ReactTestApplicationImpl.java b/ReactAndroid/src/androidTest/java/com/facebook/react/testing/ReactTestApplicationImpl.java index 49db8b66d1e..926eb274ec1 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/testing/ReactTestApplicationImpl.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/testing/ReactTestApplicationImpl.java @@ -1,14 +1,12 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.testing; import android.app.Application; - import com.facebook.buck.android.support.exopackage.DefaultApplicationLike; public class ReactTestApplicationImpl extends DefaultApplicationLike { diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/testing/ReactTestFactory.java b/ReactAndroid/src/androidTest/java/com/facebook/react/testing/ReactTestFactory.java index f22dbb7b206..4abf69c9685 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/testing/ReactTestFactory.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/testing/ReactTestFactory.java @@ -1,14 +1,12 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.testing; import android.content.Context; - import com.facebook.react.ReactInstanceManagerBuilder; import com.facebook.react.bridge.CatalystInstance; import com.facebook.react.bridge.NativeModule; @@ -16,10 +14,13 @@ import com.facebook.react.bridge.NativeModule; public interface ReactTestFactory { interface ReactInstanceEasyBuilder { ReactInstanceEasyBuilder setContext(Context context); + ReactInstanceEasyBuilder addNativeModule(NativeModule module); + CatalystInstance build(); } ReactInstanceEasyBuilder getCatalystInstanceBuilder(); + ReactInstanceManagerBuilder getReactInstanceManagerBuilder(); } diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/testing/ReactTestHelper.java b/ReactAndroid/src/androidTest/java/com/facebook/react/testing/ReactTestHelper.java index 360d10b7bc7..a737f543c04 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/testing/ReactTestHelper.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/testing/ReactTestHelper.java @@ -1,23 +1,15 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.testing; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import javax.annotation.Nullable; - -import android.app.Instrumentation; import android.content.Context; import android.view.View; import android.view.ViewGroup; - +import com.android.internal.util.Predicate; import com.facebook.infer.annotation.Assertions; import com.facebook.react.NativeModuleRegistryBuilder; import com.facebook.react.R; @@ -25,19 +17,20 @@ import com.facebook.react.ReactInstanceManager; import com.facebook.react.ReactInstanceManagerBuilder; import com.facebook.react.ReactPackage; import com.facebook.react.bridge.CatalystInstance; -import com.facebook.react.bridge.JavaScriptModuleRegistry; -import com.facebook.react.bridge.NativeModule; -import com.facebook.react.bridge.NativeModuleCallExceptionHandler; -import com.facebook.react.bridge.ReactApplicationContext; -import com.facebook.react.bridge.WritableNativeMap; -import com.facebook.react.bridge.queue.ReactQueueConfigurationSpec; import com.facebook.react.bridge.CatalystInstanceImpl; import com.facebook.react.bridge.JSBundleLoader; import com.facebook.react.bridge.JavaScriptExecutor; +import com.facebook.react.bridge.NativeModule; +import com.facebook.react.bridge.NativeModuleCallExceptionHandler; +import com.facebook.react.bridge.ReactApplicationContext; +import com.facebook.react.bridge.queue.ReactQueueConfigurationSpec; import com.facebook.react.jscexecutor.JSCExecutorFactory; import com.facebook.react.modules.core.ReactChoreographer; import com.facebook.react.uimanager.ViewManager; -import com.android.internal.util.Predicate; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import javax.annotation.Nullable; public class ReactTestHelper { private static class DefaultReactTestFactory implements ReactTestFactory { @@ -56,31 +49,30 @@ public class ReactTestHelper { @Override public ReactInstanceEasyBuilder addNativeModule(final NativeModule nativeModule) { if (mNativeModuleRegistryBuilder == null) { - mNativeModuleRegistryBuilder = new NativeModuleRegistryBuilder( - (ReactApplicationContext) mContext, - null); + mNativeModuleRegistryBuilder = + new NativeModuleRegistryBuilder((ReactApplicationContext) mContext, null); } Assertions.assertNotNull(nativeModule); - mNativeModuleRegistryBuilder.processPackage(new ReactPackage(){ - @Override - public List createViewManagers(ReactApplicationContext reactContext) { - return Collections.emptyList(); - } + mNativeModuleRegistryBuilder.processPackage( + new ReactPackage() { + @Override + public List createViewManagers(ReactApplicationContext reactContext) { + return Collections.emptyList(); + } - @Override - public List createNativeModules(ReactApplicationContext reactContext) { - return Arrays.asList(nativeModule); - } - }); + @Override + public List createNativeModules(ReactApplicationContext reactContext) { + return Arrays.asList(nativeModule); + } + }); return this; } @Override public CatalystInstance build() { if (mNativeModuleRegistryBuilder == null) { - mNativeModuleRegistryBuilder = new NativeModuleRegistryBuilder( - (ReactApplicationContext) mContext, - null); + mNativeModuleRegistryBuilder = + new NativeModuleRegistryBuilder((ReactApplicationContext) mContext, null); } JavaScriptExecutor executor = null; try { @@ -89,21 +81,20 @@ public class ReactTestHelper { throw new RuntimeException(e); } return new CatalystInstanceImpl.Builder() - .setReactQueueConfigurationSpec(ReactQueueConfigurationSpec.createDefault()) - .setJSExecutor(executor) - .setRegistry(mNativeModuleRegistryBuilder.build()) - .setJSBundleLoader(JSBundleLoader.createAssetLoader( - mContext, - "assets://AndroidTestBundle.js", - false/* Asynchronous */)) - .setNativeModuleCallExceptionHandler( - new NativeModuleCallExceptionHandler() { - @Override - public void handleException(Exception e) { - throw new RuntimeException(e); - } - }) - .build(); + .setReactQueueConfigurationSpec(ReactQueueConfigurationSpec.createDefault()) + .setJSExecutor(executor) + .setRegistry(mNativeModuleRegistryBuilder.build()) + .setJSBundleLoader( + JSBundleLoader.createAssetLoader( + mContext, "assets://AndroidTestBundle.js", false /* Asynchronous */)) + .setNativeModuleCallExceptionHandler( + new NativeModuleCallExceptionHandler() { + @Override + public void handleException(Exception e) { + throw new RuntimeException(e); + } + }) + .build(); } } @@ -119,58 +110,56 @@ public class ReactTestHelper { } public static ReactTestFactory getReactTestFactory() { -// TODO: re-enable after cleanup of android-x migration -// Instrumentation inst = InstrumentationRegistry.getInstrumentation(); -// if (!(inst instanceof ReactTestFactory)) { - return new DefaultReactTestFactory(); -// } -// -// return (ReactTestFactory) inst; + // TODO: re-enable after cleanup of android-x migration + // Instrumentation inst = InstrumentationRegistry.getInstrumentation(); + // if (!(inst instanceof ReactTestFactory)) { + return new DefaultReactTestFactory(); + // } + // + // return (ReactTestFactory) inst; } public static ReactTestFactory.ReactInstanceEasyBuilder catalystInstanceBuilder( final ReactIntegrationTestCase testCase) { final ReactTestFactory.ReactInstanceEasyBuilder builder = - getReactTestFactory().getCatalystInstanceBuilder(); + getReactTestFactory().getCatalystInstanceBuilder(); ReactTestFactory.ReactInstanceEasyBuilder postBuilder = - new ReactTestFactory.ReactInstanceEasyBuilder() { - @Override - public ReactTestFactory.ReactInstanceEasyBuilder setContext(Context context) { - builder.setContext(context); - return this; - } + new ReactTestFactory.ReactInstanceEasyBuilder() { + @Override + public ReactTestFactory.ReactInstanceEasyBuilder setContext(Context context) { + builder.setContext(context); + return this; + } - @Override - public ReactTestFactory.ReactInstanceEasyBuilder addNativeModule(NativeModule module) { - builder.addNativeModule(module); - return this; - } + @Override + public ReactTestFactory.ReactInstanceEasyBuilder addNativeModule(NativeModule module) { + builder.addNativeModule(module); + return this; + } - @Override - public CatalystInstance build() { - final CatalystInstance instance = builder.build(); - testCase.initializeWithInstance(instance); - instance.runJSBundle(); -// TODO: re-enable after cleanup of android-x migration -// InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() { -// @Override -// public void run() { - ReactChoreographer.initialize(); - instance.initialize(); -// } -// }); - testCase.waitForBridgeAndUIIdle(); - return instance; - } - }; + @Override + public CatalystInstance build() { + final CatalystInstance instance = builder.build(); + testCase.initializeWithInstance(instance); + instance.runJSBundle(); + // TODO: re-enable after cleanup of android-x migration + // InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() { + // @Override + // public void run() { + ReactChoreographer.initialize(); + instance.initialize(); + // } + // }); + testCase.waitForBridgeAndUIIdle(); + return instance; + } + }; postBuilder.setContext(testCase.getContext()); return postBuilder; } - /** - * Gets the view at given path in the UI hierarchy, ignoring modals. - */ + /** Gets the view at given path in the UI hierarchy, ignoring modals. */ public static T getViewAtPath(ViewGroup rootView, int... path) { // The application root element is wrapped in a helper view in order // to be able to display modals. See renderApplication.js. @@ -192,8 +181,8 @@ public class ReactTestHelper { public static String getTestId(View view) { return view.getTag(R.id.react_test_id) instanceof String - ? (String) view.getTag(R.id.react_test_id) - : null; + ? (String) view.getTag(R.id.react_test_id) + : null; } private static View findChild(View root, Predicate predicate) { diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/testing/ScreenshotingFrameLayout.java b/ReactAndroid/src/androidTest/java/com/facebook/react/testing/ScreenshotingFrameLayout.java index b21088a8e2a..ce1f6e86916 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/testing/ScreenshotingFrameLayout.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/testing/ScreenshotingFrameLayout.java @@ -1,19 +1,17 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.testing; -import javax.annotation.Nullable; - import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.os.Looper; import android.widget.FrameLayout; +import javax.annotation.Nullable; /** * A FrameLayout that allows you to access the result of the last time its hierarchy was drawn. It @@ -35,8 +33,8 @@ public class ScreenshotingFrameLayout extends FrameLayout { if (mBitmap == null) { mBitmap = createNewBitmap(canvas); mCanvas.setBitmap(mBitmap); - } else if (mBitmap.getWidth() != canvas.getWidth() || - mBitmap.getHeight() != canvas.getHeight()) { + } else if (mBitmap.getWidth() != canvas.getWidth() + || mBitmap.getHeight() != canvas.getHeight()) { mBitmap.recycle(); mBitmap = createNewBitmap(canvas); mCanvas.setBitmap(mBitmap); diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/testing/SingleTouchGestureGenerator.java b/ReactAndroid/src/androidTest/java/com/facebook/react/testing/SingleTouchGestureGenerator.java index 8340977b73e..056740a7de2 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/testing/SingleTouchGestureGenerator.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/testing/SingleTouchGestureGenerator.java @@ -1,28 +1,26 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.testing; import android.os.SystemClock; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; - import com.facebook.react.testing.idledetection.IdleWaiter; /** * Provides methods for generating touch events and dispatching them directly to a given view. * Events scenarios are based on {@link android.test.TouchUtils} but they get gets dispatched - * directly through the view hierarchy using {@link View#dispatchTouchEvent} method instead of - * using instrumentation API. - *

- * All the events for a gesture are dispatched immediately which makes tests run very fast. - * The eventTime for each event is still set correctly. Android's gesture recognizers check - * eventTime in order to figure out gesture speed, and therefore scroll vs fling is recognized. + * directly through the view hierarchy using {@link View#dispatchTouchEvent} method instead of using + * instrumentation API. + * + *

All the events for a gesture are dispatched immediately which makes tests run very fast. The + * eventTime for each event is still set correctly. Android's gesture recognizers check eventTime in + * order to figure out gesture speed, and therefore scroll vs fling is recognized. */ public class SingleTouchGestureGenerator { @@ -44,10 +42,7 @@ public class SingleTouchGestureGenerator { } private SingleTouchGestureGenerator dispatchEvent( - final int action, - final float x, - final float y, - long eventTime) { + final int action, final float x, final float y, long eventTime) { mEventTime = eventTime; if (action == MotionEvent.ACTION_DOWN) { mLastDownTime = eventTime; @@ -90,10 +85,7 @@ public class SingleTouchGestureGenerator { } private SingleTouchGestureGenerator dispatchDelayedEvent( - int action, - float x, - float y, - long delay) { + int action, float x, float y, long delay) { return dispatchEvent(action, x, y, mEventTime + delay); } @@ -127,12 +119,7 @@ public class SingleTouchGestureGenerator { } public SingleTouchGestureGenerator drag( - float fromX, - float fromY, - float toX, - float toY, - int stepCount, - long totalDelay) { + float fromX, float fromY, float toX, float toY, int stepCount, long totalDelay) { float xStep = (toX - fromX) / stepCount; float yStep = (toY - fromY) / stepCount; diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/testing/StringRecordingModule.java b/ReactAndroid/src/androidTest/java/com/facebook/react/testing/StringRecordingModule.java index 9103a265ec5..fb4db8e8eaa 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/testing/StringRecordingModule.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/testing/StringRecordingModule.java @@ -1,21 +1,19 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.testing; -import java.util.ArrayList; -import java.util.List; - import com.facebook.react.bridge.BaseJavaModule; import com.facebook.react.bridge.ReactMethod; +import java.util.ArrayList; +import java.util.List; /** - * Native module provides single method {@link #record} which records its single string argument - * in calls array + * Native module provides single method {@link #record} which records its single string argument in + * calls array */ public class StringRecordingModule extends BaseJavaModule { diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/testing/idledetection/IdleWaiter.java b/ReactAndroid/src/androidTest/java/com/facebook/react/testing/idledetection/IdleWaiter.java index 958e15dfec6..6f224683614 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/testing/idledetection/IdleWaiter.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/testing/idledetection/IdleWaiter.java @@ -1,15 +1,12 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.testing.idledetection; -/** - * Interface for something that knows how to wait for bridge and UI idle. - */ +/** Interface for something that knows how to wait for bridge and UI idle. */ public interface IdleWaiter { void waitForBridgeAndUIIdle(); diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/testing/idledetection/ReactBridgeIdleSignaler.java b/ReactAndroid/src/androidTest/java/com/facebook/react/testing/idledetection/ReactBridgeIdleSignaler.java index 72aa0d46c4b..6599fdc1cf3 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/testing/idledetection/ReactBridgeIdleSignaler.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/testing/idledetection/ReactBridgeIdleSignaler.java @@ -1,17 +1,15 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.testing.idledetection; +import com.facebook.react.bridge.NotThreadSafeBridgeIdleDebugListener; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; -import com.facebook.react.bridge.NotThreadSafeBridgeIdleDebugListener; - /** * Utility class that uses {@link NotThreadSafeBridgeIdleDebugListener} interface to allow callers * to wait for the bridge to be idle. diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/testing/idledetection/ReactIdleDetectionUtil.java b/ReactAndroid/src/androidTest/java/com/facebook/react/testing/idledetection/ReactIdleDetectionUtil.java index 4410d808a2f..3b54f975acf 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/testing/idledetection/ReactIdleDetectionUtil.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/testing/idledetection/ReactIdleDetectionUtil.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.testing.idledetection; import com.facebook.react.bridge.ReactContext; @@ -16,104 +15,102 @@ public class ReactIdleDetectionUtil { * bridge to become idle, then waiting for the UI thread to become idle, then checking if the * bridge is idle again (if the bridge was idle before and is still idle after running the UI * thread to idle, then there are no more events to process in either place). - *

- * Also waits for any Choreographer callbacks to run after the initial sync since things like UI - * events are initiated from Choreographer callbacks. + * + *

Also waits for any Choreographer callbacks to run after the initial sync since things like + * UI events are initiated from Choreographer callbacks. */ public static void waitForBridgeAndUIIdle( - ReactBridgeIdleSignaler idleSignaler, - final ReactContext reactContext, - long timeoutMs) { + ReactBridgeIdleSignaler idleSignaler, final ReactContext reactContext, long timeoutMs) { - return ; + return; // TODO: re-enable after cleanup of android-x migration -// UiThreadUtil.assertNotOnUiThread(); -// -// long startTime = SystemClock.uptimeMillis(); -// waitInner(idleSignaler, timeoutMs); -// -// long timeToWait = Math.max(1, timeoutMs - (SystemClock.uptimeMillis() - startTime)); -// waitForChoreographer(timeToWait); -// waitForJSIdle(reactContext); -// -// timeToWait = Math.max(1, timeoutMs - (SystemClock.uptimeMillis() - startTime)); -// waitInner(idleSignaler, timeToWait); -// timeToWait = Math.max(1, timeoutMs - (SystemClock.uptimeMillis() - startTime)); -// waitForChoreographer(timeToWait); + // UiThreadUtil.assertNotOnUiThread(); + // + // long startTime = SystemClock.uptimeMillis(); + // waitInner(idleSignaler, timeoutMs); + // + // long timeToWait = Math.max(1, timeoutMs - (SystemClock.uptimeMillis() - startTime)); + // waitForChoreographer(timeToWait); + // waitForJSIdle(reactContext); + // + // timeToWait = Math.max(1, timeoutMs - (SystemClock.uptimeMillis() - startTime)); + // waitInner(idleSignaler, timeToWait); + // timeToWait = Math.max(1, timeoutMs - (SystemClock.uptimeMillis() - startTime)); + // waitForChoreographer(timeToWait); } -// private static void waitForChoreographer(long timeToWait) { -// final int waitFrameCount = 2; -// final CountDownLatch latch = new CountDownLatch(1); -// UiThreadUtil.runOnUiThread( -// new Runnable() { -// @Override -// public void run() { -// final ChoreographerCompat choreographerCompat = ChoreographerCompat.getInstance(); -// choreographerCompat.postFrameCallback( -// new ChoreographerCompat.FrameCallback() { -// -// private int frameCount = 0; -// -// @Override -// public void doFrame(long frameTimeNanos) { -// frameCount++; -// if (frameCount == waitFrameCount) { -// latch.countDown(); -// } else { -// choreographerCompat.postFrameCallback(this); -// } -// } -// }); -// } -// }); -// try { -// if (!latch.await(timeToWait, TimeUnit.MILLISECONDS)) { -// throw new RuntimeException("Timed out waiting for Choreographer"); -// } -// } catch (Exception e) { -// throw new RuntimeException(e); -// } -// } -// -// private static void waitForJSIdle(ReactContext reactContext) { -// if (!reactContext.hasActiveCatalystInstance()) { -// return; -// } -// final CountDownLatch latch = new CountDownLatch(1); -// -// reactContext.runOnJSQueueThread( -// new Runnable() { -// @Override -// public void run() { -// latch.countDown(); -// } -// }); -// -// try { -// if (!latch.await(5000, TimeUnit.MILLISECONDS)) { -// throw new RuntimeException("Timed out waiting for JS thread"); -// } -// } catch (Exception e) { -// throw new RuntimeException(e); -// } -// } -// -// private static void waitInner(ReactBridgeIdleSignaler idleSignaler, long timeToWait) { -// // TODO gets broken in gradle, do we need it? -// Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation(); -// long startTime = SystemClock.uptimeMillis(); -// boolean bridgeWasIdle = false; -// while (SystemClock.uptimeMillis() - startTime < timeToWait) { -// boolean bridgeIsIdle = idleSignaler.isBridgeIdle(); -// if (bridgeIsIdle && bridgeWasIdle) { -// return; -// } -// bridgeWasIdle = bridgeIsIdle; -// long newTimeToWait = Math.max(1, timeToWait - (SystemClock.uptimeMillis() - startTime)); -// idleSignaler.waitForIdle(newTimeToWait); -// instrumentation.waitForIdleSync(); -// } -// throw new RuntimeException("Timed out waiting for bridge and UI idle!"); -// } + // private static void waitForChoreographer(long timeToWait) { + // final int waitFrameCount = 2; + // final CountDownLatch latch = new CountDownLatch(1); + // UiThreadUtil.runOnUiThread( + // new Runnable() { + // @Override + // public void run() { + // final ChoreographerCompat choreographerCompat = ChoreographerCompat.getInstance(); + // choreographerCompat.postFrameCallback( + // new ChoreographerCompat.FrameCallback() { + // + // private int frameCount = 0; + // + // @Override + // public void doFrame(long frameTimeNanos) { + // frameCount++; + // if (frameCount == waitFrameCount) { + // latch.countDown(); + // } else { + // choreographerCompat.postFrameCallback(this); + // } + // } + // }); + // } + // }); + // try { + // if (!latch.await(timeToWait, TimeUnit.MILLISECONDS)) { + // throw new RuntimeException("Timed out waiting for Choreographer"); + // } + // } catch (Exception e) { + // throw new RuntimeException(e); + // } + // } + // + // private static void waitForJSIdle(ReactContext reactContext) { + // if (!reactContext.hasActiveCatalystInstance()) { + // return; + // } + // final CountDownLatch latch = new CountDownLatch(1); + // + // reactContext.runOnJSQueueThread( + // new Runnable() { + // @Override + // public void run() { + // latch.countDown(); + // } + // }); + // + // try { + // if (!latch.await(5000, TimeUnit.MILLISECONDS)) { + // throw new RuntimeException("Timed out waiting for JS thread"); + // } + // } catch (Exception e) { + // throw new RuntimeException(e); + // } + // } + // + // private static void waitInner(ReactBridgeIdleSignaler idleSignaler, long timeToWait) { + // // TODO gets broken in gradle, do we need it? + // Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation(); + // long startTime = SystemClock.uptimeMillis(); + // boolean bridgeWasIdle = false; + // while (SystemClock.uptimeMillis() - startTime < timeToWait) { + // boolean bridgeIsIdle = idleSignaler.isBridgeIdle(); + // if (bridgeIsIdle && bridgeWasIdle) { + // return; + // } + // bridgeWasIdle = bridgeIsIdle; + // long newTimeToWait = Math.max(1, timeToWait - (SystemClock.uptimeMillis() - startTime)); + // idleSignaler.waitForIdle(newTimeToWait); + // instrumentation.waitForIdleSync(); + // } + // throw new RuntimeException("Timed out waiting for bridge and UI idle!"); + // } } diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/testing/network/NetworkRecordingModuleMock.java b/ReactAndroid/src/androidTest/java/com/facebook/react/testing/network/NetworkRecordingModuleMock.java index 64bb99301d7..09babeee703 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/testing/network/NetworkRecordingModuleMock.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/testing/network/NetworkRecordingModuleMock.java @@ -1,14 +1,11 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.testing.network; -import javax.annotation.Nullable; - import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.Callback; import com.facebook.react.bridge.ReactApplicationContext; @@ -20,6 +17,7 @@ import com.facebook.react.bridge.WritableArray; import com.facebook.react.bridge.WritableMap; import com.facebook.react.module.annotations.ReactModule; import com.facebook.react.modules.core.DeviceEventManagerModule; +import javax.annotation.Nullable; /** * Mock Networking module that records last request received by {@link #sendRequest} method and @@ -70,10 +68,7 @@ public class NetworkRecordingModuleMock extends ReactContextBaseJavaModule { } private void fireReactCallback( - Callback callback, - int status, - @Nullable String headers, - @Nullable String body) { + Callback callback, int status, @Nullable String headers, @Nullable String body) { callback.invoke(status, headers, body); } diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/testing/rule/ReactNativeTestRule.java b/ReactAndroid/src/androidTest/java/com/facebook/react/testing/rule/ReactNativeTestRule.java index c4bf721717e..0067f4220d3 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/testing/rule/ReactNativeTestRule.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/testing/rule/ReactNativeTestRule.java @@ -6,16 +6,14 @@ package com.facebook.react.testing.rule; import android.app.Activity; -import android.os.Build; -import androidx.test.rule.ActivityTestRule; import android.view.ViewTreeObserver.OnGlobalLayoutListener; +import androidx.test.rule.ActivityTestRule; import com.facebook.react.ReactInstanceManager; import com.facebook.react.ReactPackage; import com.facebook.react.ReactRootView; import com.facebook.react.bridge.ReactContext; import com.facebook.react.common.LifecycleState; import com.facebook.react.shell.MainReactPackage; -import com.facebook.react.testing.ReactInstanceSpecForTest; import com.facebook.react.testing.ReactTestHelper; import com.facebook.react.testing.idledetection.ReactBridgeIdleSignaler; import com.facebook.react.testing.idledetection.ReactIdleDetectionUtil; @@ -164,9 +162,7 @@ public class ReactNativeTestRule implements TestRule { public void waitForIdleSync() { ReactIdleDetectionUtil.waitForBridgeAndUIIdle( - mBridgeIdleSignaler, - mReactInstanceManager.getCurrentReactContext(), - IDLE_TIMEOUT_MS); + mBridgeIdleSignaler, mReactInstanceManager.getCurrentReactContext(), IDLE_TIMEOUT_MS); } /** Returns the react view */ diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/AnimatedTransformTest.java b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/AnimatedTransformTest.java index f2ddc0d2e9e..0c6280c7d74 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/AnimatedTransformTest.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/AnimatedTransformTest.java @@ -1,20 +1,16 @@ /** * Copyright (c) 2013-present, Facebook, Inc. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.tests; import android.view.View; - - -import com.facebook.react.testing.ReactInstanceSpecForTest; -import com.facebook.react.testing.StringRecordingModule; -import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.testing.ReactAppInstrumentationTestCase; +import com.facebook.react.testing.ReactInstanceSpecForTest; import com.facebook.react.testing.ReactTestHelper; +import com.facebook.react.testing.StringRecordingModule; /** * Integration test for {@code removeClippedSubviews} property that verify correct scrollview @@ -32,18 +28,16 @@ public class AnimatedTransformTest extends ReactAppInstrumentationTestCase { @Override protected ReactInstanceSpecForTest createReactInstanceSpecForTest() { mStringRecordingModule = new StringRecordingModule(); - return super.createReactInstanceSpecForTest() - .addNativeModule(mStringRecordingModule); + return super.createReactInstanceSpecForTest().addNativeModule(mStringRecordingModule); } public void testAnimatedRotation() { waitForBridgeAndUIIdle(); - View button = ReactTestHelper.getViewWithReactTestId( - getActivity().getRootView(), - "TouchableOpacity"); + View button = + ReactTestHelper.getViewWithReactTestId(getActivity().getRootView(), "TouchableOpacity"); - // Tap the button which triggers the animated transform containing the + // Tap the button which triggers the animated transform containing the // rotation strings. createGestureGenerator().startGesture(button).endGesture(); waitForBridgeAndUIIdle(); @@ -51,5 +45,4 @@ public class AnimatedTransformTest extends ReactAppInstrumentationTestCase { // The previous cast error will prevent it from getting here assertEquals(2, mStringRecordingModule.getCalls().size()); } - } diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/CatalystMeasureLayoutTest.java b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/CatalystMeasureLayoutTest.java index a86805fb62c..274d1f94e8b 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/CatalystMeasureLayoutTest.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/CatalystMeasureLayoutTest.java @@ -1,58 +1,54 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.tests; -import com.facebook.react.testing.ReactInstanceSpecForTest; import com.facebook.react.bridge.JavaScriptModule; -import com.facebook.react.uimanager.UIManagerModule; import com.facebook.react.testing.AssertModule; import com.facebook.react.testing.ReactAppInstrumentationTestCase; +import com.facebook.react.testing.ReactInstanceSpecForTest; +import com.facebook.react.uimanager.UIManagerModule; /** - * Tests for {@link UIManagerModule#measure}, {@link UIManagerModule#measureLayout}, and - * {@link UIManagerModule#measureLayoutRelativeToParent}. Tests measurement for views in the - * following hierarchy: + * Tests for {@link UIManagerModule#measure}, {@link UIManagerModule#measureLayout}, and {@link + * UIManagerModule#measureLayoutRelativeToParent}. Tests measurement for views in the following + * hierarchy: * - * +---------------------------------------------+ - * | A | - * | | - * | +-----------+ +---------+ | - * | | B | | D | | - * | | +---+ | | | | - * | | | C | | | | | - * | | | | | +---------+ | - * | | +---+ | | - * | +-----------+ | - * | | - * | | - * | | - * +---------------------------------------------+ + *

+---------------------------------------------+ | A | | | | +-----------+ +---------+ | | | B + * | | D | | | | +---+ | | | | | | | C | | | | | | | | | | +---------+ | | | +---+ | | | + * +-----------+ | | | | | | | +---------------------------------------------+ * - * View locations and dimensions: - * A - (0,0) to (500, 500) (500x500) - * B - (50,80) to (250, 380) (200x300) - * C - (150,150) to (200, 300) (50x150) - * D - (400,100) to (450, 300) (50x200) + *

View locations and dimensions: A - (0,0) to (500, 500) (500x500) B - (50,80) to (250, 380) + * (200x300) C - (150,150) to (200, 300) (50x150) D - (400,100) to (450, 300) (50x200) */ public class CatalystMeasureLayoutTest extends ReactAppInstrumentationTestCase { private static interface MeasureLayoutTestModule extends JavaScriptModule { public void verifyMeasureOnViewA(); + public void verifyMeasureOnViewC(); + public void verifyMeasureLayoutCRelativeToA(); + public void verifyMeasureLayoutCRelativeToB(); + public void verifyMeasureLayoutCRelativeToSelf(); + public void verifyMeasureLayoutRelativeToParentOnViewA(); + public void verifyMeasureLayoutRelativeToParentOnViewB(); + public void verifyMeasureLayoutRelativeToParentOnViewC(); + public void verifyMeasureLayoutDRelativeToB(); + public void verifyMeasureLayoutNonExistentTag(); + public void verifyMeasureLayoutNonExistentAncestor(); + public void verifyMeasureLayoutRelativeToParentNonExistentTag(); } @@ -73,8 +69,7 @@ public class CatalystMeasureLayoutTest extends ReactAppInstrumentationTestCase { @Override protected ReactInstanceSpecForTest createReactInstanceSpecForTest() { mAssertModule = new AssertModule(); - return super.createReactInstanceSpecForTest() - .addNativeModule(mAssertModule); + return super.createReactInstanceSpecForTest().addNativeModule(mAssertModule); } private void waitForBridgeIdleAndVerifyAsserts() { diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/CatalystMultitouchHandlingTestCase.java b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/CatalystMultitouchHandlingTestCase.java index 9a18ca66cb5..7aae6556514 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/CatalystMultitouchHandlingTestCase.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/CatalystMultitouchHandlingTestCase.java @@ -1,19 +1,16 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.tests; -import java.util.List; - import android.view.MotionEvent; - -import com.facebook.react.testing.ReactInstanceSpecForTest; import com.facebook.react.testing.ReactAppInstrumentationTestCase; +import com.facebook.react.testing.ReactInstanceSpecForTest; import com.facebook.react.testing.StringRecordingModule; +import java.util.List; /** * Test case for verifying that multitouch events are directed to the React's view touch handlers @@ -30,8 +27,7 @@ public class CatalystMultitouchHandlingTestCase extends ReactAppInstrumentationT @Override protected ReactInstanceSpecForTest createReactInstanceSpecForTest() { - return new ReactInstanceSpecForTest() - .addNativeModule(mRecordingModule); + return new ReactInstanceSpecForTest().addNativeModule(mRecordingModule); } /** @@ -102,27 +98,41 @@ public class CatalystMultitouchHandlingTestCase extends ReactAppInstrumentationT final int pointerCount, final MotionEvent.PointerProperties[] pointerProps, final MotionEvent.PointerCoords[] pointerCoords) { - getRootView().post( - new Runnable() { - @Override - public void run() { - MotionEvent event = - MotionEvent.obtain(start, when, action, pointerCount, pointerProps, pointerCoords, 0, 0, 1.0f, 1.0f, 0, 0, 0, 0); - getRootView().dispatchTouchEvent(event); - event.recycle(); - } - }); + getRootView() + .post( + new Runnable() { + @Override + public void run() { + MotionEvent event = + MotionEvent.obtain( + start, + when, + action, + pointerCount, + pointerProps, + pointerCoords, + 0, + 0, + 1.0f, + 1.0f, + 0, + 0, + 0, + 0); + getRootView().dispatchTouchEvent(event); + event.recycle(); + } + }); getInstrumentation().waitForIdleSync(); } /** * This method "replay" multi-touch gesture recorded with modified TouchesHelper class that - * generated this piece of code (see https://phabricator.fb.com/P19756940). - * This is not intended to be copied/reused and once we need to have more multitouch gestures - * in instrumentation tests we should either: - * - implement nice generator similar to {@link SingleTouchGestureGenerator} - * - implement gesture recorded that will record touch data using arbitrary format and then read - * this recorded touch sequence during tests instead of generating code like this + * generated this piece of code (see https://phabricator.fb.com/P19756940). This is not intended + * to be copied/reused and once we need to have more multitouch gestures in instrumentation tests + * we should either: - implement nice generator similar to {@link SingleTouchGestureGenerator} - + * implement gesture recorded that will record touch data using arbitrary format and then read + * this recorded touch sequence during tests instead of generating code like this */ private void generateRecordedPinchTouchEvents() { // START OF GENERATED CODE @@ -149,7 +159,13 @@ public class CatalystMultitouchHandlingTestCase extends ReactAppInstrumentationT pointerCoords[0] = createPointerCoords(267.0f, 346.0f); pointerProps[1] = createPointerProps(1, 1); pointerCoords[1] = createPointerCoords(225.0f, 542.0f); - dispatchEvent(MotionEvent.ACTION_POINTER_DOWN | (1 << MotionEvent.ACTION_POINTER_INDEX_SHIFT), 446560605, 446560630, 2, pointerProps, pointerCoords); + dispatchEvent( + MotionEvent.ACTION_POINTER_DOWN | (1 << MotionEvent.ACTION_POINTER_INDEX_SHIFT), + 446560605, + 446560630, + 2, + pointerProps, + pointerCoords); } { @@ -639,7 +655,13 @@ public class CatalystMultitouchHandlingTestCase extends ReactAppInstrumentationT pointerCoords[0] = createPointerCoords(349.0f, 110.0f); pointerProps[1] = createPointerProps(1, 1); pointerCoords[1] = createPointerCoords(151.0f, 680.0f); - dispatchEvent(MotionEvent.ACTION_POINTER_UP | (0 << MotionEvent.ACTION_POINTER_INDEX_SHIFT), 446560605, 446561443, 2, pointerProps, pointerCoords); + dispatchEvent( + MotionEvent.ACTION_POINTER_UP | (0 << MotionEvent.ACTION_POINTER_INDEX_SHIFT), + 446560605, + 446561443, + 2, + pointerProps, + pointerCoords); } { @@ -651,5 +673,4 @@ public class CatalystMultitouchHandlingTestCase extends ReactAppInstrumentationT } // END OF GENERATED CODE } - } diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/CatalystNativeJSToJavaParametersTestCase.java b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/CatalystNativeJSToJavaParametersTestCase.java index 5631647bcd8..42d41c77f49 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/CatalystNativeJSToJavaParametersTestCase.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/CatalystNativeJSToJavaParametersTestCase.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.tests; import com.facebook.react.bridge.BaseJavaModule; @@ -44,35 +43,45 @@ import org.junit.Ignore; /** * Integration test to verify passing various types of parameters from JS to Java works * - * TODO: we should run these tests with isBlockingSynchronousMethod = true as well, - * since they currently use a completely different codepath + *

TODO: we should run these tests with isBlockingSynchronousMethod = true as well, since they + * currently use a completely different codepath */ @Ignore("Fix prop types and view managers.") public class CatalystNativeJSToJavaParametersTestCase extends ReactIntegrationTestCase { private interface TestJSToJavaParametersModule extends JavaScriptModule { void returnBasicTypes(); + void returnBoxedTypes(); + void returnDynamicTypes(); void returnArrayWithBasicTypes(); + void returnNestedArray(); + void returnArrayWithMaps(); void returnMapWithBasicTypes(); + void returnNestedMap(); + void returnMapWithArrays(); void returnArrayWithStringDoubleIntMapArrayBooleanNull(); + void returnMapWithStringDoubleIntMapArrayBooleanNull(); void returnMapForMerge1(); + void returnMapForMerge2(); void returnMapWithMultibyteUTF8CharacterString(); + void returnArrayWithMultibyteUTF8CharacterString(); void returnArrayWithLargeInts(); + void returnMapWithLargeInts(); } @@ -83,10 +92,8 @@ public class CatalystNativeJSToJavaParametersTestCase extends ReactIntegrationTe protected void setUp() throws Exception { super.setUp(); - List viewManagers = Arrays.asList( - new ReactViewManager()); - final UIManagerModule mUIManager = - new UIManagerModule(getContext(), viewManagers, 0); + List viewManagers = Arrays.asList(new ReactViewManager()); + final UIManagerModule mUIManager = new UIManagerModule(getContext(), viewManagers, 0); UiThreadUtil.runOnUiThread( new Runnable() { @Override @@ -97,14 +104,15 @@ public class CatalystNativeJSToJavaParametersTestCase extends ReactIntegrationTe waitForIdleSync(); mRecordingTestModule = new RecordingTestModule(); - mCatalystInstance = ReactTestHelper.catalystInstanceBuilder(this) - .addNativeModule(mRecordingTestModule) - .addNativeModule(new AndroidInfoModule(getContext())) - .addNativeModule(new DeviceInfoModule(getContext())) - .addNativeModule(new AppStateModule(getContext())) - .addNativeModule(new FakeWebSocketModule()) - .addNativeModule(mUIManager) - .build(); + mCatalystInstance = + ReactTestHelper.catalystInstanceBuilder(this) + .addNativeModule(mRecordingTestModule) + .addNativeModule(new AndroidInfoModule(getContext())) + .addNativeModule(new DeviceInfoModule(getContext())) + .addNativeModule(new AppStateModule(getContext())) + .addNativeModule(new FakeWebSocketModule()) + .addNativeModule(mUIManager) + .build(); } public void testBasicTypes() { @@ -314,7 +322,8 @@ public class CatalystNativeJSToJavaParametersTestCase extends ReactIntegrationTe } public void testGetTypeFromArray() { - mCatalystInstance.getJSModule(TestJSToJavaParametersModule.class) + mCatalystInstance + .getJSModule(TestJSToJavaParametersModule.class) .returnArrayWithStringDoubleIntMapArrayBooleanNull(); waitForBridgeAndUIIdle(); @@ -332,7 +341,8 @@ public class CatalystNativeJSToJavaParametersTestCase extends ReactIntegrationTe } public void testGetTypeFromMap() { - mCatalystInstance.getJSModule(TestJSToJavaParametersModule.class) + mCatalystInstance + .getJSModule(TestJSToJavaParametersModule.class) .returnMapWithStringDoubleIntMapArrayBooleanNull(); waitForBridgeAndUIIdle(); @@ -350,7 +360,8 @@ public class CatalystNativeJSToJavaParametersTestCase extends ReactIntegrationTe } public void testGetWrongTypeFromArray() { - mCatalystInstance.getJSModule(TestJSToJavaParametersModule.class) + mCatalystInstance + .getJSModule(TestJSToJavaParametersModule.class) .returnArrayWithStringDoubleIntMapArrayBooleanNull(); waitForBridgeAndUIIdle(); @@ -367,7 +378,8 @@ public class CatalystNativeJSToJavaParametersTestCase extends ReactIntegrationTe } public void testGetWrongTypeFromMap() { - mCatalystInstance.getJSModule(TestJSToJavaParametersModule.class) + mCatalystInstance + .getJSModule(TestJSToJavaParametersModule.class) .returnMapWithStringDoubleIntMapArrayBooleanNull(); waitForBridgeAndUIIdle(); @@ -595,8 +607,9 @@ public class CatalystNativeJSToJavaParametersTestCase extends ReactIntegrationTe keys.add(mapIterator.nextKey()); } - Set expectedKeys = new HashSet( - Arrays.asList("stringKey", "doubleKey", "intKey", "booleanKey", "nullKey")); + Set expectedKeys = + new HashSet( + Arrays.asList("stringKey", "doubleKey", "intKey", "booleanKey", "nullKey")); assertEquals(keys, expectedKeys); } @@ -669,9 +682,7 @@ public class CatalystNativeJSToJavaParametersTestCase extends ReactIntegrationTe } private void assertUnexpectedTypeExceptionThrown( - ReadableArray array, - int index, - String typeToAskFor) { + ReadableArray array, int index, String typeToAskFor) { boolean gotException = false; try { arrayGetByType(array, index, typeToAskFor); @@ -683,9 +694,7 @@ public class CatalystNativeJSToJavaParametersTestCase extends ReactIntegrationTe } private void assertUnexpectedTypeExceptionThrown( - ReadableMap map, - String key, - String typeToAskFor) { + ReadableMap map, String key, String typeToAskFor) { boolean gotException = false; try { mapGetByType(map, key, typeToAskFor); @@ -697,9 +706,7 @@ public class CatalystNativeJSToJavaParametersTestCase extends ReactIntegrationTe } private void assertArrayOutOfBoundsExceptionThrown( - ReadableArray array, - int index, - String typeToAskFor) { + ReadableArray array, int index, String typeToAskFor) { boolean gotException = false; try { arrayGetByType(array, index, typeToAskFor); @@ -710,10 +717,7 @@ public class CatalystNativeJSToJavaParametersTestCase extends ReactIntegrationTe assertTrue(gotException); } - private void assertNoSuchKeyExceptionThrown( - ReadableMap map, - String key, - String typeToAskFor) { + private void assertNoSuchKeyExceptionThrown(ReadableMap map, String key, String typeToAskFor) { boolean gotException = false; try { mapGetByType(map, key, typeToAskFor); @@ -724,8 +728,7 @@ public class CatalystNativeJSToJavaParametersTestCase extends ReactIntegrationTe assertTrue(gotException); } - private static void assertInvalidIteratorExceptionThrown( - ReadableMapKeySetIterator iterator) { + private static void assertInvalidIteratorExceptionThrown(ReadableMapKeySetIterator iterator) { boolean gotException = false; try { iterator.nextKey(); @@ -787,12 +790,12 @@ public class CatalystNativeJSToJavaParametersTestCase extends ReactIntegrationTe @ReactMethod public void receiveBasicTypes(String s, double d, boolean b, String nullableString) { - mBasicTypesCalls.add(new Object[]{s, d, b, nullableString}); + mBasicTypesCalls.add(new Object[] {s, d, b, nullableString}); } @ReactMethod public void receiveBoxedTypes(Integer i, Double d, Boolean b) { - mBoxedTypesCalls.add(new Object[]{i, d, b}); + mBoxedTypesCalls.add(new Object[] {i, d, b}); } @ReactMethod diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/CatalystNativeJavaToJSArgumentsTestCase.java b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/CatalystNativeJavaToJSArgumentsTestCase.java index 0014233333e..7c78e4d9592 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/CatalystNativeJavaToJSArgumentsTestCase.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/CatalystNativeJavaToJSArgumentsTestCase.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.tests; import com.facebook.react.bridge.CatalystInstance; @@ -28,9 +27,7 @@ import java.util.Arrays; import java.util.List; import org.junit.Ignore; -/** - * Test marshalling arguments from Java to JS to appropriate native classes. - */ +/** Test marshalling arguments from Java to JS to appropriate native classes. */ @Ignore("Fix prop types and view managers.") public class CatalystNativeJavaToJSArgumentsTestCase extends ReactIntegrationTestCase { @@ -38,16 +35,21 @@ public class CatalystNativeJavaToJSArgumentsTestCase extends ReactIntegrationTes void receiveBasicTypes(String s, double d, boolean b, String nullString); void receiveArrayWithBasicTypes(WritableArray array); + void receiveNestedArray(WritableArray nestedArray); + void receiveArrayWithMaps(WritableArray arrayWithMaps); void receiveMapWithBasicTypes(WritableMap map); + void receiveNestedMap(WritableMap nestedMap); + void receiveMapWithArrays(WritableMap mapWithArrays); - void receiveMapAndArrayWithNullValues( - WritableMap map, - WritableArray array); + + void receiveMapAndArrayWithNullValues(WritableMap map, WritableArray array); + void receiveMapWithMultibyteUTF8CharacterString(WritableMap map); + void receiveArrayWithMultibyteUTF8CharacterString(WritableArray array); } @@ -58,10 +60,8 @@ public class CatalystNativeJavaToJSArgumentsTestCase extends ReactIntegrationTes protected void setUp() throws Exception { super.setUp(); - List viewManagers = Arrays.asList( - new ReactViewManager()); - final UIManagerModule mUIManager = - new UIManagerModule(getContext(), viewManagers, 0); + List viewManagers = Arrays.asList(new ReactViewManager()); + final UIManagerModule mUIManager = new UIManagerModule(getContext(), viewManagers, 0); UiThreadUtil.runOnUiThread( new Runnable() { @Override @@ -73,17 +73,19 @@ public class CatalystNativeJavaToJSArgumentsTestCase extends ReactIntegrationTes mAssertModule = new AssertModule(); - mInstance = ReactTestHelper.catalystInstanceBuilder(this) - .addNativeModule(mAssertModule) - .addNativeModule(new DeviceInfoModule(getContext())) - .addNativeModule(new AppStateModule(getContext())) - .addNativeModule(new FakeWebSocketModule()) - .addNativeModule(mUIManager) - .build(); + mInstance = + ReactTestHelper.catalystInstanceBuilder(this) + .addNativeModule(mAssertModule) + .addNativeModule(new DeviceInfoModule(getContext())) + .addNativeModule(new AppStateModule(getContext())) + .addNativeModule(new FakeWebSocketModule()) + .addNativeModule(mUIManager) + .build(); } public void testBasicTypes() { - mInstance.getJSModule(TestJavaToJSArgumentsModule.class) + mInstance + .getJSModule(TestJavaToJSArgumentsModule.class) .receiveBasicTypes("foo", 3.14, true, null); waitForBridgeAndUIIdle(); mAssertModule.verifyAssertsAndReset(); @@ -182,7 +184,8 @@ public class CatalystNativeJavaToJSArgumentsTestCase extends ReactIntegrationTes array.pushArray(null); array.pushMap(null); - mInstance.getJSModule(TestJavaToJSArgumentsModule.class) + mInstance + .getJSModule(TestJavaToJSArgumentsModule.class) .receiveMapAndArrayWithNullValues(map, array); waitForBridgeAndUIIdle(); mAssertModule.verifyAssertsAndReset(); diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/CatalystNativeJavaToJSReturnValuesTestCase.java b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/CatalystNativeJavaToJSReturnValuesTestCase.java index d53d98feb5a..e2d3636ec5e 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/CatalystNativeJavaToJSReturnValuesTestCase.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/CatalystNativeJavaToJSReturnValuesTestCase.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.tests; import com.facebook.react.bridge.BaseJavaModule; @@ -27,14 +26,13 @@ import com.facebook.react.uimanager.ViewManager; import java.util.ArrayList; import org.junit.Ignore; -/** - * Test marshalling return values from Java to JS - */ +/** Test marshalling return values from Java to JS */ @Ignore("Fix prop types and view managers.") public class CatalystNativeJavaToJSReturnValuesTestCase extends ReactIntegrationTestCase { private interface TestJavaToJSReturnValuesModule extends JavaScriptModule { void callMethod(String methodName, String expectedReturnType, String expectedJSON); + void triggerException(); } @@ -110,19 +108,19 @@ public class CatalystNativeJavaToJSReturnValuesTestCase extends ReactIntegration super.setUp(); final UIManagerModule mUIManager = - new UIManagerModule( - getContext(), new ArrayList(), 0); + new UIManagerModule(getContext(), new ArrayList(), 0); mAssertModule = new AssertModule(); - mInstance = ReactTestHelper.catalystInstanceBuilder(this) - .addNativeModule(mAssertModule) - .addNativeModule(new DeviceInfoModule(getContext())) - .addNativeModule(new AppStateModule(getContext())) - .addNativeModule(new FakeWebSocketModule()) - .addNativeModule(mUIManager) - .addNativeModule(new TestModule()) - .build(); + mInstance = + ReactTestHelper.catalystInstanceBuilder(this) + .addNativeModule(mAssertModule) + .addNativeModule(new DeviceInfoModule(getContext())) + .addNativeModule(new AppStateModule(getContext())) + .addNativeModule(new FakeWebSocketModule()) + .addNativeModule(mUIManager) + .addNativeModule(new TestModule()) + .build(); } public void testGetPrimitives() { diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/CatalystSubviewsClippingTestCase.java b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/CatalystSubviewsClippingTestCase.java index 5b7033695cd..fbd1a25c644 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/CatalystSubviewsClippingTestCase.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/CatalystSubviewsClippingTestCase.java @@ -1,30 +1,25 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.tests; -import java.util.ArrayList; -import java.util.List; - import android.content.Context; -import javax.annotation.Nullable; import android.widget.ScrollView; - import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.testing.ReactAppInstrumentationTestCase; import com.facebook.react.testing.ReactInstanceSpecForTest; import com.facebook.react.uimanager.PixelUtil; -import com.facebook.react.uimanager.annotations.ReactProp; import com.facebook.react.uimanager.ThemedReactContext; +import com.facebook.react.uimanager.annotations.ReactProp; import com.facebook.react.views.view.ReactViewGroup; import com.facebook.react.views.view.ReactViewManager; - +import java.util.ArrayList; +import java.util.List; +import javax.annotation.Nullable; import org.junit.Assert; -import org.junit.Ignore; /** * Integration test for {@code removeClippedSubviews} property that verify correct scrollview @@ -34,9 +29,13 @@ public class CatalystSubviewsClippingTestCase extends ReactAppInstrumentationTes private interface SubviewsClippingTestModule extends JavaScriptModule { void renderClippingSample1(); + void renderClippingSample2(); + void renderScrollViewTest(); + void renderUpdatingSample1(boolean update1, boolean update2); + void renderUpdatingSample2(boolean update); } @@ -49,78 +48,50 @@ public class CatalystSubviewsClippingTestCase extends ReactAppInstrumentationTes @Override protected ReactInstanceSpecForTest createReactInstanceSpecForTest() { - return super.createReactInstanceSpecForTest() - .addViewManager(new ClippableViewManager(mEvents)); + return super.createReactInstanceSpecForTest().addViewManager(new ClippableViewManager(mEvents)); } /** - * In this test view are layout in a following way: - * +-----------------------------+ - * | | - * | +---------------------+ | - * | | inner1 | | - * | +---------------------+ | - * | +-------------------------+ | - * | | outer (clip=true) | | - * | | +---------------------+ | | - * | | | inner2 | | | - * | | +---------------------+ | | - * | | | | - * | +-------------------------+ | - * | +---------------------+ | - * | | inner3 | | - * | +---------------------+ | - * | | + * In this test view are layout in a following way: +-----------------------------+ | | | + * +---------------------+ | | | inner1 | | | +---------------------+ | | + * +-------------------------+ | | | outer (clip=true) | | | | +---------------------+ | | | | | + * inner2 | | | | | +---------------------+ | | | | | | | +-------------------------+ | | + * +---------------------+ | | | inner3 | | | +---------------------+ | | | * +-----------------------------+ * - * We expect only outer and inner2 to be attached + *

We expect only outer and inner2 to be attached */ public void XtestOneLevelClippingInView() throws Throwable { mEvents.clear(); getReactContext().getJSModule(SubviewsClippingTestModule.class).renderClippingSample1(); waitForBridgeAndUIIdle(); - Assert.assertArrayEquals(new String[]{"Attach_outer", "Attach_inner2"}, mEvents.toArray()); + Assert.assertArrayEquals(new String[] {"Attach_outer", "Attach_inner2"}, mEvents.toArray()); } /** - * In this test view are layout in a following way: - * +-----------------------------+ - * | outer (clip=true) | - * | | - * | | - * | | - * | +-----------------------------+ - * | | complexInner (clip=true) | - * | | +----------+ | +---------+ | - * | | | inner1 | | | inner2 | | - * | | | | | | | | - * | | +----------+ | +---------+ | - * +--------------+--------------+ | - * | +----------+ +---------+ | - * | | inner3 | | inner4 | | - * | | | | | | - * | +----------+ +---------+ | - * | | - * +-----------------------------+ + * In this test view are layout in a following way: +-----------------------------+ | outer + * (clip=true) | | | | | | | | +-----------------------------+ | | complexInner (clip=true) | | | + * +----------+ | +---------+ | | | | inner1 | | | inner2 | | | | | | | | | | | | +----------+ | + * +---------+ | +--------------+--------------+ | | +----------+ +---------+ | | | inner3 | | + * inner4 | | | | | | | | | +----------+ +---------+ | | | +-----------------------------+ * - * We expect outer, complexInner & inner1 to be attached + *

We expect outer, complexInner & inner1 to be attached */ public void XtestTwoLevelClippingInView() throws Throwable { mEvents.clear(); getReactContext().getJSModule(SubviewsClippingTestModule.class).renderClippingSample2(); waitForBridgeAndUIIdle(); Assert.assertArrayEquals( - new String[]{"Attach_outer", "Attach_complexInner", "Attach_inner1"}, - mEvents.toArray()); + new String[] {"Attach_outer", "Attach_complexInner", "Attach_inner1"}, mEvents.toArray()); } /** * This test verifies that we update clipped subviews appropriately when some of them gets * re-layouted. * - * In this test scenario we render clipping view ("outer") with two subviews, one is outside and - * clipped and one is inside (absolutely positioned). By updating view props we first change the - * height of the first element so that it should intersect with clipping "outer" view. Then we + *

In this test scenario we render clipping view ("outer") with two subviews, one is outside + * and clipped and one is inside (absolutely positioned). By updating view props we first change + * the height of the first element so that it should intersect with clipping "outer" view. Then we * update top position of the second view so that is should go off screen. */ public void testClippingAfterLayoutInner() { @@ -130,24 +101,24 @@ public class CatalystSubviewsClippingTestCase extends ReactAppInstrumentationTes mEvents.clear(); subviewsClippingTestModule.renderUpdatingSample1(false, false); waitForBridgeAndUIIdle(); - Assert.assertArrayEquals(new String[]{"Attach_outer", "Attach_inner2"}, mEvents.toArray()); + Assert.assertArrayEquals(new String[] {"Attach_outer", "Attach_inner2"}, mEvents.toArray()); mEvents.clear(); subviewsClippingTestModule.renderUpdatingSample1(true, false); waitForBridgeAndUIIdle(); - Assert.assertArrayEquals(new String[]{"Attach_inner1"}, mEvents.toArray()); + Assert.assertArrayEquals(new String[] {"Attach_inner1"}, mEvents.toArray()); mEvents.clear(); subviewsClippingTestModule.renderUpdatingSample1(true, true); waitForBridgeAndUIIdle(); - Assert.assertArrayEquals(new String[]{"Detach_inner2"}, mEvents.toArray()); + Assert.assertArrayEquals(new String[] {"Detach_inner2"}, mEvents.toArray()); } /** * This test verifies that we update clipping views appropriately when parent view layout changes * in a way that affects clipping. * - * In this test we render clipping view ("outer") set to be 100x100dp with inner view that is + *

In this test we render clipping view ("outer") set to be 100x100dp with inner view that is * absolutely positioned out of the clipping area of the parent view. Then we resize parent view * so that inner view should be visible. */ @@ -158,12 +129,12 @@ public class CatalystSubviewsClippingTestCase extends ReactAppInstrumentationTes mEvents.clear(); subviewsClippingTestModule.renderUpdatingSample2(false); waitForBridgeAndUIIdle(); - Assert.assertArrayEquals(new String[]{"Attach_outer"}, mEvents.toArray()); + Assert.assertArrayEquals(new String[] {"Attach_outer"}, mEvents.toArray()); mEvents.clear(); subviewsClippingTestModule.renderUpdatingSample2(true); waitForBridgeAndUIIdle(); - Assert.assertArrayEquals(new String[]{"Attach_inner"}, mEvents.toArray()); + Assert.assertArrayEquals(new String[] {"Attach_inner"}, mEvents.toArray()); } public void testOneLevelClippingInScrollView() throws Throwable { @@ -171,13 +142,13 @@ public class CatalystSubviewsClippingTestCase extends ReactAppInstrumentationTes waitForBridgeAndUIIdle(); // Only 3 first views should be attached at the beginning - Assert.assertArrayEquals(new String[]{"Attach_0", "Attach_1", "Attach_2"}, mEvents.toArray()); + Assert.assertArrayEquals(new String[] {"Attach_0", "Attach_1", "Attach_2"}, mEvents.toArray()); mEvents.clear(); // We scroll down such that first view get out of the bounds, we expect the first view to be // detached and 4th view to get attached scrollToDpInUIThread(120); - Assert.assertArrayEquals(new String[]{"Detach_0", "Attach_3"}, mEvents.toArray()); + Assert.assertArrayEquals(new String[] {"Detach_0", "Attach_3"}, mEvents.toArray()); } public void testTwoLevelClippingInScrollView() throws Throwable { @@ -197,38 +168,38 @@ public class CatalystSubviewsClippingTestCase extends ReactAppInstrumentationTes // Scroll a little bit so that "complex" view is visible, but it's inner views are not scrollToDpInUIThread(complexViewOffset + 5); - Assert.assertArrayEquals(new String[]{"Attach_C0"}, mEvents.toArray()); + Assert.assertArrayEquals(new String[] {"Attach_C0"}, mEvents.toArray()); mEvents.clear(); // Step 3 // Scroll even more so that first subview of "complex" view is visible, view 1 will get off // screen scrollToDpInUIThread(complexViewOffset + 100); - Assert.assertArrayEquals(new String[]{"Detach_1", "Attach_C0.1"}, mEvents.toArray()); + Assert.assertArrayEquals(new String[] {"Detach_1", "Attach_C0.1"}, mEvents.toArray()); mEvents.clear(); // Step 4 // Scroll even more to reveal second subview of "complex" view scrollToDpInUIThread(complexViewOffset + 150); - Assert.assertArrayEquals(new String[]{"Attach_C0.2"}, mEvents.toArray()); + Assert.assertArrayEquals(new String[] {"Attach_C0.2"}, mEvents.toArray()); mEvents.clear(); // Step 5 // Scroll back to previous position (Step 3), second view should get detached scrollToDpInUIThread(complexViewOffset + 100); - Assert.assertArrayEquals(new String[]{"Detach_C0.2"}, mEvents.toArray()); + Assert.assertArrayEquals(new String[] {"Detach_C0.2"}, mEvents.toArray()); mEvents.clear(); // Step 6 // Scroll back to Step 2, complex view should be visible but all subviews should be detached scrollToDpInUIThread(complexViewOffset + 5); - Assert.assertArrayEquals(new String[]{"Attach_1", "Detach_C0.1"}, mEvents.toArray()); + Assert.assertArrayEquals(new String[] {"Attach_1", "Detach_C0.1"}, mEvents.toArray()); mEvents.clear(); // Step 7 // Scroll back to Step 1, complex view should be gone scrollToDpInUIThread(complexViewOffset); - Assert.assertArrayEquals(new String[]{"Detach_C0"}, mEvents.toArray()); + Assert.assertArrayEquals(new String[] {"Detach_C0"}, mEvents.toArray()); } private void scrollToDpInUIThread(final int yPositionInDP) throws Throwable { diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/CatalystTouchBubblingTestCase.java b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/CatalystTouchBubblingTestCase.java index 7b9a7f8431d..60dc3de87c8 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/CatalystTouchBubblingTestCase.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/CatalystTouchBubblingTestCase.java @@ -1,51 +1,35 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.tests; import android.view.View; - -import com.facebook.react.testing.ReactInstanceSpecForTest; import com.facebook.react.testing.ReactAppInstrumentationTestCase; +import com.facebook.react.testing.ReactInstanceSpecForTest; import com.facebook.react.testing.SingleTouchGestureGenerator; import com.facebook.react.testing.StringRecordingModule; /** - * This test is to verify that touch events bubbles up to the right handler. We emulate couple - * of different gestures on top of the application reflecting following layout: + * This test is to verify that touch events bubbles up to the right handler. We emulate couple of + * different gestures on top of the application reflecting following layout: * - * +---------------------------------------------------------------------------------------+ - * | | - * | +----------------------------------------------------------------------------------+ | - * | | +-------------+ +----------------+ | | - * | | | +---+ | | | | | - * | | | | A | | | | | | - * | | | +---+ | | C | | | - * | | | {B} | | | | | - * | | | | {D} | | | | - * | | +-------------+ +----------------+ | | - * | | | | - * | | | | - * | +----------------------------------------------------------------------------------+ | - * | - * | +----------------------------------------------------------------------------------+ | - * | | | | - * | | | | - * | | | | - * | | {E} | | - * | | | | - * | | | | - * | +----------------------------------------------------------------------------------+ | + *

+---------------------------------------------------------------------------------------+ | | + * | +----------------------------------------------------------------------------------+ | | | + * +-------------+ +----------------+ | | | | | +---+ | | | | | | | | | A | | | | | | | | | +---+ | + * | C | | | | | | {B} | | | | | | | | | {D} | | | | | | +-------------+ +----------------+ | | | | + * | | | | | | | + * +----------------------------------------------------------------------------------+ | | | + * +----------------------------------------------------------------------------------+ | | | | | | + * | | | | | | | | | {E} | | | | | | | | | | | + * +----------------------------------------------------------------------------------+ | * +---------------------------------------------------------------------------------------+ * - * Then in each test case we either tap the center of a particular view (from A to E) or we start - * a gesture in one view and end it with another. - * View with names in brackets (e.g. {D}) have touch handlers set whereas all other views are not - * declared to handler touch events. + *

Then in each test case we either tap the center of a particular view (from A to E) or we start + * a gesture in one view and end it with another. View with names in brackets (e.g. {D}) have touch + * handlers set whereas all other views are not declared to handler touch events. */ public class CatalystTouchBubblingTestCase extends ReactAppInstrumentationTestCase { @@ -57,8 +41,8 @@ public class CatalystTouchBubblingTestCase extends ReactAppInstrumentationTestCa } /** - * 1) Simulate touch event at view A, expect {B} touch handler to fire - * 2) Simulate touch event at view C, expect {D} touch handler to fire + * 1) Simulate touch event at view A, expect {B} touch handler to fire 2) Simulate touch event at + * view C, expect {D} touch handler to fire */ public void testSimpleClickAtInnerElements() { mRecordingModule.reset(); @@ -80,8 +64,7 @@ public class CatalystTouchBubblingTestCase extends ReactAppInstrumentationTestCa /** * 1) Start touch at view A, then drag and release on view {B} (but outside of A), expect {B}'s - * touch handler to fire - * 2) Do the same with view C and {D} + * touch handler to fire 2) Do the same with view C and {D} */ public void testDownOnInnerUpOnTouchableParent() { View innerButton = getViewByTestId("A"); @@ -151,7 +134,6 @@ public class CatalystTouchBubblingTestCase extends ReactAppInstrumentationTestCa @Override protected ReactInstanceSpecForTest createReactInstanceSpecForTest() { - return new ReactInstanceSpecForTest() - .addNativeModule(mRecordingModule); + return new ReactInstanceSpecForTest().addNativeModule(mRecordingModule); } } diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/CatalystUIManagerTestCase.java b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/CatalystUIManagerTestCase.java index 1c98ec39d21..63424cdb6e6 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/CatalystUIManagerTestCase.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/CatalystUIManagerTestCase.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.tests; import android.util.DisplayMetrics; @@ -30,17 +29,21 @@ import com.facebook.react.views.view.ReactViewManager; import java.util.Arrays; import java.util.List; -/** - * Test case for basic {@link UIManagerModule} functionality. - */ +/** Test case for basic {@link UIManagerModule} functionality. */ public class CatalystUIManagerTestCase extends ReactIntegrationTestCase { private interface UIManagerTestModule extends JavaScriptModule { void renderFlexTestApplication(int rootTag); + void renderFlexWithTextApplication(int rootTag); + void renderAbsolutePositionTestApplication(int rootTag); + void renderAbsolutePositionBottomRightTestApplication(int rootTag); + void renderCenteredTextViewTestApplication(int rootTag, String text); + void renderUpdatePositionInListTestApplication(int rootTag); + void flushUpdatePositionInList(); } @@ -71,28 +74,28 @@ public class CatalystUIManagerTestCase extends ReactIntegrationTestCase { protected void setUp() throws Exception { super.setUp(); - List viewManagers = Arrays.asList( - new ReactViewManager(), - new ReactTextViewManager(), - new ReactRawTextManager()); - uiManager = - new UIManagerModule(getContext(), viewManagers, 0); - UiThreadUtil.runOnUiThread(new Runnable() { - @Override - public void run() { - uiManager.onHostResume(); - } - }); + List viewManagers = + Arrays.asList( + new ReactViewManager(), new ReactTextViewManager(), new ReactRawTextManager()); + uiManager = new UIManagerModule(getContext(), viewManagers, 0); + UiThreadUtil.runOnUiThread( + new Runnable() { + @Override + public void run() { + uiManager.onHostResume(); + } + }); waitForIdleSync(); - jsModule = ReactTestHelper.catalystInstanceBuilder(this) - .addNativeModule(uiManager) - .addNativeModule(new AndroidInfoModule(getContext())) - .addNativeModule(new DeviceInfoModule(getContext())) - .addNativeModule(new AppStateModule(getContext())) - .addNativeModule(new FakeWebSocketModule()) - .build() - .getJSModule(UIManagerTestModule.class); + jsModule = + ReactTestHelper.catalystInstanceBuilder(this) + .addNativeModule(uiManager) + .addNativeModule(new AndroidInfoModule(getContext())) + .addNativeModule(new DeviceInfoModule(getContext())) + .addNativeModule(new AppStateModule(getContext())) + .addNativeModule(new FakeWebSocketModule()) + .build() + .getJSModule(UIManagerTestModule.class); } public void testFlexUIRendered() { @@ -134,7 +137,8 @@ public class CatalystUIManagerTestCase extends ReactIntegrationTestCase { // assertEquals(inPixelRounded(300), row.getHeight()); // assertEquals(2, row.getChildCount()); // - // // Text measurement adds padding that isn't completely dependent on density so we can't easily + // // Text measurement adds padding that isn't completely dependent on density so we can't + // easily // // get an exact value here // float approximateExpectedTextHeight = inPixelRounded(19); // View leftText = row.getChildAt(0); @@ -240,10 +244,10 @@ public class CatalystUIManagerTestCase extends ReactIntegrationTestCase { } public void testCenteredTextCases() { - String[] cases = new String[] { - "test", - "with whitespace", - }; + String[] cases = + new String[] { + "test", "with whitespace", + }; for (String text : cases) { _testCenteredText(text); } diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/DatePickerDialogTestCase.java b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/DatePickerDialogTestCase.java index cb8d22f6e21..662c8cfb439 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/DatePickerDialogTestCase.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/DatePickerDialogTestCase.java @@ -1,34 +1,29 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.tests; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.List; - import android.app.DatePickerDialog; import android.content.DialogInterface; +import android.widget.DatePicker; import androidx.fragment.app.DialogFragment; import androidx.fragment.app.Fragment; -import android.widget.DatePicker; - import com.facebook.react.bridge.BaseJavaModule; -import com.facebook.react.testing.ReactInstanceSpecForTest; -import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.JavaScriptModule; +import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.WritableMap; import com.facebook.react.bridge.WritableNativeMap; import com.facebook.react.modules.datepicker.DatePickerDialogModule; import com.facebook.react.testing.ReactAppInstrumentationTestCase; +import com.facebook.react.testing.ReactInstanceSpecForTest; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.List; -/** - * Test case for {@link DatePickerDialogModule} options and callbacks. - */ +/** Test case for {@link DatePickerDialogModule} options and callbacks. */ public class DatePickerDialogTestCase extends ReactAppInstrumentationTestCase { private static interface DatePickerDialogTestModule extends JavaScriptModule { @@ -78,8 +73,7 @@ public class DatePickerDialogTestCase extends ReactAppInstrumentationTestCase { @Override protected ReactInstanceSpecForTest createReactInstanceSpecForTest() { - return super.createReactInstanceSpecForTest() - .addNativeModule(mRecordingModule); + return super.createReactInstanceSpecForTest().addNativeModule(mRecordingModule); } @Override @@ -105,8 +99,10 @@ public class DatePickerDialogTestCase extends ReactAppInstrumentationTestCase { waitForBridgeAndUIIdle(); getInstrumentation().waitForIdleSync(); - return (DialogFragment) getActivity().getSupportFragmentManager() - .findFragmentByTag(DatePickerDialogModule.FRAGMENT_TAG); + return (DialogFragment) + getActivity() + .getSupportFragmentManager() + .findFragmentByTag(DatePickerDialogModule.FRAGMENT_TAG); } public void testShowBasicDatePicker() { @@ -139,7 +135,8 @@ public class DatePickerDialogTestCase extends ReactAppInstrumentationTestCase { @Override public void run() { ((DatePickerDialog) datePickerFragment.getDialog()) - .getButton(DialogInterface.BUTTON_POSITIVE).performClick(); + .getButton(DialogInterface.BUTTON_POSITIVE) + .performClick(); } }); @@ -171,5 +168,4 @@ public class DatePickerDialogTestCase extends ReactAppInstrumentationTestCase { assertEquals(0, mRecordingModule.getDates().size()); assertEquals(1, mRecordingModule.getDismissed()); } - } diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/ImageErrorTestCase.java b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/ImageErrorTestCase.java index 3676a9cd202..f500599cd94 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/ImageErrorTestCase.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/ImageErrorTestCase.java @@ -1,20 +1,16 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.tests; -import android.view.View; import com.facebook.react.testing.ReactAppInstrumentationTestCase; import com.facebook.react.testing.ReactInstanceSpecForTest; import com.facebook.react.testing.StringRecordingModule; -/** - * Simple test case to check that onError does not get called with undefined - */ +/** Simple test case to check that onError does not get called with undefined */ public class ImageErrorTestCase extends ReactAppInstrumentationTestCase { private StringRecordingModule mStringRecordingModule; @@ -30,17 +26,21 @@ public class ImageErrorTestCase extends ReactAppInstrumentationTestCase { assertNotNull(getViewByTestId("image-3")); Thread.sleep(3000); - + assertEquals(3, mStringRecordingModule.getCalls().size()); - assertEquals("Got error: Unsupported uri scheme! Uri is: ", mStringRecordingModule.getCalls().get(0)); - assertEquals("Got error: /does/not/exist: open failed: ENOENT (No such file or directory)", mStringRecordingModule.getCalls().get(1)); - assertEquals("Got error: Unexpected HTTP code Response{protocol=http/1.1, code=404, message=Not Found, url=https://typo_error_facebook.github.io/react/logo-og.png}", mStringRecordingModule.getCalls().get(2)); + assertEquals( + "Got error: Unsupported uri scheme! Uri is: ", mStringRecordingModule.getCalls().get(0)); + assertEquals( + "Got error: /does/not/exist: open failed: ENOENT (No such file or directory)", + mStringRecordingModule.getCalls().get(1)); + assertEquals( + "Got error: Unexpected HTTP code Response{protocol=http/1.1, code=404, message=Not Found, url=https://typo_error_facebook.github.io/react/logo-og.png}", + mStringRecordingModule.getCalls().get(2)); } @Override protected ReactInstanceSpecForTest createReactInstanceSpecForTest() { mStringRecordingModule = new StringRecordingModule(); - return super.createReactInstanceSpecForTest() - .addNativeModule(mStringRecordingModule); + return super.createReactInstanceSpecForTest().addNativeModule(mStringRecordingModule); } } diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/ImageOverlayColorTestCase.java b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/ImageOverlayColorTestCase.java index 4dd334af88f..1dd531ad2ef 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/ImageOverlayColorTestCase.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/ImageOverlayColorTestCase.java @@ -1,18 +1,15 @@ /** * Copyright (c) 2014-present, Facebook, Inc. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.tests; import android.view.View; import com.facebook.react.testing.ReactAppInstrumentationTestCase; -/** - * Simple test case for passing overlayColor prop to the Image component - */ +/** Simple test case for passing overlayColor prop to the Image component */ public class ImageOverlayColorTestCase extends ReactAppInstrumentationTestCase { @Override diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/InitialPropsTestCase.java b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/InitialPropsTestCase.java index bf754df05df..6a7c84f35bd 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/InitialPropsTestCase.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/InitialPropsTestCase.java @@ -1,28 +1,23 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.tests; import android.os.Bundle; import android.test.ActivityInstrumentationTestCase2; - import com.facebook.react.bridge.BaseJavaModule; -import com.facebook.react.testing.FakeWebSocketModule; -import com.facebook.react.testing.ReactInstanceSpecForTest; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableMap; +import com.facebook.react.testing.FakeWebSocketModule; import com.facebook.react.testing.ReactAppTestActivity; +import com.facebook.react.testing.ReactInstanceSpecForTest; -/** - * Simple test case for passing initial props to the root React application. - */ -public class InitialPropsTestCase extends - ActivityInstrumentationTestCase2 { +/** Simple test case for passing initial props to the root React application. */ +public class InitialPropsTestCase extends ActivityInstrumentationTestCase2 { public static final String DEFAULT_JS_BUNDLE = "AndroidTestBundle.js"; @@ -78,17 +73,13 @@ public class InitialPropsTestCase extends props.putDouble("key3", 5.5); props.putFloat("key4", 5.6f); props.putBoolean("key5", true); - props.putStringArray("key6", new String[]{"one", "two", "three"}); - props.putIntArray("key7", new int[]{1, 2, 3}); - props.putDoubleArray("key8", new double[]{1.5, 2.5, 3.5}); - props.putFloatArray("key9", new float[]{1.6f, 2.6f, 3.6f}); - props.putBooleanArray("key10", new boolean[]{true, false}); + props.putStringArray("key6", new String[] {"one", "two", "three"}); + props.putIntArray("key7", new int[] {1, 2, 3}); + props.putDoubleArray("key8", new double[] {1.5, 2.5, 3.5}); + props.putFloatArray("key9", new float[] {1.6f, 2.6f, 3.6f}); + props.putBooleanArray("key10", new boolean[] {true, false}); activity.loadApp( - "InitialPropsTestApp", - catalystInstanceSpec, - props, - DEFAULT_JS_BUNDLE, - false); + "InitialPropsTestApp", catalystInstanceSpec, props, DEFAULT_JS_BUNDLE, false); } }); activity.waitForBridgeAndUIIdle(); diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/JSLocaleTest.java b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/JSLocaleTest.java index 3875ad878f8..96c22a70a59 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/JSLocaleTest.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/JSLocaleTest.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.tests; import com.facebook.react.bridge.CatalystInstance; @@ -23,13 +22,12 @@ import com.facebook.react.views.view.ReactViewManager; import java.util.Arrays; import java.util.List; -/** - * Test locale-based functionality of JS VM - */ +/** Test locale-based functionality of JS VM */ public class JSLocaleTest extends ReactIntegrationTestCase { private interface TestJSLocaleModule extends JavaScriptModule { void toUpper(String string); + void toLower(String string); } @@ -41,12 +39,8 @@ public class JSLocaleTest extends ReactIntegrationTestCase { protected void setUp() throws Exception { super.setUp(); - List viewManagers = Arrays.asList( - new ReactViewManager()); - final UIManagerModule mUIManager = new UIManagerModule( - getContext(), - viewManagers, - 0); + List viewManagers = Arrays.asList(new ReactViewManager()); + final UIManagerModule mUIManager = new UIManagerModule(getContext(), viewManagers, 0); UiThreadUtil.runOnUiThread( new Runnable() { @Override @@ -58,13 +52,14 @@ public class JSLocaleTest extends ReactIntegrationTestCase { waitForIdleSync(); mStringRecordingModule = new StringRecordingModule(); - mInstance = ReactTestHelper.catalystInstanceBuilder(this) - .addNativeModule(mStringRecordingModule) - .addNativeModule(mUIManager) - .addNativeModule(new DeviceInfoModule(getContext())) - .addNativeModule(new AppStateModule(getContext())) - .addNativeModule(new FakeWebSocketModule()) - .build(); + mInstance = + ReactTestHelper.catalystInstanceBuilder(this) + .addNativeModule(mStringRecordingModule) + .addNativeModule(mUIManager) + .addNativeModule(new DeviceInfoModule(getContext())) + .addNativeModule(new AppStateModule(getContext())) + .addNativeModule(new FakeWebSocketModule()) + .build(); } public void testToUpper() { diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/JSResponderTestCase.java b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/JSResponderTestCase.java index 077298065b0..62148cdb39a 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/JSResponderTestCase.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/JSResponderTestCase.java @@ -1,25 +1,23 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.tests; import android.widget.ScrollView; - -import com.facebook.react.uimanager.PixelUtil; import com.facebook.react.testing.ReactAppInstrumentationTestCase; import com.facebook.react.testing.SingleTouchGestureGenerator; +import com.facebook.react.uimanager.PixelUtil; /** * Test case to verify that JSResponder flow work correctly. * - * In a single test case scenario we have a view with pan gesture recognizer containing a scrollview - * We verify that by vertical drags affects a scrollview while horizontal drags are suppose to - * be recognized by pan responder and setJSResponder should be triggered resulting in scrollview - * events being intercepted. + *

In a single test case scenario we have a view with pan gesture recognizer containing a + * scrollview We verify that by vertical drags affects a scrollview while horizontal drags are + * suppose to be recognized by pan responder and setJSResponder should be triggered resulting in + * scrollview events being intercepted. */ public class JSResponderTestCase extends ReactAppInstrumentationTestCase { @@ -55,13 +53,9 @@ public class JSResponderTestCase extends ReactAppInstrumentationTestCase { waitForBridgeAndUIIdle(); - gestureGenerator - .dragTo(30 + inpx40dp, 30, 10, 1200) - .endGesture(); + gestureGenerator.dragTo(30 + inpx40dp, 30, 10, 1200).endGesture(); waitForBridgeAndUIIdle(); assertEquals("Expected not to scroll", scrollView.getScrollY(), previousScroll); - } - } diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/LayoutEventsTestCase.java b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/LayoutEventsTestCase.java index f9f7741d8c7..1f075eaca3d 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/LayoutEventsTestCase.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/LayoutEventsTestCase.java @@ -1,19 +1,16 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.tests; import com.facebook.react.testing.ReactAppInstrumentationTestCase; import com.facebook.react.testing.ReactInstanceSpecForTest; import com.facebook.react.testing.StringRecordingModule; -/** - * Simple test to verify that layout events (onLayout) propagate to JS from native. - */ +/** Simple test to verify that layout events (onLayout) propagate to JS from native. */ public class LayoutEventsTestCase extends ReactAppInstrumentationTestCase { private StringRecordingModule mStringRecordingModule; @@ -23,9 +20,7 @@ public class LayoutEventsTestCase extends ReactAppInstrumentationTestCase { return "LayoutEventsTestApp"; } - /** - * Creates a UI in JS and verifies the onLayout handler is called. - */ + /** Creates a UI in JS and verifies the onLayout handler is called. */ public void testOnLayoutCalled() { assertEquals(3, mStringRecordingModule.getCalls().size()); assertEquals("10,10-100x100", mStringRecordingModule.getCalls().get(0)); @@ -36,7 +31,6 @@ public class LayoutEventsTestCase extends ReactAppInstrumentationTestCase { @Override protected ReactInstanceSpecForTest createReactInstanceSpecForTest() { mStringRecordingModule = new StringRecordingModule(); - return super.createReactInstanceSpecForTest() - .addNativeModule(mStringRecordingModule); + return super.createReactInstanceSpecForTest().addNativeModule(mStringRecordingModule); } } diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/NativeIdTestCase.java b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/NativeIdTestCase.java index 0cfd4d6c277..ce5c89c7b9d 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/NativeIdTestCase.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/NativeIdTestCase.java @@ -1,23 +1,20 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.tests; +import android.view.View; +import com.facebook.react.testing.ReactAppInstrumentationTestCase; +import com.facebook.react.uimanager.util.ReactFindViewUtil; import java.util.Arrays; import java.util.List; -import android.view.View; - -import com.facebook.react.testing.ReactAppInstrumentationTestCase; -import com.facebook.react.uimanager.util.ReactFindViewUtil; - /** - * Tests that the 'nativeID' property can be set on various views. - * The 'nativeID' property is used to reference react managed views from native code. + * Tests that the 'nativeID' property can be set on various views. The 'nativeID' property is used + * to reference react managed views from native code. */ public class NativeIdTestCase extends ReactAppInstrumentationTestCase { @@ -26,43 +23,43 @@ public class NativeIdTestCase extends ReactAppInstrumentationTestCase { return "NativeIdTestApp"; } - private final List viewTags = Arrays.asList( - "Image", - "Text", - "TouchableBounce", - "TouchableHighlight", - "TouchableOpacity", - "TouchableWithoutFeedback", - "TextInput", - "View"); + private final List viewTags = + Arrays.asList( + "Image", + "Text", + "TouchableBounce", + "TouchableHighlight", + "TouchableOpacity", + "TouchableWithoutFeedback", + "TextInput", + "View"); private boolean mViewFound; @Override protected void setUp() throws Exception { mViewFound = false; - ReactFindViewUtil.addViewListener(new ReactFindViewUtil.OnViewFoundListener() { - @Override - public String getNativeId() { - return viewTags.get(0); - } + ReactFindViewUtil.addViewListener( + new ReactFindViewUtil.OnViewFoundListener() { + @Override + public String getNativeId() { + return viewTags.get(0); + } - @Override - public void onViewFound(View view) { - mViewFound = true; - } - }); + @Override + public void onViewFound(View view) { + mViewFound = true; + } + }); super.setUp(); } public void testPropertyIsSetForViews() { for (String nativeId : viewTags) { - View viewWithTag = ReactFindViewUtil.findView( - getActivity().getRootView(), - nativeId); + View viewWithTag = ReactFindViewUtil.findView(getActivity().getRootView(), nativeId); assertNotNull( - "View with nativeID " + nativeId + " was not found. Check NativeIdTestModule.js.", - viewWithTag); + "View with nativeID " + nativeId + " was not found. Check NativeIdTestModule.js.", + viewWithTag); } } @@ -73,20 +70,19 @@ public class NativeIdTestCase extends ReactAppInstrumentationTestCase { public void testFindView() { mViewFound = false; ReactFindViewUtil.findView( - getActivity().getRootView(), - new ReactFindViewUtil.OnViewFoundListener() { - @Override - public String getNativeId() { - return viewTags.get(0); - } + getActivity().getRootView(), + new ReactFindViewUtil.OnViewFoundListener() { + @Override + public String getNativeId() { + return viewTags.get(0); + } - @Override - public void onViewFound(View view) { - mViewFound = true; - } - }); + @Override + public void onViewFound(View view) { + mViewFound = true; + } + }); assertTrue( - "OnViewFound callback should have successfully been invoked synchronously", - mViewFound); + "OnViewFound callback should have successfully been invoked synchronously", mViewFound); } } diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/ProgressBarTestCase.java b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/ProgressBarTestCase.java index 19989b52426..a4804cd032a 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/ProgressBarTestCase.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/ProgressBarTestCase.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.tests; import android.content.res.Resources; @@ -32,9 +31,7 @@ import java.util.Arrays; import java.util.HashMap; import java.util.List; -/** - * Test to verify that Progress bar renders as a view of the right size - */ +/** Test to verify that Progress bar renders as a view of the right size */ public class ProgressBarTestCase extends ReactIntegrationTestCase { // Has same order of progressBars in ProgressBarTestModule @@ -49,7 +46,7 @@ public class ProgressBarTestCase extends ReactIntegrationTestCase { styles.put("Inverse", android.R.attr.progressBarStyleInverse); styles.put("SmallInverse", android.R.attr.progressBarStyleSmallInverse); styles.put("LargeInverse", android.R.attr.progressBarStyleLargeInverse); -} + } private static interface ProgressBarTestModule extends JavaScriptModule { public void renderProgressBarApplication(int rootTag); @@ -63,11 +60,9 @@ public class ProgressBarTestCase extends ReactIntegrationTestCase { protected void setUp() throws Exception { super.setUp(); - List viewManagers = Arrays.asList( - new ReactViewManager(), - new ReactProgressBarViewManager()); - mUIManager = - new UIManagerModule(getContext(), viewManagers, 0); + List viewManagers = + Arrays.asList(new ReactViewManager(), new ReactProgressBarViewManager()); + mUIManager = new UIManagerModule(getContext(), viewManagers, 0); UiThreadUtil.runOnUiThread( new Runnable() { @Override @@ -77,13 +72,14 @@ public class ProgressBarTestCase extends ReactIntegrationTestCase { }); waitForIdleSync(); - mInstance = ReactTestHelper.catalystInstanceBuilder(this) - .addNativeModule(mUIManager) - .addNativeModule(new AndroidInfoModule(getContext())) - .addNativeModule(new DeviceInfoModule(getContext())) - .addNativeModule(new AppStateModule(getContext())) - .addNativeModule(new FakeWebSocketModule()) - .build(); + mInstance = + ReactTestHelper.catalystInstanceBuilder(this) + .addNativeModule(mUIManager) + .addNativeModule(new AndroidInfoModule(getContext())) + .addNativeModule(new DeviceInfoModule(getContext())) + .addNativeModule(new AppStateModule(getContext())) + .addNativeModule(new FakeWebSocketModule()) + .build(); mRootView = new ReactRootView(getContext()); DisplayMetrics metrics = getContext().getResources().getDisplayMetrics(); @@ -94,16 +90,13 @@ public class ProgressBarTestCase extends ReactIntegrationTestCase { waitForBridgeAndUIIdle(); } - /** - * Test that the sizes of the progressBars are setup correctly - */ + /** Test that the sizes of the progressBars are setup correctly */ public void testProgressBarSizes() { for (String style : styleList) { - ProgressBar newProgressBar = - new ProgressBar(getContext(), null, styles.get(style)); - final int spec = View.MeasureSpec.makeMeasureSpec( - ViewGroup.LayoutParams.WRAP_CONTENT, - View.MeasureSpec.UNSPECIFIED); + ProgressBar newProgressBar = new ProgressBar(getContext(), null, styles.get(style)); + final int spec = + View.MeasureSpec.makeMeasureSpec( + ViewGroup.LayoutParams.WRAP_CONTENT, View.MeasureSpec.UNSPECIFIED); newProgressBar.measure(spec, spec); final int expectedHeight = newProgressBar.getMeasuredHeight(); diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/ReactHorizontalScrollViewTestCase.java b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/ReactHorizontalScrollViewTestCase.java index e1defbb208b..15a81bd5d23 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/ReactHorizontalScrollViewTestCase.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/ReactHorizontalScrollViewTestCase.java @@ -1,25 +1,19 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.tests; -import java.util.ArrayList; - import android.view.View; import android.widget.HorizontalScrollView; - import com.facebook.react.testing.AbstractScrollViewTestCase; import com.facebook.react.testing.SingleTouchGestureGenerator; import com.facebook.react.uimanager.PixelUtil; +import java.util.ArrayList; -/** - * Integration test for horizontal ScrollView. - * See ScrollViewTestModule.js - */ +/** Integration test for horizontal ScrollView. See ScrollViewTestModule.js */ public class ReactHorizontalScrollViewTestCase extends AbstractScrollViewTestCase { @Override @@ -61,8 +55,7 @@ public class ReactHorizontalScrollViewTestCase extends AbstractScrollViewTestCas assertFalse("Expected to receive at least one scroll event", xOffsets.isEmpty()); assertTrue("Expected offset to be greater than 0", xOffsets.get(xOffsets.size() - 1) > 0); assertTrue( - "Expected no item click event fired", - mScrollListenerModule.getItemsPressed().isEmpty()); + "Expected no item click event fired", mScrollListenerModule.getItemsPressed().isEmpty()); assertEquals( "Expected last offset to be offset of scroll view", PixelUtil.toDIPFromPixel(scrollView.getScrollX()), @@ -103,9 +96,7 @@ public class ReactHorizontalScrollViewTestCase extends AbstractScrollViewTestCas assertEquals(visibleItemNumber, (int) itemIds.get(0)); } - /** - * Verify that 'scrollTo' command makes ScrollView start scrolling - */ + /** Verify that 'scrollTo' command makes ScrollView start scrolling */ public void testScrollToCommand() throws Exception { HorizontalScrollView scrollView = getViewAtPath(0); ScrollViewTestModule jsModule = diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/ReactPickerTestCase.java b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/ReactPickerTestCase.java index ec8fd977a0a..24bf069a0bd 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/ReactPickerTestCase.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/ReactPickerTestCase.java @@ -1,29 +1,26 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.tests; -import java.util.ArrayList; -import java.util.List; - import android.graphics.Color; import android.widget.Spinner; import android.widget.SpinnerAdapter; import android.widget.TextView; - import com.facebook.react.bridge.BaseJavaModule; -import com.facebook.react.testing.ReactInstanceSpecForTest; -import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.JavaScriptModule; +import com.facebook.react.bridge.ReactMethod; +import com.facebook.react.testing.ReactAppInstrumentationTestCase; +import com.facebook.react.testing.ReactInstanceSpecForTest; import com.facebook.react.views.picker.ReactDialogPickerManager; import com.facebook.react.views.picker.ReactDropdownPickerManager; import com.facebook.react.views.picker.ReactPicker; import com.facebook.react.views.picker.ReactPickerManager; -import com.facebook.react.testing.ReactAppInstrumentationTestCase; +import java.util.ArrayList; +import java.util.List; /** * Integration test for {@link ReactDialogPickerManager} and {@link ReactDropdownPickerManager} @@ -34,7 +31,9 @@ public class ReactPickerTestCase extends ReactAppInstrumentationTestCase { private static interface PickerAndroidTestModule extends JavaScriptModule { public void selectItem(int position); + public void setMode(String mode); + public void setPrimaryColor(String color); } @@ -66,8 +65,7 @@ public class ReactPickerTestCase extends ReactAppInstrumentationTestCase { @Override protected ReactInstanceSpecForTest createReactInstanceSpecForTest() { mRecordingModule = new PickerAndroidRecordingModule(); - return super.createReactInstanceSpecForTest() - .addNativeModule(mRecordingModule); + return super.createReactInstanceSpecForTest().addNativeModule(mRecordingModule); } public void testBasicProperties() { @@ -88,29 +86,22 @@ public class ReactPickerTestCase extends ReactAppInstrumentationTestCase { assertEquals(Color.GREEN, ((TextView) adapter.getView(1, null, null)).getCurrentTextColor()); assertEquals(Color.BLUE, ((TextView) adapter.getView(2, null, null)).getCurrentTextColor()); assertEquals( - Color.RED, - ((TextView) adapter.getDropDownView(0, null, null)).getCurrentTextColor()); + Color.RED, ((TextView) adapter.getDropDownView(0, null, null)).getCurrentTextColor()); assertEquals( - Color.GREEN, - ((TextView) adapter.getDropDownView(1, null, null)).getCurrentTextColor()); + Color.GREEN, ((TextView) adapter.getDropDownView(1, null, null)).getCurrentTextColor()); assertEquals( - Color.BLUE, - ((TextView) adapter.getDropDownView(2, null, null)).getCurrentTextColor()); + Color.BLUE, ((TextView) adapter.getDropDownView(2, null, null)).getCurrentTextColor()); getTestModule().setPrimaryColor("black"); waitForBridgeAndUIIdle(); assertEquals(Color.BLACK, ((TextView) adapter.getView(0, null, null)).getCurrentTextColor()); assertEquals(Color.BLACK, ((TextView) adapter.getView(1, null, null)).getCurrentTextColor()); assertEquals(Color.BLACK, ((TextView) adapter.getView(2, null, null)).getCurrentTextColor()); assertEquals( - Color.RED, - ((TextView) adapter.getDropDownView(0, null, null)).getCurrentTextColor()); + Color.RED, ((TextView) adapter.getDropDownView(0, null, null)).getCurrentTextColor()); assertEquals( - Color.GREEN, - ((TextView) adapter.getDropDownView(1, null, null)).getCurrentTextColor()); + Color.GREEN, ((TextView) adapter.getDropDownView(1, null, null)).getCurrentTextColor()); assertEquals( - Color.BLUE, - ((TextView) adapter.getDropDownView(2, null, null)).getCurrentTextColor()); - + Color.BLUE, ((TextView) adapter.getDropDownView(2, null, null)).getCurrentTextColor()); } public void testDropdownPicker() { @@ -176,9 +167,8 @@ public class ReactPickerTestCase extends ReactAppInstrumentationTestCase { updateFirstSpinnerAndCheckLastSpinnerMatches(2); } - private void updateFirstSpinnerAndCheckLastSpinnerMatches( - final int indexToSelect - ) throws Throwable { + private void updateFirstSpinnerAndCheckLastSpinnerMatches(final int indexToSelect) + throws Throwable { // The last spinner has the same selected value as the first one. // Test that user selection is propagated correctly to JS, to setState, and to Spinners. runTestOnUiThread( @@ -194,13 +184,12 @@ public class ReactPickerTestCase extends ReactAppInstrumentationTestCase { ReactPicker spinnerInSync = getViewAtPath(0, 3); assertEquals( - "Picker selection was not updated correctly via setState.", - indexToSelect, - spinnerInSync.getSelectedItemPosition()); + "Picker selection was not updated correctly via setState.", + indexToSelect, + spinnerInSync.getSelectedItemPosition()); } private PickerAndroidTestModule getTestModule() { return getReactContext().getCatalystInstance().getJSModule(PickerAndroidTestModule.class); } - } diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/ReactScrollViewTestCase.java b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/ReactScrollViewTestCase.java index 0267bb8e28b..434d98cb97b 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/ReactScrollViewTestCase.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/ReactScrollViewTestCase.java @@ -1,25 +1,19 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.tests; -import java.util.ArrayList; - import android.view.View; import android.widget.ScrollView; - import com.facebook.react.testing.AbstractScrollViewTestCase; import com.facebook.react.testing.SingleTouchGestureGenerator; import com.facebook.react.uimanager.PixelUtil; +import java.util.ArrayList; -/** - * Integration test for vertical ScrollView. - * See ScrollViewTestModule.js - */ +/** Integration test for vertical ScrollView. See ScrollViewTestModule.js */ public class ReactScrollViewTestCase extends AbstractScrollViewTestCase { @Override @@ -61,8 +55,7 @@ public class ReactScrollViewTestCase extends AbstractScrollViewTestCase { assertFalse("Expected to receive at least one scroll event", yOffsets.isEmpty()); assertTrue("Expected offset to be greater than 0", yOffsets.get(yOffsets.size() - 1) > 0); assertTrue( - "Expected no item click event fired", - mScrollListenerModule.getItemsPressed().isEmpty()); + "Expected no item click event fired", mScrollListenerModule.getItemsPressed().isEmpty()); assertEquals( "Expected last offset to be offset of scroll view", PixelUtil.toDIPFromPixel(scrollView.getScrollY()), @@ -104,9 +97,7 @@ public class ReactScrollViewTestCase extends AbstractScrollViewTestCase { assertEquals(visibleItemNumber, (int) itemIds.get(0)); } - /** - * Verify that 'scrollTo' command makes ScrollView start scrolling - */ + /** Verify that 'scrollTo' command makes ScrollView start scrolling */ public void testScrollToCommand() throws Exception { ScrollView scrollView = getViewAtPath(0); ScrollViewTestModule jsModule = diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/ReactSwipeRefreshLayoutTestCase.java b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/ReactSwipeRefreshLayoutTestCase.java index a75b217131f..a4054cf88fb 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/ReactSwipeRefreshLayoutTestCase.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/ReactSwipeRefreshLayoutTestCase.java @@ -1,24 +1,20 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.tests; import android.view.View; - -import com.facebook.react.testing.ReactAppInstrumentationTestCase; -import com.facebook.react.testing.ReactInstanceSpecForTest; import com.facebook.react.bridge.BaseJavaModule; import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.bridge.ReactMethod; +import com.facebook.react.testing.ReactAppInstrumentationTestCase; +import com.facebook.react.testing.ReactInstanceSpecForTest; import com.facebook.react.views.swiperefresh.ReactSwipeRefreshLayout; -/** - * Test case for {@link ReactSwipeRefreshLayout}. - */ +/** Test case for {@link ReactSwipeRefreshLayout}. */ public class ReactSwipeRefreshLayoutTestCase extends ReactAppInstrumentationTestCase { private class SwipeRefreshLayoutRecordingModule extends BaseJavaModule { @@ -53,8 +49,7 @@ public class ReactSwipeRefreshLayoutTestCase extends ReactAppInstrumentationTest @Override protected ReactInstanceSpecForTest createReactInstanceSpecForTest() { - return super.createReactInstanceSpecForTest() - .addNativeModule(mRecordingModule); + return super.createReactInstanceSpecForTest().addNativeModule(mRecordingModule); } public void testRefreshNoScroll() { @@ -98,5 +93,4 @@ public class ReactSwipeRefreshLayoutTestCase extends ReactAppInstrumentationTest waitForBridgeAndUIIdle(); assertEquals(0, mRecordingModule.getCount()); } - } diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/ShareTestCase.java b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/ShareTestCase.java index 83d382d112c..356d84186a1 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/ShareTestCase.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/ShareTestCase.java @@ -1,36 +1,24 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.tests; -import java.util.ArrayList; -import java.util.List; - -import android.app.Activity; -import android.app.AlertDialog; import android.app.Instrumentation.ActivityMonitor; -import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; -import android.content.IntentFilter.MalformedMimeTypeException; -import androidx.fragment.app.DialogFragment; - import com.facebook.react.bridge.BaseJavaModule; -import com.facebook.react.testing.ReactInstanceSpecForTest; -import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.JavaScriptModule; +import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.WritableMap; import com.facebook.react.bridge.WritableNativeMap; import com.facebook.react.modules.share.ShareModule; import com.facebook.react.testing.ReactAppInstrumentationTestCase; +import com.facebook.react.testing.ReactInstanceSpecForTest; -/** - * Test case for {@link ShareModule}. - */ +/** Test case for {@link ShareModule}. */ public class ShareTestCase extends ReactAppInstrumentationTestCase { private static interface ShareTestModule extends JavaScriptModule { @@ -64,15 +52,13 @@ public class ShareTestCase extends ReactAppInstrumentationTestCase { public int getErrors() { return mErrors; } - } final ShareRecordingModule mRecordingModule = new ShareRecordingModule(); @Override protected ReactInstanceSpecForTest createReactInstanceSpecForTest() { - return super.createReactInstanceSpecForTest() - .addNativeModule(mRecordingModule); + return super.createReactInstanceSpecForTest().addNativeModule(mRecordingModule); } @Override @@ -101,7 +87,5 @@ public class ShareTestCase extends ReactAppInstrumentationTestCase { assertEquals(1, monitor.getHits()); assertEquals(1, mRecordingModule.getOpened()); assertEquals(0, mRecordingModule.getErrors()); - } - } diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/TestIdTestCase.java b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/TestIdTestCase.java index 47696a68460..54eedf9ddeb 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/TestIdTestCase.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/TestIdTestCase.java @@ -1,25 +1,20 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.tests; +import android.view.View; +import com.facebook.react.testing.ReactAppInstrumentationTestCase; +import com.facebook.react.testing.ReactTestHelper; import java.util.Arrays; import java.util.List; -import android.view.View; - -import com.facebook.react.views.picker.ReactDropdownPickerManager; -import com.facebook.react.testing.ReactAppInstrumentationTestCase; -import com.facebook.react.testing.ReactInstanceSpecForTest; -import com.facebook.react.testing.ReactTestHelper; - /** - * Tests that the 'testID' property can be set on various views. - * The 'testID' property is used to locate views in UI tests. + * Tests that the 'testID' property can be set on various views. The 'testID' property is used to + * locate views in UI tests. */ public class TestIdTestCase extends ReactAppInstrumentationTestCase { @@ -28,22 +23,20 @@ public class TestIdTestCase extends ReactAppInstrumentationTestCase { return "TestIdTestApp"; } - private final List viewTags = Arrays.asList( - "Image", - "Text", - "TouchableBounce", - "TouchableHighlight", - "TouchableOpacity", - "TouchableWithoutFeedback", - "TextInput", - "View" - ); + private final List viewTags = + Arrays.asList( + "Image", + "Text", + "TouchableBounce", + "TouchableHighlight", + "TouchableOpacity", + "TouchableWithoutFeedback", + "TextInput", + "View"); public void testPropertyIsSetForViews() { for (String tag : viewTags) { - View viewWithTag = ReactTestHelper.getViewWithReactTestId( - getActivity().getRootView(), - tag); + View viewWithTag = ReactTestHelper.getViewWithReactTestId(getActivity().getRootView(), tag); assertNotNull( "View with testID tag " + tag + " was not found. Check TestIdTestModule.js.", viewWithTag); diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/TextInputTestCase.java b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/TextInputTestCase.java index ffc9c9e8ce2..40ac1f59d1d 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/TextInputTestCase.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/TextInputTestCase.java @@ -1,21 +1,18 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.tests; import android.graphics.Color; import android.text.style.ForegroundColorSpan; import android.util.TypedValue; -import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.widget.EditText; - import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.testing.ReactAppInstrumentationTestCase; import com.facebook.react.testing.ReactInstanceSpecForTest; @@ -23,9 +20,7 @@ import com.facebook.react.testing.StringRecordingModule; import com.facebook.react.uimanager.PixelUtil; import com.facebook.react.views.textinput.ReactEditText; -/** - * Test to verify that TextInput renders correctly - */ +/** Test to verify that TextInput renders correctly */ public class TextInputTestCase extends ReactAppInstrumentationTestCase { private final StringRecordingModule mRecordingModule = new StringRecordingModule(); @@ -47,20 +42,17 @@ public class TextInputTestCase extends ReactAppInstrumentationTestCase { EditText editText = new EditText(textInputViewNoHeight.getContext()); editText.setTextSize( - TypedValue.COMPLEX_UNIT_PX, - (float) Math.ceil(PixelUtil.toPixelFromSP(21.f))); + TypedValue.COMPLEX_UNIT_PX, (float) Math.ceil(PixelUtil.toPixelFromSP(21.f))); editText.setPadding(0, 0, 0, 0); - int measureSpec = View.MeasureSpec.makeMeasureSpec( - ViewGroup.LayoutParams.WRAP_CONTENT, - View.MeasureSpec.UNSPECIFIED); + int measureSpec = + View.MeasureSpec.makeMeasureSpec( + ViewGroup.LayoutParams.WRAP_CONTENT, View.MeasureSpec.UNSPECIFIED); editText.measure(measureSpec, measureSpec); assertEquals(editText.getMeasuredHeight(), textInputViewNoHeight.getHeight()); } - /** - * Test that the cursor moves to the end of the word. - */ + /** Test that the cursor moves to the end of the word. */ public void testTextInputCursorPosition() throws Throwable { final EditText textInputWithText = getViewByTestId("textInput3"); @@ -71,7 +63,8 @@ public class TextInputTestCase extends ReactAppInstrumentationTestCase { textInputWithText.setSelection(3); } }); - getReactContext().getJSModule(TextInputTestModule.class) + getReactContext() + .getJSModule(TextInputTestModule.class) .setValueRef("textInput3", "Some other value"); waitForBridgeAndUIIdle(); @@ -79,9 +72,7 @@ public class TextInputTestCase extends ReactAppInstrumentationTestCase { assertEquals(4, textInputWithText.getSelectionEnd()); } - /** - * Test that the colors are applied to new text - */ + /** Test that the colors are applied to new text */ public void testTextInputColors() throws Throwable { String testIDs[] = new String[] {"textInput4", "textInput5", "textInput6"}; @@ -94,7 +85,9 @@ public class TextInputTestCase extends ReactAppInstrumentationTestCase { ReactEditText reactEditText = getViewByTestId(testID); assertEquals( Color.GREEN, - reactEditText.getText().getSpans(0, 1, ForegroundColorSpan.class)[0] + reactEditText + .getText() + .getSpans(0, 1, ForegroundColorSpan.class)[0] .getForegroundColor()); } } @@ -113,26 +106,26 @@ public class TextInputTestCase extends ReactAppInstrumentationTestCase { fireEditorActionAndCheckRecording(reactEditText, EditorInfo.IME_ACTION_NONE); } - private void fireEditorActionAndCheckRecording(final ReactEditText reactEditText, - final int actionId) throws Throwable { + private void fireEditorActionAndCheckRecording( + final ReactEditText reactEditText, final int actionId) throws Throwable { fireEditorActionAndCheckRecording(reactEditText, actionId, true); fireEditorActionAndCheckRecording(reactEditText, actionId, false); } - private void fireEditorActionAndCheckRecording(final ReactEditText reactEditText, - final int actionId, - final boolean blurOnSubmit) throws Throwable { + private void fireEditorActionAndCheckRecording( + final ReactEditText reactEditText, final int actionId, final boolean blurOnSubmit) + throws Throwable { mRecordingModule.reset(); runTestOnUiThread( - new Runnable() { - @Override - public void run() { - reactEditText.requestFocusFromJS(); - reactEditText.setBlurOnSubmit(blurOnSubmit); - reactEditText.onEditorAction(actionId); - } - }); + new Runnable() { + @Override + public void run() { + reactEditText.requestFocusFromJS(); + reactEditText.setBlurOnSubmit(blurOnSubmit); + reactEditText.onEditorAction(actionId); + } + }); waitForBridgeAndUIIdle(); assertEquals(1, mRecordingModule.getCalls().size()); @@ -140,114 +133,68 @@ public class TextInputTestCase extends ReactAppInstrumentationTestCase { } /** - * Test that the mentions input has colors displayed correctly. - * Removed for being flaky in open source, December 2016 - public void testMetionsInputColors() throws Throwable { - EventDispatcher eventDispatcher = - getReactContext().getNativeModule(UIManagerModule.class).getEventDispatcher(); - ReactEditText reactEditText = getViewByTestId("tokenizedInput"); - String newText = "#Things and more #things"; - int contentWidth = reactEditText.getWidth(); - int contentHeight = reactEditText.getHeight(); - int start = 0; - int count = newText.length(); - - eventDispatcher.dispatchEvent( - new ReactTextChangedEvent( - reactEditText.getId(), - newText.toString(), - (int) PixelUtil.toDIPFromPixel(contentWidth), - (int) PixelUtil.toDIPFromPixel(contentHeight), - reactEditText.incrementAndGetEventCounter())); - - eventDispatcher.dispatchEvent( - new ReactTextInputEvent( - reactEditText.getId(), - newText.toString(), - "", - start, - start + count - 1)); - waitForBridgeAndUIIdle(); - - ForegroundColorSpan[] spans = reactEditText - .getText().getSpans(0, reactEditText.getText().length(), ForegroundColorSpan.class); - assertEquals(2, spans.length); - assertEquals(spans[0].getForegroundColor(), spans[1].getForegroundColor()); - assertEquals(0, reactEditText.getText().getSpanStart(spans[1])); - assertEquals(7, reactEditText.getText().getSpanEnd(spans[1])); - assertEquals(newText.length() - 7, reactEditText.getText().getSpanStart(spans[0])); - assertEquals(newText.length(), reactEditText.getText().getSpanEnd(spans[0])); - - String moreText = "andsuch "; - String previousText = newText; - newText += moreText; - count = moreText.length(); - start = previousText.length(); - - eventDispatcher.dispatchEvent( - new ReactTextChangedEvent( - reactEditText.getId(), - newText.toString(), - (int) PixelUtil.toDIPFromPixel(contentWidth), - (int) PixelUtil.toDIPFromPixel(contentHeight), - reactEditText.incrementAndGetEventCounter())); - - eventDispatcher.dispatchEvent( - new ReactTextInputEvent( - reactEditText.getId(), - moreText, - "", - start, - start + count - 1)); - waitForBridgeAndUIIdle(); - - spans = reactEditText.getText() - .getSpans(0, reactEditText.getText().length(), ForegroundColorSpan.class); - assertEquals(2, spans.length); - assertEquals(spans[0].getForegroundColor(), spans[1].getForegroundColor()); - assertEquals(0, reactEditText.getText().getSpanStart(spans[1])); - assertEquals(7, reactEditText.getText().getSpanEnd(spans[1])); - assertEquals(newText.length() - 15, reactEditText.getText().getSpanStart(spans[0])); - assertEquals(newText.length() - 1, reactEditText.getText().getSpanEnd(spans[0])); - - moreText = "morethings"; - previousText = newText; - newText += moreText; - count = moreText.length(); - start = previousText.length(); - - eventDispatcher.dispatchEvent( - new ReactTextChangedEvent( - reactEditText.getId(), - newText.toString(), - (int) PixelUtil.toDIPFromPixel(contentWidth), - (int) PixelUtil.toDIPFromPixel(contentHeight), - reactEditText.incrementAndGetEventCounter())); - - eventDispatcher.dispatchEvent( - new ReactTextInputEvent( - reactEditText.getId(), - moreText, - "", - start, - start + count - 1)); - waitForBridgeAndUIIdle(); - - spans = reactEditText.getText() - .getSpans(0, reactEditText.getText().length(), ForegroundColorSpan.class); - assertEquals(spans[0].getForegroundColor(), spans[1].getForegroundColor()); - assertEquals(2, spans.length); - assertEquals(0, reactEditText.getText().getSpanStart(spans[1])); - assertEquals(7, reactEditText.getText().getSpanEnd(spans[1])); - assertEquals(newText.length() - 25, reactEditText.getText().getSpanStart(spans[0])); - assertEquals(newText.length() - 11, reactEditText.getText().getSpanEnd(spans[0])); - } - */ - + * Test that the mentions input has colors displayed correctly. Removed for being flaky in open + * source, December 2016 public void testMetionsInputColors() throws Throwable { EventDispatcher + * eventDispatcher = + * getReactContext().getNativeModule(UIManagerModule.class).getEventDispatcher(); ReactEditText + * reactEditText = getViewByTestId("tokenizedInput"); String newText = "#Things and more #things"; + * int contentWidth = reactEditText.getWidth(); int contentHeight = reactEditText.getHeight(); int + * start = 0; int count = newText.length(); + * + *

eventDispatcher.dispatchEvent( new ReactTextChangedEvent( reactEditText.getId(), + * newText.toString(), (int) PixelUtil.toDIPFromPixel(contentWidth), (int) + * PixelUtil.toDIPFromPixel(contentHeight), reactEditText.incrementAndGetEventCounter())); + * + *

eventDispatcher.dispatchEvent( new ReactTextInputEvent( reactEditText.getId(), + * newText.toString(), "", start, start + count - 1)); waitForBridgeAndUIIdle(); + * + *

ForegroundColorSpan[] spans = reactEditText .getText().getSpans(0, + * reactEditText.getText().length(), ForegroundColorSpan.class); assertEquals(2, spans.length); + * assertEquals(spans[0].getForegroundColor(), spans[1].getForegroundColor()); assertEquals(0, + * reactEditText.getText().getSpanStart(spans[1])); assertEquals(7, + * reactEditText.getText().getSpanEnd(spans[1])); assertEquals(newText.length() - 7, + * reactEditText.getText().getSpanStart(spans[0])); assertEquals(newText.length(), + * reactEditText.getText().getSpanEnd(spans[0])); + * + *

String moreText = "andsuch "; String previousText = newText; newText += moreText; count = + * moreText.length(); start = previousText.length(); + * + *

eventDispatcher.dispatchEvent( new ReactTextChangedEvent( reactEditText.getId(), + * newText.toString(), (int) PixelUtil.toDIPFromPixel(contentWidth), (int) + * PixelUtil.toDIPFromPixel(contentHeight), reactEditText.incrementAndGetEventCounter())); + * + *

eventDispatcher.dispatchEvent( new ReactTextInputEvent( reactEditText.getId(), moreText, "", + * start, start + count - 1)); waitForBridgeAndUIIdle(); + * + *

spans = reactEditText.getText() .getSpans(0, reactEditText.getText().length(), + * ForegroundColorSpan.class); assertEquals(2, spans.length); + * assertEquals(spans[0].getForegroundColor(), spans[1].getForegroundColor()); assertEquals(0, + * reactEditText.getText().getSpanStart(spans[1])); assertEquals(7, + * reactEditText.getText().getSpanEnd(spans[1])); assertEquals(newText.length() - 15, + * reactEditText.getText().getSpanStart(spans[0])); assertEquals(newText.length() - 1, + * reactEditText.getText().getSpanEnd(spans[0])); + * + *

moreText = "morethings"; previousText = newText; newText += moreText; count = + * moreText.length(); start = previousText.length(); + * + *

eventDispatcher.dispatchEvent( new ReactTextChangedEvent( reactEditText.getId(), + * newText.toString(), (int) PixelUtil.toDIPFromPixel(contentWidth), (int) + * PixelUtil.toDIPFromPixel(contentHeight), reactEditText.incrementAndGetEventCounter())); + * + *

eventDispatcher.dispatchEvent( new ReactTextInputEvent( reactEditText.getId(), moreText, "", + * start, start + count - 1)); waitForBridgeAndUIIdle(); + * + *

spans = reactEditText.getText() .getSpans(0, reactEditText.getText().length(), + * ForegroundColorSpan.class); assertEquals(spans[0].getForegroundColor(), + * spans[1].getForegroundColor()); assertEquals(2, spans.length); assertEquals(0, + * reactEditText.getText().getSpanStart(spans[1])); assertEquals(7, + * reactEditText.getText().getSpanEnd(spans[1])); assertEquals(newText.length() - 25, + * reactEditText.getText().getSpanStart(spans[0])); assertEquals(newText.length() - 11, + * reactEditText.getText().getSpanEnd(spans[0])); } + */ @Override protected ReactInstanceSpecForTest createReactInstanceSpecForTest() { - return super.createReactInstanceSpecForTest() - .addNativeModule(mRecordingModule); + return super.createReactInstanceSpecForTest().addNativeModule(mRecordingModule); } @Override diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/TimePickerDialogTestCase.java b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/TimePickerDialogTestCase.java index a899098dbd6..e88eb555d75 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/TimePickerDialogTestCase.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/TimePickerDialogTestCase.java @@ -1,31 +1,26 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.tests; -import java.util.ArrayList; -import java.util.List; - import android.app.TimePickerDialog; import android.content.DialogInterface; import androidx.fragment.app.DialogFragment; - import com.facebook.react.bridge.BaseJavaModule; -import com.facebook.react.testing.ReactInstanceSpecForTest; -import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.JavaScriptModule; +import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.WritableMap; import com.facebook.react.bridge.WritableNativeMap; import com.facebook.react.modules.timepicker.TimePickerDialogModule; import com.facebook.react.testing.ReactAppInstrumentationTestCase; +import com.facebook.react.testing.ReactInstanceSpecForTest; +import java.util.ArrayList; +import java.util.List; -/** - * Test case for {@link TimePickerDialogModule} options and callbacks. - */ +/** Test case for {@link TimePickerDialogModule} options and callbacks. */ public class TimePickerDialogTestCase extends ReactAppInstrumentationTestCase { private static interface TimePickerDialogTestModule extends JavaScriptModule { @@ -75,8 +70,7 @@ public class TimePickerDialogTestCase extends ReactAppInstrumentationTestCase { @Override protected ReactInstanceSpecForTest createReactInstanceSpecForTest() { - return super.createReactInstanceSpecForTest() - .addNativeModule(mRecordingModule); + return super.createReactInstanceSpecForTest().addNativeModule(mRecordingModule); } @Override @@ -94,8 +88,10 @@ public class TimePickerDialogTestCase extends ReactAppInstrumentationTestCase { waitForBridgeAndUIIdle(); getInstrumentation().waitForIdleSync(); - return (DialogFragment) getActivity().getSupportFragmentManager() - .findFragmentByTag(TimePickerDialogModule.FRAGMENT_TAG); + return (DialogFragment) + getActivity() + .getSupportFragmentManager() + .findFragmentByTag(TimePickerDialogModule.FRAGMENT_TAG); } public void testShowBasicTimePicker() { @@ -119,7 +115,8 @@ public class TimePickerDialogTestCase extends ReactAppInstrumentationTestCase { @Override public void run() { ((TimePickerDialog) fragment.getDialog()) - .getButton(DialogInterface.BUTTON_POSITIVE).performClick(); + .getButton(DialogInterface.BUTTON_POSITIVE) + .performClick(); } }); @@ -155,5 +152,4 @@ public class TimePickerDialogTestCase extends ReactAppInstrumentationTestCase { assertEquals(0, mRecordingModule.getTimes().size()); assertEquals(1, mRecordingModule.getDismissed()); } - } diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/ViewRenderingTestCase.java b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/ViewRenderingTestCase.java index edccc5e89f9..d9b36924147 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/ViewRenderingTestCase.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/ViewRenderingTestCase.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.tests; import android.graphics.Color; @@ -32,9 +31,13 @@ public class ViewRenderingTestCase extends ReactIntegrationTestCase { private interface ViewRenderingTestModule extends JavaScriptModule { void renderViewApplication(int rootTag); + void renderMarginApplication(int rootTag); + void renderBorderApplication(int rootTag); + void updateMargins(); + void renderTransformApplication(int rootTag); } @@ -47,8 +50,7 @@ public class ViewRenderingTestCase extends ReactIntegrationTestCase { super.setUp(); List viewManagers = Arrays.asList(new ReactViewManager()); - final UIManagerModule uiManager = - new UIManagerModule(getContext(), viewManagers, 0); + final UIManagerModule uiManager = new UIManagerModule(getContext(), viewManagers, 0); UiThreadUtil.runOnUiThread( new Runnable() { @Override @@ -58,13 +60,14 @@ public class ViewRenderingTestCase extends ReactIntegrationTestCase { }); waitForIdleSync(); - mCatalystInstance = ReactTestHelper.catalystInstanceBuilder(this) - .addNativeModule(uiManager) - .addNativeModule(new AndroidInfoModule(getContext())) - .addNativeModule(new DeviceInfoModule(getContext())) - .addNativeModule(new AppStateModule(getContext())) - .addNativeModule(new FakeWebSocketModule()) - .build(); + mCatalystInstance = + ReactTestHelper.catalystInstanceBuilder(this) + .addNativeModule(uiManager) + .addNativeModule(new AndroidInfoModule(getContext())) + .addNativeModule(new DeviceInfoModule(getContext())) + .addNativeModule(new AppStateModule(getContext())) + .addNativeModule(new FakeWebSocketModule()) + .build(); mRootView = new ReactRootView(getContext()); mRootTag = uiManager.addRootView(mRootView); @@ -131,7 +134,8 @@ public class ViewRenderingTestCase extends ReactIntegrationTestCase { } public void testTransformations() { - mCatalystInstance.getJSModule(ViewRenderingTestModule.class) + mCatalystInstance + .getJSModule(ViewRenderingTestModule.class) .renderTransformApplication(mRootTag); waitForBridgeAndUIIdle(); diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/core/ReactInstanceManagerTest.java b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/core/ReactInstanceManagerTest.java index afb2540ddcb..e5877c3802b 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/core/ReactInstanceManagerTest.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/core/ReactInstanceManagerTest.java @@ -36,26 +36,28 @@ public class ReactInstanceManagerTest { Activity activity = mActivityRule.getActivity(); mReactRootView = new ReactRootView(activity); mReactInstanceManager = - ReactTestHelper.getReactTestFactory() - .getReactInstanceManagerBuilder() - .setApplication(activity.getApplication()) - .setBundleAssetName("AndroidTestBundle.js") - .setInitialLifecycleState(LifecycleState.BEFORE_CREATE) - .addPackage(new MainReactPackage()) - .build(); + ReactTestHelper.getReactTestFactory() + .getReactInstanceManagerBuilder() + .setApplication(activity.getApplication()) + .setBundleAssetName("AndroidTestBundle.js") + .setInitialLifecycleState(LifecycleState.BEFORE_CREATE) + .addPackage(new MainReactPackage()) + .build(); } @After public void tearDown() { final ReactRootView reactRootView = mReactRootView; final ReactInstanceManager reactInstanceManager = mReactInstanceManager; - InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() { - @Override - public void run() { - reactRootView.unmountReactApplication(); - reactInstanceManager.destroy(); - } - }); + InstrumentationRegistry.getInstrumentation() + .runOnMainSync( + new Runnable() { + @Override + public void run() { + reactRootView.unmountReactApplication(); + reactInstanceManager.destroy(); + } + }); } @Test diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/core/ReactRootViewTest.java b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/core/ReactRootViewTest.java index 6f6d1495385..e7f9f96ce57 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/core/ReactRootViewTest.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/core/ReactRootViewTest.java @@ -8,34 +8,29 @@ package com.facebook.react.tests.core; import static org.fest.assertions.api.Assertions.assertThat; import android.app.Instrumentation; -import androidx.test.InstrumentationRegistry; -import androidx.test.runner.AndroidJUnit4; -import android.util.DisplayMetrics; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; +import androidx.test.InstrumentationRegistry; +import androidx.test.runner.AndroidJUnit4; import com.facebook.react.ReactPackage; import com.facebook.react.ReactRootView; import com.facebook.react.bridge.JavaScriptModule; -import com.facebook.react.bridge.ModuleSpec; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; +import com.facebook.react.module.annotations.ReactModule; +import com.facebook.react.module.model.ReactModuleInfo; +import com.facebook.react.module.model.ReactModuleInfoProvider; import com.facebook.react.shell.MainReactPackage; import com.facebook.react.testing.StringRecordingModule; import com.facebook.react.testing.rule.ReactNativeTestRule; import com.facebook.react.uimanager.PixelUtil; -import java.util.ArrayList; -import java.util.List; import java.util.HashMap; import java.util.Map; -import javax.inject.Provider; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; -import com.facebook.react.module.model.ReactModuleInfo; -import com.facebook.react.module.model.ReactModuleInfoProvider; -import com.facebook.react.module.annotations.ReactModule; @RunWith(AndroidJUnit4.class) public class ReactRootViewTest { @@ -45,55 +40,56 @@ public class ReactRootViewTest { } final StringRecordingModule mRecordingModule = new StringRecordingModule(); - final ReactPackage mReactPackage = new MainReactPackage() { - @Override - public NativeModule getModule(String name, ReactApplicationContext context) { - if (name.equals(StringRecordingModule.NAME)) { - return mRecordingModule; - } - - return super.getModule(name, context); - } - - @Override - public ReactModuleInfoProvider getReactModuleInfoProvider() { - final ReactModuleInfoProvider provider = super.getReactModuleInfoProvider(); - - return new ReactModuleInfoProvider() { - private Map mModuleInfos = null; - + final ReactPackage mReactPackage = + new MainReactPackage() { @Override - public Map getReactModuleInfos() { - if (mModuleInfos != null) { - return mModuleInfos; + public NativeModule getModule(String name, ReactApplicationContext context) { + if (name.equals(StringRecordingModule.NAME)) { + return mRecordingModule; } - mModuleInfos = new HashMap<>(); - mModuleInfos.putAll(provider.getReactModuleInfos()); + return super.getModule(name, context); + } - Class moduleClass = StringRecordingModule.class; - ReactModule reactModule = moduleClass.getAnnotation(ReactModule.class); + @Override + public ReactModuleInfoProvider getReactModuleInfoProvider() { + final ReactModuleInfoProvider provider = super.getReactModuleInfoProvider(); - mModuleInfos.put( - reactModule.name(), - new ReactModuleInfo( - reactModule.name(), - moduleClass.getName(), - reactModule.canOverrideExistingModule(), - reactModule.needsEagerInit(), - reactModule.hasConstants(), - reactModule.isCxxModule(), - false)); + return new ReactModuleInfoProvider() { + private Map mModuleInfos = null; - return mModuleInfos; + @Override + public Map getReactModuleInfos() { + if (mModuleInfos != null) { + return mModuleInfos; + } + + mModuleInfos = new HashMap<>(); + mModuleInfos.putAll(provider.getReactModuleInfos()); + + Class moduleClass = StringRecordingModule.class; + ReactModule reactModule = moduleClass.getAnnotation(ReactModule.class); + + mModuleInfos.put( + reactModule.name(), + new ReactModuleInfo( + reactModule.name(), + moduleClass.getName(), + reactModule.canOverrideExistingModule(), + reactModule.needsEagerInit(), + reactModule.hasConstants(), + reactModule.isCxxModule(), + false)); + + return mModuleInfos; + } + }; } }; - } - }; @Rule public ReactNativeTestRule mReactNativeRule = - new ReactNativeTestRule("AndroidTestBundle.js", mReactPackage); + new ReactNativeTestRule("AndroidTestBundle.js", mReactPackage); @Before public void setup() { @@ -111,14 +107,13 @@ public class ReactRootViewTest { Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation(); instrumentation.runOnMainSync( - new Runnable() { - @Override - public void run() { - rootView.setLayoutParams(new FrameLayout.LayoutParams( - newWidth, - ViewGroup.LayoutParams.MATCH_PARENT)); - } - }); + new Runnable() { + @Override + public void run() { + rootView.setLayoutParams( + new FrameLayout.LayoutParams(newWidth, ViewGroup.LayoutParams.MATCH_PARENT)); + } + }); instrumentation.waitForIdleSync(); mReactNativeRule.waitForIdleSync(); @@ -132,24 +127,23 @@ public class ReactRootViewTest { Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation(); instrumentation.runOnMainSync( - new Runnable() { - @Override - public void run() { - rootView.setLayoutParams( - new FrameLayout.LayoutParams( - ViewGroup.LayoutParams.WRAP_CONTENT, - ViewGroup.LayoutParams.WRAP_CONTENT)); - } - }); + new Runnable() { + @Override + public void run() { + rootView.setLayoutParams( + new FrameLayout.LayoutParams( + ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); + } + }); instrumentation.waitForIdleSync(); mReactNativeRule.waitForIdleSync(); int newComponentHeight = 500; mReactNativeRule - .getContext() - .getJSModule(ReactRootViewTestModule.class) - .setHeight(newComponentHeight); + .getContext() + .getJSModule(ReactRootViewTestModule.class) + .setHeight(newComponentHeight); instrumentation.waitForIdleSync(); mReactNativeRule.waitForIdleSync(); @@ -157,7 +151,7 @@ public class ReactRootViewTest { // added 0.5 to account for rounding issues assertThat(rootView.getMeasuredHeight()) - .isEqualTo((int) (PixelUtil.toPixelFromDIP(newComponentHeight) + 0.5)); + .isEqualTo((int) (PixelUtil.toPixelFromDIP(newComponentHeight) + 0.5)); } /** @@ -172,32 +166,32 @@ public class ReactRootViewTest { Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation(); instrumentation.runOnMainSync( - new Runnable() { - @Override - public void run() { - ViewGroup parent = (ViewGroup) rootView.getParent(); - parent.removeView(rootView); - // removing from parent should not remove child views, child views should be removed as - // an effect of native call to UIManager.removeRootView - assertThat(rootView.getChildCount()).isEqualTo(1); - } - }); + new Runnable() { + @Override + public void run() { + ViewGroup parent = (ViewGroup) rootView.getParent(); + parent.removeView(rootView); + // removing from parent should not remove child views, child views should be removed as + // an effect of native call to UIManager.removeRootView + assertThat(rootView.getChildCount()).isEqualTo(1); + } + }); instrumentation.waitForIdleSync(); mReactNativeRule.waitForIdleSync(); assertThat(mRecordingModule.getCalls().size()) - .isEqualTo(0) - .overridingErrorMessage("root component should not be automatically unmounted"); + .isEqualTo(0) + .overridingErrorMessage("root component should not be automatically unmounted"); assertThat(rootView.getChildCount()).isEqualTo(1); instrumentation.runOnMainSync( - new Runnable() { - @Override - public void run() { - rootView.unmountReactApplication(); - } - }); + new Runnable() { + @Override + public void run() { + rootView.unmountReactApplication(); + } + }); mReactNativeRule.waitForIdleSync(); assertThat(mRecordingModule.getCalls().size()).isEqualTo(1); diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/core/WritableNativeMapTest.java b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/core/WritableNativeMapTest.java index e709799f66e..dcd39b8ef67 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/tests/core/WritableNativeMapTest.java +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/tests/core/WritableNativeMapTest.java @@ -5,13 +5,11 @@ import static org.fest.assertions.api.Assertions.assertThat; import androidx.test.runner.AndroidJUnit4; import com.facebook.react.bridge.NoSuchKeyException; import com.facebook.react.bridge.UnexpectedNativeTypeException; -import com.facebook.react.bridge.WritableArray; import com.facebook.react.bridge.WritableMap; import com.facebook.react.bridge.WritableNativeArray; import com.facebook.react.bridge.WritableNativeMap; import org.junit.Assert; import org.junit.Before; -import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/ReactAndroid/src/main/java/com/facebook/debug/holder/Printer.java b/ReactAndroid/src/main/java/com/facebook/debug/holder/Printer.java index 8b7ffadbd9c..3a01ac9bc59 100644 --- a/ReactAndroid/src/main/java/com/facebook/debug/holder/Printer.java +++ b/ReactAndroid/src/main/java/com/facebook/debug/holder/Printer.java @@ -11,6 +11,8 @@ import com.facebook.debug.debugoverlay.model.DebugOverlayTag; public interface Printer { void logMessage(final DebugOverlayTag tag, final String message, Object... args); + void logMessage(final DebugOverlayTag tag, final String message); + boolean shouldDisplayLogMessage(final DebugOverlayTag tag); } diff --git a/ReactAndroid/src/main/java/com/facebook/debug/tags/ReactDebugOverlayTags.java b/ReactAndroid/src/main/java/com/facebook/debug/tags/ReactDebugOverlayTags.java index 877aa14c9c9..6de54e3c6b5 100644 --- a/ReactAndroid/src/main/java/com/facebook/debug/tags/ReactDebugOverlayTags.java +++ b/ReactAndroid/src/main/java/com/facebook/debug/tags/ReactDebugOverlayTags.java @@ -28,15 +28,9 @@ public class ReactDebugOverlayTags { "UI Manager View Operations (requires restart\nwarning: this is spammy)", Color.CYAN); public static final DebugOverlayTag FABRIC_UI_MANAGER = - new DebugOverlayTag( - "FabricUIManager", - "Fabric UI Manager View Operations", - Color.CYAN); + new DebugOverlayTag("FabricUIManager", "Fabric UI Manager View Operations", Color.CYAN); public static final DebugOverlayTag FABRIC_RECONCILER = - new DebugOverlayTag( - "FabricReconciler", - "Reconciler for Fabric", - Color.CYAN); + new DebugOverlayTag("FabricReconciler", "Reconciler for Fabric", Color.CYAN); public static final DebugOverlayTag RELAY = new DebugOverlayTag("Relay", "including prefetching", Color.rgb(0xFF, 0x99, 0x00)); } diff --git a/ReactAndroid/src/main/java/com/facebook/jni/Countable.java b/ReactAndroid/src/main/java/com/facebook/jni/Countable.java index ba3216e0f08..b3a1184c6e0 100644 --- a/ReactAndroid/src/main/java/com/facebook/jni/Countable.java +++ b/ReactAndroid/src/main/java/com/facebook/jni/Countable.java @@ -11,11 +11,11 @@ import com.facebook.soloader.SoLoader; /** * A Java Object that has native memory allocated corresponding to this instance. * - * NB: THREAD SAFETY (this comment also exists at Countable.cpp) + *

NB: THREAD SAFETY (this comment also exists at Countable.cpp) * - * {@link #dispose} deletes the corresponding native object on whatever thread the method is called - * on. In the common case when this is called by Countable#finalize(), this will be called on the - * system finalizer thread. If you manually call dispose on the Java object, the native object + *

{@link #dispose} deletes the corresponding native object on whatever thread the method is + * called on. In the common case when this is called by Countable#finalize(), this will be called on + * the system finalizer thread. If you manually call dispose on the Java object, the native object * will be deleted synchronously on that thread. */ @DoNotStrip @@ -26,8 +26,7 @@ public class Countable { } // Private C++ instance - @DoNotStrip - private long mInstance = 0; + @DoNotStrip private long mInstance = 0; public native void dispose(); diff --git a/ReactAndroid/src/main/java/com/facebook/jni/CpuCapabilitiesJni.java b/ReactAndroid/src/main/java/com/facebook/jni/CpuCapabilitiesJni.java index d0df3db702b..c4c3e84cef9 100644 --- a/ReactAndroid/src/main/java/com/facebook/jni/CpuCapabilitiesJni.java +++ b/ReactAndroid/src/main/java/com/facebook/jni/CpuCapabilitiesJni.java @@ -8,9 +8,7 @@ package com.facebook.jni; import com.facebook.proguard.annotations.DoNotStrip; import com.facebook.soloader.SoLoader; -/** - * Utility class to determine CPU capabilities - */ +/** Utility class to determine CPU capabilities */ @DoNotStrip public class CpuCapabilitiesJni { @@ -26,5 +24,4 @@ public class CpuCapabilitiesJni { @DoNotStrip public static native boolean nativeDeviceSupportsX86(); - } diff --git a/ReactAndroid/src/main/java/com/facebook/jni/DestructorThread.java b/ReactAndroid/src/main/java/com/facebook/jni/DestructorThread.java index 38bc2e7d848..7acc8f4c28d 100644 --- a/ReactAndroid/src/main/java/com/facebook/jni/DestructorThread.java +++ b/ReactAndroid/src/main/java/com/facebook/jni/DestructorThread.java @@ -12,12 +12,12 @@ import java.util.concurrent.atomic.AtomicReference; /** * A thread which invokes the "destruct" routine for objects after they have been garbage collected. * - * An object which needs to be destructed should create a static subclass of {@link Destructor}. - * Once the referent object is garbage collected, the DestructorThread will callback to the - * {@link Destructor#destruct()} method. + *

An object which needs to be destructed should create a static subclass of {@link Destructor}. + * Once the referent object is garbage collected, the DestructorThread will callback to the {@link + * Destructor#destruct()} method. * - * The underlying thread in DestructorThread starts when the first Destructor is constructed - * and then runs indefinitely. + *

The underlying thread in DestructorThread starts when the first Destructor is constructed and + * then runs indefinitely. */ public class DestructorThread { @@ -48,6 +48,7 @@ public class DestructorThread { private static DestructorList sDestructorList; /** A thread safe stack where new Destructors are placed before being add to sDestructorList. */ private static DestructorStack sDestructorStack; + private static ReferenceQueue sReferenceQueue; private static Thread sThread; @@ -55,27 +56,28 @@ public class DestructorThread { sDestructorStack = new DestructorStack(); sReferenceQueue = new ReferenceQueue(); sDestructorList = new DestructorList(); - sThread = new Thread("HybridData DestructorThread") { - @Override - public void run() { - while (true) { - try { - Destructor current = (Destructor) sReferenceQueue.remove(); - current.destruct(); + sThread = + new Thread("HybridData DestructorThread") { + @Override + public void run() { + while (true) { + try { + Destructor current = (Destructor) sReferenceQueue.remove(); + current.destruct(); - // If current is in the sDestructorStack, - // transfer all the Destructors in the stack to the list. - if (current.previous == null) { - sDestructorStack.transferAllToList(); + // If current is in the sDestructorStack, + // transfer all the Destructors in the stack to the list. + if (current.previous == null) { + sDestructorStack.transferAllToList(); + } + + DestructorList.drop(current); + } catch (InterruptedException e) { + // Continue. This thread should never be terminated. + } } - - DestructorList.drop(current); - } catch (InterruptedException e) { - // Continue. This thread should never be terminated. } - } - } - }; + }; sThread.start(); } diff --git a/ReactAndroid/src/main/java/com/facebook/jni/HybridClassBase.java b/ReactAndroid/src/main/java/com/facebook/jni/HybridClassBase.java index 540c1ca5e05..c27b5c14456 100644 --- a/ReactAndroid/src/main/java/com/facebook/jni/HybridClassBase.java +++ b/ReactAndroid/src/main/java/com/facebook/jni/HybridClassBase.java @@ -4,8 +4,8 @@ // LICENSE file in the root directory of this source tree. package com.facebook.jni; + import com.facebook.proguard.annotations.DoNotStrip; @DoNotStrip -public abstract class HybridClassBase extends HybridData { -} +public abstract class HybridClassBase extends HybridData {} diff --git a/ReactAndroid/src/main/java/com/facebook/jni/HybridData.java b/ReactAndroid/src/main/java/com/facebook/jni/HybridData.java index 47a331e24c1..158182df3ab 100644 --- a/ReactAndroid/src/main/java/com/facebook/jni/HybridData.java +++ b/ReactAndroid/src/main/java/com/facebook/jni/HybridData.java @@ -5,19 +5,16 @@ package com.facebook.jni; -import android.util.Log; - import com.facebook.proguard.annotations.DoNotStrip; import com.facebook.soloader.SoLoader; /** * This object holds a native C++ member for hybrid Java/C++ objects. * - * NB: THREAD SAFETY + *

NB: THREAD SAFETY * - * {@link #resetNative} deletes the corresponding native object synchronously on whatever thread - * the method is called on. Otherwise, deletion will occur on the {@link DestructorThread} - * thread. + *

{@link #resetNative} deletes the corresponding native object synchronously on whatever thread + * the method is called on. Otherwise, deletion will occur on the {@link DestructorThread} thread. */ @DoNotStrip public class HybridData { @@ -26,26 +23,24 @@ public class HybridData { SoLoader.loadLibrary("fb"); } - @DoNotStrip - private Destructor mDestructor = new Destructor(this); + @DoNotStrip private Destructor mDestructor = new Destructor(this); /** - * To explicitly delete the instance, call resetNative(). If the C++ - * instance is referenced after this is called, a NullPointerException will - * be thrown. resetNative() may be called multiple times safely. Because - * the {@link DestructorThread} also calls resetNative, the instance will not leak if this is - * not called, but timing of deletion and the thread the C++ dtor is called - * on will be at the whim of the Java GC. If you want to control the thread - * and timing of the destructor, you should call resetNative() explicitly. + * To explicitly delete the instance, call resetNative(). If the C++ instance is referenced after + * this is called, a NullPointerException will be thrown. resetNative() may be called multiple + * times safely. Because the {@link DestructorThread} also calls resetNative, the instance will + * not leak if this is not called, but timing of deletion and the thread the C++ dtor is called on + * will be at the whim of the Java GC. If you want to control the thread and timing of the + * destructor, you should call resetNative() explicitly. */ public synchronized void resetNative() { mDestructor.destruct(); } /** - * N.B. Thread safety. - * If you call isValid from a different thread than {@link #resetNative()} then be sure to - * do so while synchronizing on the hybrid. For example: + * N.B. Thread safety. If you call isValid from a different thread than {@link #resetNative()} + * then be sure to do so while synchronizing on the hybrid. For example: + * *


    * synchronized(hybrid) {
    *   if (hybrid.isValid) {
@@ -61,8 +56,7 @@ public class HybridData {
   public static class Destructor extends DestructorThread.Destructor {
 
     // Private C++ instance
-    @DoNotStrip
-    private long mNativePointer;
+    @DoNotStrip private long mNativePointer;
 
     Destructor(Object referent) {
       super(referent);
diff --git a/ReactAndroid/src/main/java/com/facebook/jni/IteratorHelper.java b/ReactAndroid/src/main/java/com/facebook/jni/IteratorHelper.java
index 88e2de6353d..26e00aed135 100644
--- a/ReactAndroid/src/main/java/com/facebook/jni/IteratorHelper.java
+++ b/ReactAndroid/src/main/java/com/facebook/jni/IteratorHelper.java
@@ -1,31 +1,26 @@
 /**
  * Copyright (c) Facebook, Inc. and its affiliates.
  *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
+ * 

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.jni; import com.facebook.proguard.annotations.DoNotStrip; - +import java.util.Iterator; import javax.annotation.Nullable; -import java.util.Iterator; - /** - * To iterate over an Iterator from C++ requires two calls per entry: hasNext() - * and next(). This helper reduces it to one call and one field get per entry. - * It does not use a generic argument, since in C++, the types will be erased, - * anyway. This is *not* a {@link java.util.Iterator}. + * To iterate over an Iterator from C++ requires two calls per entry: hasNext() and next(). This + * helper reduces it to one call and one field get per entry. It does not use a generic argument, + * since in C++, the types will be erased, anyway. This is *not* a {@link java.util.Iterator}. */ @DoNotStrip public class IteratorHelper { private final Iterator mIterator; // This is private, but accessed via JNI. - @DoNotStrip - private @Nullable Object mElement; + @DoNotStrip private @Nullable Object mElement; @DoNotStrip public IteratorHelper(Iterator iterator) { @@ -38,8 +33,8 @@ public class IteratorHelper { } /** - * Moves the helper to the next entry in the map, if any. Returns true iff - * there is an entry to read. + * Moves the helper to the next entry in the map, if any. Returns true iff there is an entry to + * read. */ @DoNotStrip boolean hasNext() { diff --git a/ReactAndroid/src/main/java/com/facebook/jni/MapIteratorHelper.java b/ReactAndroid/src/main/java/com/facebook/jni/MapIteratorHelper.java index e57cb9f1733..49749292ca3 100644 --- a/ReactAndroid/src/main/java/com/facebook/jni/MapIteratorHelper.java +++ b/ReactAndroid/src/main/java/com/facebook/jni/MapIteratorHelper.java @@ -1,24 +1,21 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.jni; -import javax.annotation.Nullable; - +import com.facebook.proguard.annotations.DoNotStrip; import java.util.Iterator; import java.util.Map; - -import com.facebook.proguard.annotations.DoNotStrip; +import javax.annotation.Nullable; /** - * To iterate over a Map from C++ requires four calls per entry: hasNext(), - * next(), getKey(), getValue(). This helper reduces it to one call and two - * field gets per entry. It does not use a generic argument, since in C++, the - * types will be erased, anyway. This is *not* a {@link java.util.Iterator}. + * To iterate over a Map from C++ requires four calls per entry: hasNext(), next(), getKey(), + * getValue(). This helper reduces it to one call and two field gets per entry. It does not use a + * generic argument, since in C++, the types will be erased, anyway. This is *not* a {@link + * java.util.Iterator}. */ @DoNotStrip public class MapIteratorHelper { @@ -32,8 +29,8 @@ public class MapIteratorHelper { } /** - * Moves the helper to the next entry in the map, if any. Returns true iff - * there is an entry to read. + * Moves the helper to the next entry in the map, if any. Returns true iff there is an entry to + * read. */ @DoNotStrip boolean hasNext() { diff --git a/ReactAndroid/src/main/java/com/facebook/jni/NativeRunnable.java b/ReactAndroid/src/main/java/com/facebook/jni/NativeRunnable.java index 10a2517a223..290de68d91f 100644 --- a/ReactAndroid/src/main/java/com/facebook/jni/NativeRunnable.java +++ b/ReactAndroid/src/main/java/com/facebook/jni/NativeRunnable.java @@ -1,18 +1,14 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.jni; -import com.facebook.jni.HybridData; import com.facebook.proguard.annotations.DoNotStrip; -/** - * A Runnable that has a native run implementation. - */ +/** A Runnable that has a native run implementation. */ @DoNotStrip public class NativeRunnable implements Runnable { diff --git a/ReactAndroid/src/main/java/com/facebook/perftest/PerfTestConfig.java b/ReactAndroid/src/main/java/com/facebook/perftest/PerfTestConfig.java index 7420ab0dce9..8b71fc67449 100644 --- a/ReactAndroid/src/main/java/com/facebook/perftest/PerfTestConfig.java +++ b/ReactAndroid/src/main/java/com/facebook/perftest/PerfTestConfig.java @@ -1,19 +1,15 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.perftest; -/** - * PerfTestConfig stub. - */ +/** PerfTestConfig stub. */ public class PerfTestConfig { public boolean isRunningInPerfTest() { return false; } - } diff --git a/ReactAndroid/src/main/java/com/facebook/proguard/annotations/DoNotStrip.java b/ReactAndroid/src/main/java/com/facebook/proguard/annotations/DoNotStrip.java index e73cd266897..0af1b790f13 100644 --- a/ReactAndroid/src/main/java/com/facebook/proguard/annotations/DoNotStrip.java +++ b/ReactAndroid/src/main/java/com/facebook/proguard/annotations/DoNotStrip.java @@ -1,24 +1,22 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.proguard.annotations; +import static java.lang.annotation.RetentionPolicy.CLASS; + import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.Target; -import static java.lang.annotation.RetentionPolicy.CLASS; - /** * Add this annotation to a class, method, or field to instruct Proguard to not strip it out. * - * This is useful for methods called via reflection that could appear as unused to Proguard. + *

This is useful for methods called via reflection that could appear as unused to Proguard. */ -@Target({ ElementType.TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.CONSTRUCTOR }) +@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.CONSTRUCTOR}) @Retention(CLASS) -public @interface DoNotStrip { -} +public @interface DoNotStrip {} diff --git a/ReactAndroid/src/main/java/com/facebook/proguard/annotations/KeepGettersAndSetters.java b/ReactAndroid/src/main/java/com/facebook/proguard/annotations/KeepGettersAndSetters.java index 127dd91ba6c..59b75f000cb 100644 --- a/ReactAndroid/src/main/java/com/facebook/proguard/annotations/KeepGettersAndSetters.java +++ b/ReactAndroid/src/main/java/com/facebook/proguard/annotations/KeepGettersAndSetters.java @@ -1,28 +1,26 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.proguard.annotations; +import static java.lang.annotation.RetentionPolicy.CLASS; + import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.Target; -import static java.lang.annotation.RetentionPolicy.CLASS; - /** * Add this annotation to a class, to keep all "void set*(***)" and get* methods. * - *

This is useful for classes that are controlled by animator-like classes that control - * various properties with reflection. + *

This is useful for classes that are controlled by animator-like classes that control various + * properties with reflection. * - *

NOTE: This is not needed for Views because their getters and setters - * are automatically kept by the default Android SDK ProGuard config. + *

NOTE: This is not needed for Views because their getters and setters are + * automatically kept by the default Android SDK ProGuard config. */ @Target({ElementType.TYPE}) @Retention(CLASS) -public @interface KeepGettersAndSetters { -} +public @interface KeepGettersAndSetters {} diff --git a/ReactAndroid/src/main/java/com/facebook/react/CompositeReactPackage.java b/ReactAndroid/src/main/java/com/facebook/react/CompositeReactPackage.java index 9450719098e..f033aed7e82 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/CompositeReactPackage.java +++ b/ReactAndroid/src/main/java/com/facebook/react/CompositeReactPackage.java @@ -20,7 +20,6 @@ import java.util.ListIterator; import java.util.Map; import java.util.Set; import javax.annotation.Nullable; -import com.facebook.react.TurboReactPackage; /** * {@code CompositeReactPackage} allows to create a single package composed of views and modules @@ -50,14 +49,14 @@ public class CompositeReactPackage implements ViewManagerOnDemandReactPackage, R final Map moduleMap = new HashMap<>(); for (ReactPackage reactPackage : mChildReactPackages) { /** - * For now, we eagerly initialize the NativeModules inside TurboReactPackages. - * Ultimately, we should turn CompositeReactPackage into a TurboReactPackage - * and remove this eager initialization. + * For now, we eagerly initialize the NativeModules inside TurboReactPackages. Ultimately, we + * should turn CompositeReactPackage into a TurboReactPackage and remove this eager + * initialization. * - * TODO: T45627020 + *

TODO: T45627020 */ if (reactPackage instanceof TurboReactPackage) { - TurboReactPackage turboReactPackage = (TurboReactPackage)reactPackage; + TurboReactPackage turboReactPackage = (TurboReactPackage) reactPackage; ReactModuleInfoProvider moduleInfoProvider = turboReactPackage.getReactModuleInfoProvider(); Map moduleInfos = moduleInfoProvider.getReactModuleInfos(); diff --git a/ReactAndroid/src/main/java/com/facebook/react/CoreModulesPackage.java b/ReactAndroid/src/main/java/com/facebook/react/CoreModulesPackage.java index 074269c2d0e..dfe3132b035 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/CoreModulesPackage.java +++ b/ReactAndroid/src/main/java/com/facebook/react/CoreModulesPackage.java @@ -6,6 +6,7 @@ */ package com.facebook.react; +import static com.facebook.react.bridge.ReactMarkerConstants.*; import static com.facebook.react.bridge.ReactMarkerConstants.CREATE_UI_MANAGER_MODULE_END; import static com.facebook.react.bridge.ReactMarkerConstants.CREATE_UI_MANAGER_MODULE_START; import static com.facebook.react.bridge.ReactMarkerConstants.PROCESS_CORE_REACT_PACKAGE_END; @@ -18,11 +19,11 @@ import com.facebook.react.module.annotations.ReactModule; import com.facebook.react.module.annotations.ReactModuleList; import com.facebook.react.module.model.ReactModuleInfo; import com.facebook.react.module.model.ReactModuleInfoProvider; +import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler; import com.facebook.react.modules.core.DeviceEventManagerModule; import com.facebook.react.modules.core.ExceptionsManagerModule; -import com.facebook.react.modules.core.Timing; -import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler; import com.facebook.react.modules.core.HeadlessJsTaskSupportModule; +import com.facebook.react.modules.core.Timing; import com.facebook.react.modules.debug.DevSettingsModule; import com.facebook.react.modules.debug.SourceCodeModule; import com.facebook.react.modules.deviceinfo.DeviceInfoModule; @@ -31,14 +32,10 @@ import com.facebook.react.uimanager.UIImplementationProvider; import com.facebook.react.uimanager.UIManagerModule; import com.facebook.react.uimanager.ViewManager; import com.facebook.systrace.Systrace; - -import java.util.Collections; -import javax.annotation.Nullable; import java.util.HashMap; import java.util.List; import java.util.Map; - -import static com.facebook.react.bridge.ReactMarkerConstants.*; +import javax.annotation.Nullable; /** * This is the basic module to support React Native. The debug modules are now in DebugCorePackage. diff --git a/ReactAndroid/src/main/java/com/facebook/react/DebugCorePackage.java b/ReactAndroid/src/main/java/com/facebook/react/DebugCorePackage.java index e40b61a93c6..93c347fe93f 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/DebugCorePackage.java +++ b/ReactAndroid/src/main/java/com/facebook/react/DebugCorePackage.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react; import com.facebook.react.bridge.ModuleSpec; @@ -24,15 +23,13 @@ import javax.inject.Provider; * view managers from). */ @ReactModuleList( - nativeModules = { - JSCHeapCapture.class, - JSDevSupport.class, - } -) + nativeModules = { + JSCHeapCapture.class, + JSDevSupport.class, + }) /* package */ class DebugCorePackage extends LazyReactPackage { - DebugCorePackage() { - } + DebugCorePackage() {} @Override public List getNativeModules(final ReactApplicationContext reactContext) { diff --git a/ReactAndroid/src/main/java/com/facebook/react/EagerModuleProvider.java b/ReactAndroid/src/main/java/com/facebook/react/EagerModuleProvider.java index 6af684d33b5..e8e456186f2 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/EagerModuleProvider.java +++ b/ReactAndroid/src/main/java/com/facebook/react/EagerModuleProvider.java @@ -5,13 +5,10 @@ package com.facebook.react; +import com.facebook.react.bridge.NativeModule; import javax.inject.Provider; -import com.facebook.react.bridge.NativeModule; - -/** - * Provider for an already initialized and non-lazy NativeModule. - */ +/** Provider for an already initialized and non-lazy NativeModule. */ public class EagerModuleProvider implements Provider { private final NativeModule mModule; diff --git a/ReactAndroid/src/main/java/com/facebook/react/HeadlessJsTaskService.java b/ReactAndroid/src/main/java/com/facebook/react/HeadlessJsTaskService.java index c527167cf3d..0405edd868e 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/HeadlessJsTaskService.java +++ b/ReactAndroid/src/main/java/com/facebook/react/HeadlessJsTaskService.java @@ -1,17 +1,11 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react; -import javax.annotation.Nullable; - -import java.util.Set; -import java.util.concurrent.CopyOnWriteArraySet; - import android.annotation.SuppressLint; import android.app.Service; import android.content.BroadcastReceiver; @@ -19,23 +13,25 @@ import android.content.Context; import android.content.Intent; import android.os.IBinder; import android.os.PowerManager; - import com.facebook.infer.annotation.Assertions; import com.facebook.react.bridge.ReactContext; import com.facebook.react.bridge.UiThreadUtil; -import com.facebook.react.jstasks.HeadlessJsTaskEventListener; import com.facebook.react.jstasks.HeadlessJsTaskConfig; import com.facebook.react.jstasks.HeadlessJsTaskContext; +import com.facebook.react.jstasks.HeadlessJsTaskEventListener; +import java.util.Set; +import java.util.concurrent.CopyOnWriteArraySet; +import javax.annotation.Nullable; /** - * Base class for running JS without a UI. Generally, you only need to override - * {@link #getTaskConfig}, which is called for every {@link #onStartCommand}. The - * result, if not {@code null}, is used to run a JS task. + * Base class for running JS without a UI. Generally, you only need to override {@link + * #getTaskConfig}, which is called for every {@link #onStartCommand}. The result, if not {@code + * null}, is used to run a JS task. * - * If you need more fine-grained control over how tasks are run, you can override - * {@link #onStartCommand} and call {@link #startTask} depending on your custom logic. + *

If you need more fine-grained control over how tasks are run, you can override {@link + * #onStartCommand} and call {@link #startTask} depending on your custom logic. * - * If you're starting a {@code HeadlessJsTaskService} from a {@code BroadcastReceiver} (e.g. + *

If you're starting a {@code HeadlessJsTaskService} from a {@code BroadcastReceiver} (e.g. * handling push notifications), make sure to call {@link #acquireWakeLockNow} before returning from * {@link BroadcastReceiver#onReceive}, to make sure the device doesn't go to sleep before the * service is started. @@ -57,9 +53,10 @@ public abstract class HeadlessJsTaskService extends Service implements HeadlessJ /** * Called from {@link #onStartCommand} to create a {@link HeadlessJsTaskConfig} for this intent. + * * @param intent the {@link Intent} received in {@link #onStartCommand}. - * @return a {@link HeadlessJsTaskConfig} to be used with {@link #startTask}, or - * {@code null} to ignore this command. + * @return a {@link HeadlessJsTaskConfig} to be used with {@link #startTask}, or {@code null} to + * ignore this command. */ protected @Nullable HeadlessJsTaskConfig getTaskConfig(Intent intent) { return null; @@ -72,10 +69,10 @@ public abstract class HeadlessJsTaskService extends Service implements HeadlessJ public static void acquireWakeLockNow(Context context) { if (sWakeLock == null || !sWakeLock.isHeld()) { PowerManager powerManager = - Assertions.assertNotNull((PowerManager) context.getSystemService(POWER_SERVICE)); - sWakeLock = powerManager.newWakeLock( - PowerManager.PARTIAL_WAKE_LOCK, - HeadlessJsTaskService.class.getCanonicalName()); + Assertions.assertNotNull((PowerManager) context.getSystemService(POWER_SERVICE)); + sWakeLock = + powerManager.newWakeLock( + PowerManager.PARTIAL_WAKE_LOCK, HeadlessJsTaskService.class.getCanonicalName()); sWakeLock.setReferenceCounted(false); sWakeLock.acquire(); } @@ -89,7 +86,7 @@ public abstract class HeadlessJsTaskService extends Service implements HeadlessJ /** * Start a task. This method handles starting a new React instance if required. * - * Has to be called on the UI thread. + *

Has to be called on the UI thread. * * @param taskConfig describes what task to start and the parameters to pass to it */ @@ -97,17 +94,17 @@ public abstract class HeadlessJsTaskService extends Service implements HeadlessJ UiThreadUtil.assertOnUiThread(); acquireWakeLockNow(this); final ReactInstanceManager reactInstanceManager = - getReactNativeHost().getReactInstanceManager(); + getReactNativeHost().getReactInstanceManager(); ReactContext reactContext = reactInstanceManager.getCurrentReactContext(); if (reactContext == null) { - reactInstanceManager - .addReactInstanceEventListener(new ReactInstanceManager.ReactInstanceEventListener() { - @Override - public void onReactContextInitialized(ReactContext reactContext) { - invokeStartTask(reactContext, taskConfig); - reactInstanceManager.removeReactInstanceEventListener(this); - } - }); + reactInstanceManager.addReactInstanceEventListener( + new ReactInstanceManager.ReactInstanceEventListener() { + @Override + public void onReactContextInitialized(ReactContext reactContext) { + invokeStartTask(reactContext, taskConfig); + reactInstanceManager.removeReactInstanceEventListener(this); + } + }); reactInstanceManager.createReactContextInBackground(); } else { invokeStartTask(reactContext, taskConfig); @@ -115,18 +112,18 @@ public abstract class HeadlessJsTaskService extends Service implements HeadlessJ } private void invokeStartTask(ReactContext reactContext, final HeadlessJsTaskConfig taskConfig) { - final HeadlessJsTaskContext headlessJsTaskContext = HeadlessJsTaskContext.getInstance(reactContext); + final HeadlessJsTaskContext headlessJsTaskContext = + HeadlessJsTaskContext.getInstance(reactContext); headlessJsTaskContext.addTaskEventListener(this); UiThreadUtil.runOnUiThread( - new Runnable() { - @Override - public void run() { - int taskId = headlessJsTaskContext.startTask(taskConfig); - mActiveTasks.add(taskId); - } - } - ); + new Runnable() { + @Override + public void run() { + int taskId = headlessJsTaskContext.startTask(taskConfig); + mActiveTasks.add(taskId); + } + }); } @Override @@ -138,7 +135,7 @@ public abstract class HeadlessJsTaskService extends Service implements HeadlessJ ReactContext reactContext = reactInstanceManager.getCurrentReactContext(); if (reactContext != null) { HeadlessJsTaskContext headlessJsTaskContext = - HeadlessJsTaskContext.getInstance(reactContext); + HeadlessJsTaskContext.getInstance(reactContext); headlessJsTaskContext.removeTaskEventListener(this); } } @@ -148,7 +145,7 @@ public abstract class HeadlessJsTaskService extends Service implements HeadlessJ } @Override - public void onHeadlessJsTaskStart(int taskId) { } + public void onHeadlessJsTaskStart(int taskId) {} @Override public void onHeadlessJsTaskFinish(int taskId) { @@ -160,10 +157,10 @@ public abstract class HeadlessJsTaskService extends Service implements HeadlessJ /** * Get the {@link ReactNativeHost} used by this app. By default, assumes {@link #getApplication()} - * is an instance of {@link ReactApplication} and calls - * {@link ReactApplication#getReactNativeHost()}. Override this method if your application class - * does not implement {@code ReactApplication} or you simply have a different mechanism for - * storing a {@code ReactNativeHost}, e.g. as a static field somewhere. + * is an instance of {@link ReactApplication} and calls {@link + * ReactApplication#getReactNativeHost()}. Override this method if your application class does not + * implement {@code ReactApplication} or you simply have a different mechanism for storing a + * {@code ReactNativeHost}, e.g. as a static field somewhere. */ protected ReactNativeHost getReactNativeHost() { return ((ReactApplication) getApplication()).getReactNativeHost(); diff --git a/ReactAndroid/src/main/java/com/facebook/react/LazyReactPackage.java b/ReactAndroid/src/main/java/com/facebook/react/LazyReactPackage.java index 5c8217b1b93..7e07760f639 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/LazyReactPackage.java +++ b/ReactAndroid/src/main/java/com/facebook/react/LazyReactPackage.java @@ -76,7 +76,8 @@ public abstract class LazyReactPackage implements ReactPackage { * @param reactContext * @return */ - public Iterable getNativeModuleIterator(final ReactApplicationContext reactContext) { + public Iterable getNativeModuleIterator( + final ReactApplicationContext reactContext) { final Map reactModuleInfoMap = getReactModuleInfoProvider().getReactModuleInfos(); final List nativeModules = getNativeModules(reactContext); diff --git a/ReactAndroid/src/main/java/com/facebook/react/MemoryPressureRouter.java b/ReactAndroid/src/main/java/com/facebook/react/MemoryPressureRouter.java index 209c21f5f0f..fa88fef1403 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/MemoryPressureRouter.java +++ b/ReactAndroid/src/main/java/com/facebook/react/MemoryPressureRouter.java @@ -13,12 +13,10 @@ import java.util.Collections; import java.util.LinkedHashSet; import java.util.Set; -/** - * Translates and routes memory pressure events to the current catalyst instance. - */ +/** Translates and routes memory pressure events to the current catalyst instance. */ public class MemoryPressureRouter implements ComponentCallbacks2 { private final Set mListeners = - Collections.synchronizedSet(new LinkedHashSet()); + Collections.synchronizedSet(new LinkedHashSet()); MemoryPressureRouter(Context context) { context.getApplicationContext().registerComponentCallbacks(this); @@ -28,16 +26,12 @@ public class MemoryPressureRouter implements ComponentCallbacks2 { context.getApplicationContext().unregisterComponentCallbacks(this); } - /** - * Add a listener to be notified of memory pressure events. - */ + /** Add a listener to be notified of memory pressure events. */ public void addMemoryPressureListener(MemoryPressureListener listener) { mListeners.add(listener); } - /** - * Remove a listener previously added with {@link #addMemoryPressureListener}. - */ + /** Remove a listener previously added with {@link #addMemoryPressureListener}. */ public void removeMemoryPressureListener(MemoryPressureListener listener) { mListeners.remove(listener); } @@ -48,18 +42,16 @@ public class MemoryPressureRouter implements ComponentCallbacks2 { } @Override - public void onConfigurationChanged(Configuration newConfig) { - } + public void onConfigurationChanged(Configuration newConfig) {} @Override - public void onLowMemory() { - } + public void onLowMemory() {} private void dispatchMemoryPressure(int level) { // copy listeners array to avoid ConcurrentModificationException if any of the listeners remove // themselves in handleMemoryPressure() MemoryPressureListener[] listeners = - mListeners.toArray(new MemoryPressureListener[mListeners.size()]); + mListeners.toArray(new MemoryPressureListener[mListeners.size()]); for (MemoryPressureListener listener : listeners) { listener.handleMemoryPressure(level); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/NativeModuleRegistryBuilder.java b/ReactAndroid/src/main/java/com/facebook/react/NativeModuleRegistryBuilder.java index ea4365e6675..9107a62d98e 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/NativeModuleRegistryBuilder.java +++ b/ReactAndroid/src/main/java/com/facebook/react/NativeModuleRegistryBuilder.java @@ -64,7 +64,8 @@ public class NativeModuleRegistryBuilder { // already in the list, and then NOT add the new module, since that will be directly exposed // Note that is someone uses {@link NativeModuleRegistry#registerModules}, we will NOT check - // for TurboModules - assuming that people wanted to explicitly register native modules there + // for TurboModules - assuming that people wanted to explicitly register native modules + // there continue; } mModules.put(name, moduleHolder); diff --git a/ReactAndroid/src/main/java/com/facebook/react/ReactActivity.java b/ReactAndroid/src/main/java/com/facebook/react/ReactActivity.java index 1dd6d18073c..b5b0024f863 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/ReactActivity.java +++ b/ReactAndroid/src/main/java/com/facebook/react/ReactActivity.java @@ -1,26 +1,21 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react; -import javax.annotation.Nullable; - import android.content.Intent; import android.os.Bundle; -import androidx.appcompat.app.AppCompatActivity; import android.view.KeyEvent; - +import androidx.appcompat.app.AppCompatActivity; import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler; import com.facebook.react.modules.core.PermissionAwareActivity; import com.facebook.react.modules.core.PermissionListener; +import javax.annotation.Nullable; -/** - * Base Activity for React Native applications. - */ +/** Base Activity for React Native applications. */ public abstract class ReactActivity extends AppCompatActivity implements DefaultHardwareBackBtnHandler, PermissionAwareActivity { @@ -31,17 +26,14 @@ public abstract class ReactActivity extends AppCompatActivity } /** - * Returns the name of the main component registered from JavaScript. - * This is used to schedule rendering of the component. - * e.g. "MoviesApp" + * Returns the name of the main component registered from JavaScript. This is used to schedule + * rendering of the component. e.g. "MoviesApp" */ protected @Nullable String getMainComponentName() { return null; } - /** - * Called at construction time, override if you have a custom delegate implementation. - */ + /** Called at construction time, override if you have a custom delegate implementation. */ protected ReactActivityDelegate createReactActivityDelegate() { return new ReactActivityDelegate(this, getMainComponentName()); } @@ -111,17 +103,13 @@ public abstract class ReactActivity extends AppCompatActivity @Override public void requestPermissions( - String[] permissions, - int requestCode, - PermissionListener listener) { + String[] permissions, int requestCode, PermissionListener listener) { mDelegate.requestPermissions(permissions, requestCode, listener); } @Override public void onRequestPermissionsResult( - int requestCode, - String[] permissions, - int[] grantResults) { + int requestCode, String[] permissions, int[] grantResults) { mDelegate.onRequestPermissionsResult(requestCode, permissions, grantResults); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/ReactActivityDelegate.java b/ReactAndroid/src/main/java/com/facebook/react/ReactActivityDelegate.java index fcfbea9b4d3..199d9bf6a41 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/ReactActivityDelegate.java +++ b/ReactAndroid/src/main/java/com/facebook/react/ReactActivityDelegate.java @@ -12,12 +12,9 @@ import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.view.KeyEvent; - import com.facebook.infer.annotation.Assertions; import com.facebook.react.bridge.Callback; -import com.facebook.react.uimanager.RootView; import com.facebook.react.modules.core.PermissionListener; - import javax.annotation.Nullable; /** @@ -54,11 +51,11 @@ public class ReactActivityDelegate { } /** - * Get the {@link ReactNativeHost} used by this app. By default, assumes - * {@link Activity#getApplication()} is an instance of {@link ReactApplication} and calls - * {@link ReactApplication#getReactNativeHost()}. Override this method if your application class - * does not implement {@code ReactApplication} or you simply have a different mechanism for - * storing a {@code ReactNativeHost}, e.g. as a static field somewhere. + * Get the {@link ReactNativeHost} used by this app. By default, assumes {@link + * Activity#getApplication()} is an instance of {@link ReactApplication} and calls {@link + * ReactApplication#getReactNativeHost()}. Override this method if your application class does not + * implement {@code ReactApplication} or you simply have a different mechanism for storing a + * {@code ReactNativeHost}, e.g. as a static field somewhere. */ protected ReactNativeHost getReactNativeHost() { return ((ReactApplication) getPlainActivity().getApplication()).getReactNativeHost(); @@ -74,7 +71,9 @@ public class ReactActivityDelegate { protected void onCreate(Bundle savedInstanceState) { String mainComponentName = getMainComponentName(); - mReactDelegate = new ReactDelegate(getPlainActivity(), getReactNativeHost(), mainComponentName, getLaunchOptions()); + mReactDelegate = + new ReactDelegate( + getPlainActivity(), getReactNativeHost(), mainComponentName, getLaunchOptions()); if (mMainComponentName != null) { loadApp(mainComponentName); } @@ -108,8 +107,8 @@ public class ReactActivityDelegate { public boolean onKeyDown(int keyCode, KeyEvent event) { if (getReactNativeHost().hasInstance() - && getReactNativeHost().getUseDeveloperSupport() - && keyCode == KeyEvent.KEYCODE_MEDIA_FAST_FORWARD) { + && getReactNativeHost().getUseDeveloperSupport() + && keyCode == KeyEvent.KEYCODE_MEDIA_FAST_FORWARD) { event.startTracking(); return true; } @@ -150,25 +149,24 @@ public class ReactActivityDelegate { @TargetApi(Build.VERSION_CODES.M) public void requestPermissions( - String[] permissions, - int requestCode, - PermissionListener listener) { + String[] permissions, int requestCode, PermissionListener listener) { mPermissionListener = listener; getPlainActivity().requestPermissions(permissions, requestCode); } public void onRequestPermissionsResult( - final int requestCode, - final String[] permissions, - final int[] grantResults) { - mPermissionsCallback = new Callback() { - @Override - public void invoke(Object... args) { - if (mPermissionListener != null && mPermissionListener.onRequestPermissionsResult(requestCode, permissions, grantResults)) { - mPermissionListener = null; - } - } - }; + final int requestCode, final String[] permissions, final int[] grantResults) { + mPermissionsCallback = + new Callback() { + @Override + public void invoke(Object... args) { + if (mPermissionListener != null + && mPermissionListener.onRequestPermissionsResult( + requestCode, permissions, grantResults)) { + mPermissionListener = null; + } + } + }; } protected Context getContext() { diff --git a/ReactAndroid/src/main/java/com/facebook/react/ReactAndroidHWInputDeviceHelper.java b/ReactAndroid/src/main/java/com/facebook/react/ReactAndroidHWInputDeviceHelper.java index de1df519d37..7168f89f1ce 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/ReactAndroidHWInputDeviceHelper.java +++ b/ReactAndroid/src/main/java/com/facebook/react/ReactAndroidHWInputDeviceHelper.java @@ -1,47 +1,42 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react; import android.view.KeyEvent; import android.view.View; - import com.facebook.react.bridge.WritableMap; import com.facebook.react.bridge.WritableNativeMap; import com.facebook.react.common.MapBuilder; - import java.util.Map; -/** - * Responsible for dispatching events specific for hardware inputs. - */ +/** Responsible for dispatching events specific for hardware inputs. */ public class ReactAndroidHWInputDeviceHelper { /** - * Contains a mapping between handled KeyEvents and the corresponding navigation event - * that should be fired when the KeyEvent is received. + * Contains a mapping between handled KeyEvents and the corresponding navigation event that should + * be fired when the KeyEvent is received. */ - private static final Map KEY_EVENTS_ACTIONS = MapBuilder.builder() - .put(KeyEvent.KEYCODE_DPAD_CENTER, "select") - .put(KeyEvent.KEYCODE_ENTER, "select") - .put(KeyEvent.KEYCODE_SPACE, "select") - .put(KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE, "playPause") - .put(KeyEvent.KEYCODE_MEDIA_REWIND, "rewind") - .put(KeyEvent.KEYCODE_MEDIA_FAST_FORWARD, "fastForward") - .put(KeyEvent.KEYCODE_DPAD_UP, "up") - .put(KeyEvent.KEYCODE_DPAD_RIGHT, "right") - .put(KeyEvent.KEYCODE_DPAD_DOWN, "down") - .put(KeyEvent.KEYCODE_DPAD_LEFT, "left") - .build(); + private static final Map KEY_EVENTS_ACTIONS = + MapBuilder.builder() + .put(KeyEvent.KEYCODE_DPAD_CENTER, "select") + .put(KeyEvent.KEYCODE_ENTER, "select") + .put(KeyEvent.KEYCODE_SPACE, "select") + .put(KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE, "playPause") + .put(KeyEvent.KEYCODE_MEDIA_REWIND, "rewind") + .put(KeyEvent.KEYCODE_MEDIA_FAST_FORWARD, "fastForward") + .put(KeyEvent.KEYCODE_DPAD_UP, "up") + .put(KeyEvent.KEYCODE_DPAD_RIGHT, "right") + .put(KeyEvent.KEYCODE_DPAD_DOWN, "down") + .put(KeyEvent.KEYCODE_DPAD_LEFT, "left") + .build(); /** - * We keep a reference to the last focused view id - * so that we can send it as a target for key events - * and be able to send a blur event when focus changes. + * We keep a reference to the last focused view id so that we can send it as a target for key + * events and be able to send a blur event when focus changes. */ private int mLastFocusedViewId = View.NO_ID; @@ -51,21 +46,17 @@ public class ReactAndroidHWInputDeviceHelper { this.mReactRootView = mReactRootView; } - /** - * Called from {@link ReactRootView}. - * This is the main place the key events are handled. - */ + /** Called from {@link ReactRootView}. This is the main place the key events are handled. */ public void handleKeyEvent(KeyEvent ev) { int eventKeyCode = ev.getKeyCode(); int eventKeyAction = ev.getAction(); - if ((eventKeyAction == KeyEvent.ACTION_UP || eventKeyAction == KeyEvent.ACTION_DOWN) && KEY_EVENTS_ACTIONS.containsKey(eventKeyCode)) { + if ((eventKeyAction == KeyEvent.ACTION_UP || eventKeyAction == KeyEvent.ACTION_DOWN) + && KEY_EVENTS_ACTIONS.containsKey(eventKeyCode)) { dispatchEvent(KEY_EVENTS_ACTIONS.get(eventKeyCode), mLastFocusedViewId, eventKeyAction); } } - /** - * Called from {@link ReactRootView} when focused view changes. - */ + /** Called from {@link ReactRootView} when focused view changes. */ public void onFocusChanged(View newFocusedView) { if (mLastFocusedViewId == newFocusedView.getId()) { return; @@ -77,9 +68,7 @@ public class ReactAndroidHWInputDeviceHelper { dispatchEvent("focus", newFocusedView.getId()); } - /** - * Called from {@link ReactRootView} when the whole view hierarchy looses focus. - */ + /** Called from {@link ReactRootView} when the whole view hierarchy looses focus. */ public void clearFocus() { if (mLastFocusedViewId != View.NO_ID) { dispatchEvent("blur", mLastFocusedViewId); diff --git a/ReactAndroid/src/main/java/com/facebook/react/ReactApplication.java b/ReactAndroid/src/main/java/com/facebook/react/ReactApplication.java index 0a63e0149ea..2f43646d7af 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/ReactApplication.java +++ b/ReactAndroid/src/main/java/com/facebook/react/ReactApplication.java @@ -1,16 +1,13 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react; public interface ReactApplication { - /** - * Get the default {@link ReactNativeHost} for this app. - */ + /** Get the default {@link ReactNativeHost} for this app. */ ReactNativeHost getReactNativeHost(); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/ReactDelegate.java b/ReactAndroid/src/main/java/com/facebook/react/ReactDelegate.java index e219c8be3c6..99aef296725 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/ReactDelegate.java +++ b/ReactAndroid/src/main/java/com/facebook/react/ReactDelegate.java @@ -1,21 +1,18 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.KeyEvent; - import com.facebook.infer.annotation.Assertions; import com.facebook.react.devsupport.DoubleTapReloadRecognizer; import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler; - import javax.annotation.Nullable; /** @@ -27,19 +24,19 @@ public class ReactDelegate { private final Activity mActivity; private ReactRootView mReactRootView; - @Nullable - private final String mMainComponentName; + @Nullable private final String mMainComponentName; - @Nullable - private Bundle mLaunchOptions; + @Nullable private Bundle mLaunchOptions; - @Nullable - private DoubleTapReloadRecognizer mDoubleTapReloadRecognizer; + @Nullable private DoubleTapReloadRecognizer mDoubleTapReloadRecognizer; private ReactNativeHost mReactNativeHost; - - public ReactDelegate(Activity activity, ReactNativeHost reactNativeHost, @Nullable String appKey, @Nullable Bundle launchOptions) { + public ReactDelegate( + Activity activity, + ReactNativeHost reactNativeHost, + @Nullable String appKey, + @Nullable Bundle launchOptions) { mActivity = activity; mMainComponentName = appKey; mLaunchOptions = launchOptions; @@ -50,9 +47,12 @@ public class ReactDelegate { public void onHostResume() { if (getReactNativeHost().hasInstance()) { if (mActivity instanceof DefaultHardwareBackBtnHandler) { - getReactNativeHost().getReactInstanceManager().onHostResume(mActivity, (DefaultHardwareBackBtnHandler) mActivity); + getReactNativeHost() + .getReactInstanceManager() + .onHostResume(mActivity, (DefaultHardwareBackBtnHandler) mActivity); } else { - throw new ClassCastException("Host Activity does not implement DefaultHardwareBackBtnHandler"); + throw new ClassCastException( + "Host Activity does not implement DefaultHardwareBackBtnHandler"); } } } @@ -81,9 +81,12 @@ public class ReactDelegate { return false; } - public void onActivityResult(int requestCode, int resultCode, Intent data, boolean shouldForwardToReactInstance) { + public void onActivityResult( + int requestCode, int resultCode, Intent data, boolean shouldForwardToReactInstance) { if (getReactNativeHost().hasInstance() && shouldForwardToReactInstance) { - getReactNativeHost().getReactInstanceManager().onActivityResult(mActivity, requestCode, resultCode, data); + getReactNativeHost() + .getReactInstanceManager() + .onActivityResult(mActivity, requestCode, resultCode, data); } } @@ -97,26 +100,23 @@ public class ReactDelegate { } mReactRootView = createRootView(); mReactRootView.startReactApplication( - getReactNativeHost().getReactInstanceManager(), - appKey, - mLaunchOptions); - + getReactNativeHost().getReactInstanceManager(), appKey, mLaunchOptions); } public ReactRootView getReactRootView() { return mReactRootView; } - protected ReactRootView createRootView() { return new ReactRootView(mActivity); } /** - * Handles delegating the {@link Activity#onKeyUp(int, KeyEvent)} method to determine whether - * the application should show the developer menu or should reload the React Application. + * Handles delegating the {@link Activity#onKeyUp(int, KeyEvent)} method to determine whether the + * application should show the developer menu or should reload the React Application. * - * @return true if we consume the event and either shoed the develop menu or reloaded the application. + * @return true if we consume the event and either shoed the develop menu or reloaded the + * application. */ public boolean shouldShowDevMenuOrReload(int keyCode, KeyEvent event) { if (getReactNativeHost().hasInstance() && getReactNativeHost().getUseDeveloperSupport()) { @@ -124,7 +124,9 @@ public class ReactDelegate { getReactNativeHost().getReactInstanceManager().showDevOptionsDialog(); return true; } - boolean didDoubleTapR = Assertions.assertNotNull(mDoubleTapReloadRecognizer).didDoubleTapR(keyCode, mActivity.getCurrentFocus()); + boolean didDoubleTapR = + Assertions.assertNotNull(mDoubleTapReloadRecognizer) + .didDoubleTapR(keyCode, mActivity.getCurrentFocus()); if (didDoubleTapR) { getReactNativeHost().getReactInstanceManager().getDevSupportManager().handleReloadJS(); return true; @@ -133,9 +135,7 @@ public class ReactDelegate { return false; } - /** - * Get the {@link ReactNativeHost} used by this app. - */ + /** Get the {@link ReactNativeHost} used by this app. */ private ReactNativeHost getReactNativeHost() { return mReactNativeHost; } @@ -143,5 +143,4 @@ public class ReactDelegate { public ReactInstanceManager getReactInstanceManager() { return getReactNativeHost().getReactInstanceManager(); } - } diff --git a/ReactAndroid/src/main/java/com/facebook/react/ReactFragment.java b/ReactAndroid/src/main/java/com/facebook/react/ReactFragment.java index 6673c895527..34ed7aa3452 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/ReactFragment.java +++ b/ReactAndroid/src/main/java/com/facebook/react/ReactFragment.java @@ -1,11 +1,9 @@ - /** -* Copyright (c) Facebook, Inc. and its affiliates. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - + * Copyright (c) Facebook, Inc. and its affiliates. + * + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. + */ package com.facebook.react; import android.annotation.TargetApi; @@ -17,194 +15,188 @@ import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; - +import androidx.fragment.app.Fragment; import com.facebook.react.modules.core.PermissionAwareActivity; import com.facebook.react.modules.core.PermissionListener; - import javax.annotation.Nullable; -import androidx.fragment.app.Fragment; - /** -* Fragment for creating a React View. This allows the developer to "embed" a React Application -* inside native components such as a Drawer, ViewPager, etc. -*/ + * Fragment for creating a React View. This allows the developer to "embed" a React Application + * inside native components such as a Drawer, ViewPager, etc. + */ public class ReactFragment extends Fragment implements PermissionAwareActivity { -private static final String ARG_COMPONENT_NAME = "arg_component_name"; -private static final String ARG_LAUNCH_OPTIONS = "arg_launch_options"; + private static final String ARG_COMPONENT_NAME = "arg_component_name"; + private static final String ARG_LAUNCH_OPTIONS = "arg_launch_options"; -private ReactDelegate mReactDelegate; + private ReactDelegate mReactDelegate; -@Nullable -private PermissionListener mPermissionListener; + @Nullable private PermissionListener mPermissionListener; - -public ReactFragment() { - // Required empty public constructor -} - -/** - * @param componentName The name of the react native component - * @return A new instance of fragment ReactFragment. - */ -private static ReactFragment newInstance(String componentName, Bundle launchOptions) { - ReactFragment fragment = new ReactFragment(); - Bundle args = new Bundle(); - args.putString(ARG_COMPONENT_NAME, componentName); - args.putBundle(ARG_LAUNCH_OPTIONS, launchOptions); - fragment.setArguments(args); - return fragment; -} - -// region Lifecycle -@Override -public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - String mainComponentName = null; - Bundle launchOptions = null; - if (getArguments() != null) { - mainComponentName = getArguments().getString(ARG_COMPONENT_NAME); - launchOptions = getArguments().getBundle(ARG_LAUNCH_OPTIONS); - } - if (mainComponentName == null) { - throw new IllegalStateException("Cannot loadApp if component name is null"); - } - mReactDelegate = new ReactDelegate(getActivity(), getReactNativeHost(), mainComponentName, launchOptions); -} - -/** - * Get the {@link ReactNativeHost} used by this app. By default, assumes - * {@link Activity#getApplication()} is an instance of {@link ReactApplication} and calls - * {@link ReactApplication#getReactNativeHost()}. Override this method if your application class - * does not implement {@code ReactApplication} or you simply have a different mechanism for - * storing a {@code ReactNativeHost}, e.g. as a static field somewhere. - */ -protected ReactNativeHost getReactNativeHost() { - return ((ReactApplication) getActivity().getApplication()).getReactNativeHost(); -} - -@Override -public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - mReactDelegate.loadApp(); - return mReactDelegate.getReactRootView(); -} - -@Override -public void onResume() { - super.onResume(); - mReactDelegate.onHostResume(); -} - -@Override -public void onPause() { - super.onPause(); - mReactDelegate.onHostPause(); -} - -@Override -public void onDestroy() { - super.onDestroy(); - mReactDelegate.onHostDestroy(); -} -// endregion - -@Override -public void onActivityResult(int requestCode, int resultCode, Intent data) { - super.onActivityResult(requestCode, resultCode, data); - mReactDelegate.onActivityResult(requestCode, resultCode, data, false); -} - -/** - * Helper to forward hardware back presses to our React Native Host - * - * This must be called via a forward from your host Activity - * - */ -public boolean onBackPressed() { - return mReactDelegate.onBackPressed(); -} - -/** - * Helper to forward onKeyUp commands from our host Activity. - * This allows ReactFragment to handle double tap reloads and dev menus - * - * This must be called via a forward from your host Activity - * - * @param keyCode keyCode - * @param event event - * @return true if we handled onKeyUp - */ -public boolean onKeyUp(int keyCode, KeyEvent event) { - return mReactDelegate.shouldShowDevMenuOrReload(keyCode, event); -} - -@Override -public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { - super.onRequestPermissionsResult(requestCode, permissions, grantResults); - if (mPermissionListener != null && - mPermissionListener.onRequestPermissionsResult(requestCode, permissions, grantResults)) { - mPermissionListener = null; - } -} - -@Override -public int checkPermission(String permission, int pid, int uid) { - return getActivity().checkPermission(permission, pid, uid); -} - -@TargetApi(Build.VERSION_CODES.M) -@Override -public int checkSelfPermission(String permission) { - return getActivity().checkSelfPermission(permission); -} - -@TargetApi(Build.VERSION_CODES.M) -@Override -public void requestPermissions(String[] permissions, int requestCode, PermissionListener listener) { - mPermissionListener = listener; - requestPermissions(permissions, requestCode); -} - -/** - * Builder class to help instantiate a ReactFragment - */ -public static class Builder { - - String mComponentName; - Bundle mLaunchOptions; - - public Builder() { - mComponentName = null; - mLaunchOptions = null; + public ReactFragment() { + // Required empty public constructor } /** - * Set the Component name for our React Native instance. - * - * @param componentName The name of the component - * @return Builder + * @param componentName The name of the react native component + * @return A new instance of fragment ReactFragment. */ - public Builder setComponentName(String componentName) { - mComponentName = componentName; - return this; + private static ReactFragment newInstance(String componentName, Bundle launchOptions) { + ReactFragment fragment = new ReactFragment(); + Bundle args = new Bundle(); + args.putString(ARG_COMPONENT_NAME, componentName); + args.putBundle(ARG_LAUNCH_OPTIONS, launchOptions); + fragment.setArguments(args); + return fragment; + } + + // region Lifecycle + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + String mainComponentName = null; + Bundle launchOptions = null; + if (getArguments() != null) { + mainComponentName = getArguments().getString(ARG_COMPONENT_NAME); + launchOptions = getArguments().getBundle(ARG_LAUNCH_OPTIONS); + } + if (mainComponentName == null) { + throw new IllegalStateException("Cannot loadApp if component name is null"); + } + mReactDelegate = + new ReactDelegate(getActivity(), getReactNativeHost(), mainComponentName, launchOptions); } /** - * Set the Launch Options for our React Native instance. - * - * @param launchOptions launchOptions - * @return Builder + * Get the {@link ReactNativeHost} used by this app. By default, assumes {@link + * Activity#getApplication()} is an instance of {@link ReactApplication} and calls {@link + * ReactApplication#getReactNativeHost()}. Override this method if your application class does not + * implement {@code ReactApplication} or you simply have a different mechanism for storing a + * {@code ReactNativeHost}, e.g. as a static field somewhere. */ - public Builder setLaunchOptions(Bundle launchOptions) { - mLaunchOptions = launchOptions; - return this; + protected ReactNativeHost getReactNativeHost() { + return ((ReactApplication) getActivity().getApplication()).getReactNativeHost(); } - public ReactFragment build() { - return ReactFragment.newInstance(mComponentName, mLaunchOptions); + @Override + public View onCreateView( + LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + mReactDelegate.loadApp(); + return mReactDelegate.getReactRootView(); } -} + @Override + public void onResume() { + super.onResume(); + mReactDelegate.onHostResume(); + } + + @Override + public void onPause() { + super.onPause(); + mReactDelegate.onHostPause(); + } + + @Override + public void onDestroy() { + super.onDestroy(); + mReactDelegate.onHostDestroy(); + } + // endregion + + @Override + public void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + mReactDelegate.onActivityResult(requestCode, resultCode, data, false); + } + + /** + * Helper to forward hardware back presses to our React Native Host + * + *

This must be called via a forward from your host Activity + */ + public boolean onBackPressed() { + return mReactDelegate.onBackPressed(); + } + + /** + * Helper to forward onKeyUp commands from our host Activity. This allows ReactFragment to handle + * double tap reloads and dev menus + * + *

This must be called via a forward from your host Activity + * + * @param keyCode keyCode + * @param event event + * @return true if we handled onKeyUp + */ + public boolean onKeyUp(int keyCode, KeyEvent event) { + return mReactDelegate.shouldShowDevMenuOrReload(keyCode, event); + } + + @Override + public void onRequestPermissionsResult( + int requestCode, String[] permissions, int[] grantResults) { + super.onRequestPermissionsResult(requestCode, permissions, grantResults); + if (mPermissionListener != null + && mPermissionListener.onRequestPermissionsResult(requestCode, permissions, grantResults)) { + mPermissionListener = null; + } + } + + @Override + public int checkPermission(String permission, int pid, int uid) { + return getActivity().checkPermission(permission, pid, uid); + } + + @TargetApi(Build.VERSION_CODES.M) + @Override + public int checkSelfPermission(String permission) { + return getActivity().checkSelfPermission(permission); + } + + @TargetApi(Build.VERSION_CODES.M) + @Override + public void requestPermissions( + String[] permissions, int requestCode, PermissionListener listener) { + mPermissionListener = listener; + requestPermissions(permissions, requestCode); + } + + /** Builder class to help instantiate a ReactFragment */ + public static class Builder { + + String mComponentName; + Bundle mLaunchOptions; + + public Builder() { + mComponentName = null; + mLaunchOptions = null; + } + + /** + * Set the Component name for our React Native instance. + * + * @param componentName The name of the component + * @return Builder + */ + public Builder setComponentName(String componentName) { + mComponentName = componentName; + return this; + } + + /** + * Set the Launch Options for our React Native instance. + * + * @param launchOptions launchOptions + * @return Builder + */ + public Builder setLaunchOptions(Bundle launchOptions) { + mLaunchOptions = launchOptions; + return this; + } + + public ReactFragment build() { + return ReactFragment.newInstance(mComponentName, mLaunchOptions); + } + } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/ReactFragmentActivity.java b/ReactAndroid/src/main/java/com/facebook/react/ReactFragmentActivity.java index 029909d47cd..131e97c2c1c 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/ReactFragmentActivity.java +++ b/ReactAndroid/src/main/java/com/facebook/react/ReactFragmentActivity.java @@ -1,17 +1,14 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react; /** - * @deprecated - * ReactFragmentActivity will be removed in 0.59 release. - * Use {@link ReactActivity} instead. + * @deprecated ReactFragmentActivity will be removed in 0.59 release. Use {@link ReactActivity} + * instead. */ @Deprecated -public abstract class ReactFragmentActivity extends ReactActivity { -} +public abstract class ReactFragmentActivity extends ReactActivity {} diff --git a/ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManager.java b/ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManager.java index 3bbe584ecf9..4c7dde79712 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManager.java +++ b/ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManager.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react; import static com.facebook.infer.annotation.ThreadConfined.UI; @@ -12,6 +11,7 @@ import static com.facebook.react.bridge.ReactMarkerConstants.ATTACH_MEASURED_ROO import static com.facebook.react.bridge.ReactMarkerConstants.ATTACH_MEASURED_ROOT_VIEWS_START; import static com.facebook.react.bridge.ReactMarkerConstants.BUILD_NATIVE_MODULE_REGISTRY_END; import static com.facebook.react.bridge.ReactMarkerConstants.BUILD_NATIVE_MODULE_REGISTRY_START; +import static com.facebook.react.bridge.ReactMarkerConstants.CHANGE_THREAD_PRIORITY; import static com.facebook.react.bridge.ReactMarkerConstants.CREATE_CATALYST_INSTANCE_END; import static com.facebook.react.bridge.ReactMarkerConstants.CREATE_CATALYST_INSTANCE_START; import static com.facebook.react.bridge.ReactMarkerConstants.CREATE_REACT_CONTEXT_START; @@ -25,7 +25,6 @@ import static com.facebook.react.bridge.ReactMarkerConstants.REACT_CONTEXT_THREA import static com.facebook.react.bridge.ReactMarkerConstants.REACT_CONTEXT_THREAD_START; import static com.facebook.react.bridge.ReactMarkerConstants.SETUP_REACT_CONTEXT_END; import static com.facebook.react.bridge.ReactMarkerConstants.SETUP_REACT_CONTEXT_START; -import static com.facebook.react.bridge.ReactMarkerConstants.CHANGE_THREAD_PRIORITY; import static com.facebook.react.bridge.ReactMarkerConstants.VM_INIT; import static com.facebook.react.uimanager.common.UIManagerType.FABRIC; import static com.facebook.systrace.Systrace.TRACE_TAG_REACT_APPS; @@ -38,9 +37,9 @@ import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.Process; -import androidx.core.view.ViewCompat; import android.util.Log; import android.view.View; +import androidx.core.view.ViewCompat; import com.facebook.common.logging.FLog; import com.facebook.debug.holder.PrinterHolder; import com.facebook.debug.tags.ReactDebugOverlayTags; @@ -107,28 +106,26 @@ import javax.annotation.Nullable; /** * This class is managing instances of {@link CatalystInstance}. It exposes a way to configure - * catalyst instance using {@link ReactPackage} and keeps track of the lifecycle of that - * instance. It also sets up connection between the instance and developers support functionality - * of the framework. + * catalyst instance using {@link ReactPackage} and keeps track of the lifecycle of that instance. + * It also sets up connection between the instance and developers support functionality of the + * framework. * - * An instance of this manager is required to start JS application in {@link ReactRootView} (see + *

An instance of this manager is required to start JS application in {@link ReactRootView} (see * {@link ReactRootView#startReactApplication} for more info). * - * The lifecycle of the instance of {@link ReactInstanceManager} should be bound to the - * activity that owns the {@link ReactRootView} that is used to render react application using this - * instance manager (see {@link ReactRootView#startReactApplication}). It's required to pass owning + *

The lifecycle of the instance of {@link ReactInstanceManager} should be bound to the activity + * that owns the {@link ReactRootView} that is used to render react application using this instance + * manager (see {@link ReactRootView#startReactApplication}). It's required to pass owning * activity's lifecycle events to the instance manager (see {@link #onHostPause}, {@link * #onHostDestroy} and {@link #onHostResume}). * - * To instantiate an instance of this class use {@link #builder}. + *

To instantiate an instance of this class use {@link #builder}. */ @ThreadSafe public class ReactInstanceManager { private static final String TAG = ReactInstanceManager.class.getSimpleName(); - /** - * Listener interface for react instance events. - */ + /** Listener interface for react instance events. */ public interface ReactInstanceEventListener { /** @@ -138,8 +135,8 @@ public class ReactInstanceManager { void onReactContextInitialized(ReactContext context); } - private final Set mAttachedReactRoots = Collections.synchronizedSet( - new HashSet()); + private final Set mAttachedReactRoots = + Collections.synchronizedSet(new HashSet()); private volatile LifecycleState mLifecycleState; @@ -176,8 +173,7 @@ public class ReactInstanceManager { private final JSBundleLoader mJsBundleLoader; public ReactContextInitParams( - JavaScriptExecutorFactory jsExecutorFactory, - JSBundleLoader jsBundleLoader) { + JavaScriptExecutorFactory jsExecutorFactory, JSBundleLoader jsBundleLoader) { mJsExecutorFactory = Assertions.assertNotNull(jsExecutorFactory); mJsBundleLoader = Assertions.assertNotNull(jsBundleLoader); } @@ -191,33 +187,31 @@ public class ReactInstanceManager { } } - /** - * Creates a builder that is capable of creating an instance of {@link ReactInstanceManager}. - */ + /** Creates a builder that is capable of creating an instance of {@link ReactInstanceManager}. */ public static ReactInstanceManagerBuilder builder() { return new ReactInstanceManagerBuilder(); } /* package */ ReactInstanceManager( - Context applicationContext, - @Nullable Activity currentActivity, - @Nullable DefaultHardwareBackBtnHandler defaultHardwareBackBtnHandler, - JavaScriptExecutorFactory javaScriptExecutorFactory, - @Nullable JSBundleLoader bundleLoader, - @Nullable String jsMainModulePath, - List packages, - boolean useDeveloperSupport, - @Nullable NotThreadSafeBridgeIdleDebugListener bridgeIdleDebugListener, - LifecycleState initialLifecycleState, - @Nullable UIImplementationProvider mUIImplementationProvider, - NativeModuleCallExceptionHandler nativeModuleCallExceptionHandler, - @Nullable RedBoxHandler redBoxHandler, - boolean lazyViewManagersEnabled, - @Nullable DevBundleDownloadListener devBundleDownloadListener, - int minNumShakes, - int minTimeLeftInFrameForNonBatchedOperationMs, - @Nullable JSIModulePackage jsiModulePackage, - @Nullable Map customPackagerCommandHandlers) { + Context applicationContext, + @Nullable Activity currentActivity, + @Nullable DefaultHardwareBackBtnHandler defaultHardwareBackBtnHandler, + JavaScriptExecutorFactory javaScriptExecutorFactory, + @Nullable JSBundleLoader bundleLoader, + @Nullable String jsMainModulePath, + List packages, + boolean useDeveloperSupport, + @Nullable NotThreadSafeBridgeIdleDebugListener bridgeIdleDebugListener, + LifecycleState initialLifecycleState, + @Nullable UIImplementationProvider mUIImplementationProvider, + NativeModuleCallExceptionHandler nativeModuleCallExceptionHandler, + @Nullable RedBoxHandler redBoxHandler, + boolean lazyViewManagersEnabled, + @Nullable DevBundleDownloadListener devBundleDownloadListener, + int minNumShakes, + int minTimeLeftInFrameForNonBatchedOperationMs, + @Nullable JSIModulePackage jsiModulePackage, + @Nullable Map customPackagerCommandHandlers) { Log.d(ReactConstants.TAG, "ReactInstanceManager.ctor()"); initializeSoLoaderIfNecessary(applicationContext); @@ -326,10 +320,10 @@ public class ReactInstanceManager { /** * Trigger react context initialization asynchronously in a background async task. This enables - * applications to pre-load the application JS, and execute global code before - * {@link ReactRootView} is available and measured. + * applications to pre-load the application JS, and execute global code before {@link + * ReactRootView} is available and measured. * - * Called from UI thread. + *

Called from UI thread. */ @ThreadConfined(UI) public void createReactContextInBackground() { @@ -351,8 +345,8 @@ public class ReactInstanceManager { public void recreateReactContextInBackground() { Assertions.assertCondition( mHasStartedCreatingInitialContext, - "recreateReactContextInBackground should only be called after the initial " + - "createReactContextInBackground call."); + "recreateReactContextInBackground should only be called after the initial " + + "createReactContextInBackground call."); recreateReactContextInBackgroundInner(); } @@ -367,8 +361,8 @@ public class ReactInstanceManager { final DeveloperSettings devSettings = mDevSupportManager.getDevSettings(); // If remote JS debugging is enabled, load from dev server. - if (mDevSupportManager.hasUpToDateJSBundleInCache() && - !devSettings.isRemoteJSDebugEnabled()) { + if (mDevSupportManager.hasUpToDateJSBundleInCache() + && !devSettings.isRemoteJSDebugEnabled()) { // If there is a up-to-date bundle downloaded from server, // with remote JS debugging disabled, always use that. onJSBundleLoadedFromServer(null); @@ -409,8 +403,8 @@ public class ReactInstanceManager { @ThreadConfined(UI) private void recreateReactContextInBackgroundFromBundleLoader() { Log.d( - ReactConstants.TAG, - "ReactInstanceManager.recreateReactContextInBackgroundFromBundleLoader()"); + ReactConstants.TAG, + "ReactInstanceManager.recreateReactContextInBackgroundFromBundleLoader()"); PrinterHolder.getPrinter() .logMessage(ReactDebugOverlayTags.RN_CORE, "RNCore: load from BundleLoader"); recreateReactContextInBackground(mJavaScriptExecutorFactory, mBundleLoader); @@ -418,7 +412,7 @@ public class ReactInstanceManager { /** * @return whether createReactContextInBackground has been called. Will return false after - * onDestroy until a new initial context has been created. + * onDestroy until a new initial context has been created. */ public boolean hasStartedCreatingInitialContext() { return mHasStartedCreatingInitialContext; @@ -437,7 +431,7 @@ public class ReactInstanceManager { invokeDefaultOnBackPressed(); } else { DeviceEventManagerModule deviceEventManagerModule = - reactContext.getNativeModule(DeviceEventManagerModule.class); + reactContext.getNativeModule(DeviceEventManagerModule.class); deviceEventManagerModule.emitHardwareBackPressed(); } } @@ -449,9 +443,7 @@ public class ReactInstanceManager { } } - /** - * This method will give JS the opportunity to receive intents via Linking. - */ + /** This method will give JS the opportunity to receive intents via Linking. */ @ThreadConfined(UI) public void onNewIntent(Intent intent) { UiThreadUtil.assertOnUiThread(); @@ -464,7 +456,7 @@ public class ReactInstanceManager { if (Intent.ACTION_VIEW.equals(action) && uri != null) { DeviceEventManagerModule deviceEventManagerModule = - currentContext.getNativeModule(DeviceEventManagerModule.class); + currentContext.getNativeModule(DeviceEventManagerModule.class); deviceEventManagerModule.emitNewIntentReceived(uri); } currentContext.onNewIntent(mCurrentActivity, intent); @@ -501,8 +493,8 @@ public class ReactInstanceManager { /** * Call this from {@link Activity#onPause()}. This notifies any listening modules so they can do * any necessary cleanup. The passed Activity is the current Activity being paused. This will - * always be the foreground activity that would be returned by - * {@link ReactContext#getCurrentActivity()}. + * always be the foreground activity that would be returned by {@link + * ReactContext#getCurrentActivity()}. * * @param activity the activity being paused */ @@ -510,23 +502,26 @@ public class ReactInstanceManager { public void onHostPause(Activity activity) { Assertions.assertNotNull(mCurrentActivity); Assertions.assertCondition( - activity == mCurrentActivity, - "Pausing an activity that is not the current activity, this is incorrect! " + - "Current activity: " + mCurrentActivity.getClass().getSimpleName() + " " + - "Paused activity: " + activity.getClass().getSimpleName()); + activity == mCurrentActivity, + "Pausing an activity that is not the current activity, this is incorrect! " + + "Current activity: " + + mCurrentActivity.getClass().getSimpleName() + + " " + + "Paused activity: " + + activity.getClass().getSimpleName()); onHostPause(); } /** * Use this method when the activity resumes to enable invoking the back button directly from JS. * - * This method retains an instance to provided mDefaultBackButtonImpl. Thus it's important to pass - * from the activity instance that owns this particular instance of {@link - * ReactInstanceManager}, so that once this instance receive {@link #onHostDestroy} event it - * will clear the reference to that defaultBackButtonImpl. + *

This method retains an instance to provided mDefaultBackButtonImpl. Thus it's important to + * pass from the activity instance that owns this particular instance of {@link + * ReactInstanceManager}, so that once this instance receive {@link #onHostDestroy} event it will + * clear the reference to that defaultBackButtonImpl. * * @param defaultBackButtonImpl a {@link DefaultHardwareBackBtnHandler} from an Activity that owns - * this instance of {@link ReactInstanceManager}. + * this instance of {@link ReactInstanceManager}. */ @ThreadConfined(UI) public void onHostResume(Activity activity, DefaultHardwareBackBtnHandler defaultBackButtonImpl) { @@ -536,9 +531,7 @@ public class ReactInstanceManager { onHostResume(activity); } - /** - * Use this method when the activity resumes. - */ + /** Use this method when the activity resumes. */ @ThreadConfined(UI) public void onHostResume(Activity activity) { UiThreadUtil.assertOnUiThread(); @@ -558,19 +551,20 @@ public class ReactInstanceManager { // We check if activity is attached to window by checking if decor view is attached final View decorView = mCurrentActivity.getWindow().getDecorView(); if (!ViewCompat.isAttachedToWindow(decorView)) { - decorView.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() { - @Override - public void onViewAttachedToWindow(View v) { - // we can drop listener now that we know the view is attached - decorView.removeOnAttachStateChangeListener(this); - mDevSupportManager.setDevSupportEnabled(true); - } + decorView.addOnAttachStateChangeListener( + new View.OnAttachStateChangeListener() { + @Override + public void onViewAttachedToWindow(View v) { + // we can drop listener now that we know the view is attached + decorView.removeOnAttachStateChangeListener(this); + mDevSupportManager.setDevSupportEnabled(true); + } - @Override - public void onViewDetachedFromWindow(View v) { - // do nothing - } - }); + @Override + public void onViewDetachedFromWindow(View v) { + // do nothing + } + }); } else { // activity is attached to window, we can enable dev support immediately mDevSupportManager.setDevSupportEnabled(true); @@ -612,9 +606,7 @@ public class ReactInstanceManager { } } - /** - * Destroy this React instance and the attached JS context. - */ + /** Destroy this React instance and the attached JS context. */ @ThreadConfined(UI) public void destroy() { UiThreadUtil.assertOnUiThread(); @@ -655,9 +647,9 @@ public class ReactInstanceManager { ReactContext currentContext = getCurrentReactContext(); if (currentContext != null) { // we currently don't have an onCreate callback so we call onResume for both transitions - if (force || - mLifecycleState == LifecycleState.BEFORE_RESUME || - mLifecycleState == LifecycleState.BEFORE_CREATE) { + if (force + || mLifecycleState == LifecycleState.BEFORE_RESUME + || mLifecycleState == LifecycleState.BEFORE_CREATE) { currentContext.onHostResume(mCurrentActivity); } } @@ -729,9 +721,9 @@ public class ReactInstanceManager { * Attach given {@param reactRoot} to a catalyst instance manager and start JS application using * JS module provided by {@link ReactRootView#getJSModuleName}. If the react context is currently * being (re)-created, or if react context has not been created yet, the JS application associated - * with the provided reactRoot reactRoot will be started asynchronously, i.e this method won't block. - * This reactRoot will then be tracked by this manager and in case of catalyst instance restart it will - * be re-attached. + * with the provided reactRoot reactRoot will be started asynchronously, i.e this method won't + * block. This reactRoot will then be tracked by this manager and in case of catalyst instance + * restart it will be re-attached. */ @ThreadConfined(UI) public void attachRootView(ReactRoot reactRoot) { @@ -742,7 +734,8 @@ public class ReactInstanceManager { clearReactRoot(reactRoot); // If react context is being created in the background, JS application will be started - // automatically when creation completes, as reactRoot reactRoot is part of the attached reactRoot reactRoot list. + // automatically when creation completes, as reactRoot reactRoot is part of the attached + // reactRoot reactRoot list. ReactContext currentContext = getCurrentReactContext(); if (mCreateReactContextThread == null && currentContext != null) { attachRootViewToInstance(reactRoot); @@ -768,9 +761,7 @@ public class ReactInstanceManager { } } - /** - * Uses configured {@link ReactPackage} instances to create all view managers. - */ + /** Uses configured {@link ReactPackage} instances to create all view managers. */ public List getOrCreateViewManagers( ReactApplicationContext catalystApplicationContext) { ReactMarker.logMarker(CREATE_VIEW_MANAGERS_START); @@ -821,7 +812,7 @@ public class ReactInstanceManager { public @Nullable List getViewManagerNames() { Systrace.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "ReactInstanceManager.getViewManagerNames"); ReactApplicationContext context; - synchronized(mReactContextLock) { + synchronized (mReactContextLock) { context = (ReactApplicationContext) getCurrentReactContext(); if (context == null || !context.hasActiveCatalystInstance()) { return null; @@ -831,9 +822,10 @@ public class ReactInstanceManager { synchronized (mPackages) { Set uniqueNames = new HashSet<>(); for (ReactPackage reactPackage : mPackages) { - SystraceMessage.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "ReactInstanceManager.getViewManagerName") - .arg("Package", reactPackage.getClass().getSimpleName()) - .flush(); + SystraceMessage.beginSection( + TRACE_TAG_REACT_JAVA_BRIDGE, "ReactInstanceManager.getViewManagerName") + .arg("Package", reactPackage.getClass().getSimpleName()) + .flush(); if (reactPackage instanceof ViewManagerOnDemandReactPackage) { List names = ((ViewManagerOnDemandReactPackage) reactPackage).getViewManagerNames(context); @@ -848,16 +840,12 @@ public class ReactInstanceManager { } } - /** - * Add a listener to be notified of react instance events. - */ + /** Add a listener to be notified of react instance events. */ public void addReactInstanceEventListener(ReactInstanceEventListener listener) { mReactInstanceEventListeners.add(listener); } - /** - * Remove a listener previously added with {@link #addReactInstanceEventListener}. - */ + /** Remove a listener previously added with {@link #addReactInstanceEventListener}. */ public void removeReactInstanceEventListener(ReactInstanceEventListener listener) { mReactInstanceEventListeners.remove(listener); } @@ -891,26 +879,24 @@ public class ReactInstanceManager { private void onJSBundleLoadedFromServer(@Nullable NativeDeltaClient nativeDeltaClient) { Log.d(ReactConstants.TAG, "ReactInstanceManager.onJSBundleLoadedFromServer()"); - JSBundleLoader bundleLoader = nativeDeltaClient == null - ? JSBundleLoader.createCachedBundleFromNetworkLoader( - mDevSupportManager.getSourceUrl(), - mDevSupportManager.getDownloadedJSBundleFile()) - : JSBundleLoader.createDeltaFromNetworkLoader( - mDevSupportManager.getSourceUrl(), nativeDeltaClient); + JSBundleLoader bundleLoader = + nativeDeltaClient == null + ? JSBundleLoader.createCachedBundleFromNetworkLoader( + mDevSupportManager.getSourceUrl(), mDevSupportManager.getDownloadedJSBundleFile()) + : JSBundleLoader.createDeltaFromNetworkLoader( + mDevSupportManager.getSourceUrl(), nativeDeltaClient); recreateReactContextInBackground(mJavaScriptExecutorFactory, bundleLoader); } @ThreadConfined(UI) private void recreateReactContextInBackground( - JavaScriptExecutorFactory jsExecutorFactory, - JSBundleLoader jsBundleLoader) { + JavaScriptExecutorFactory jsExecutorFactory, JSBundleLoader jsBundleLoader) { Log.d(ReactConstants.TAG, "ReactInstanceManager.recreateReactContextInBackground()"); UiThreadUtil.assertOnUiThread(); - final ReactContextInitParams initParams = new ReactContextInitParams( - jsExecutorFactory, - jsBundleLoader); + final ReactContextInitParams initParams = + new ReactContextInitParams(jsExecutorFactory, jsBundleLoader); if (mCreateReactContextThread == null) { runCreateReactContextOnNewThread(initParams); } else { @@ -947,7 +933,8 @@ public class ReactInstanceManager { } } } - // As destroy() may have run and set this to false, ensure that it is true before we create + // As destroy() may have run and set this to false, ensure that it is true before we + // create mHasStartedCreatingInitialContext = true; try { @@ -1009,7 +996,6 @@ public class ReactInstanceManager { catalystInstance.initialize(); - mDevSupportManager.onNewReactContextCreated(reactContext); mMemoryPressureRouter.addMemoryPressureListener(catalystInstance); moveReactContextToCurrentLifecycleState(); @@ -1022,7 +1008,7 @@ public class ReactInstanceManager { } ReactInstanceEventListener[] listeners = - new ReactInstanceEventListener[mReactInstanceEventListeners.size()]; + new ReactInstanceEventListener[mReactInstanceEventListeners.size()]; final ReactInstanceEventListener[] finalListeners = mReactInstanceEventListeners.toArray(listeners); @@ -1057,28 +1043,30 @@ public class ReactInstanceManager { private void attachRootViewToInstance(final ReactRoot reactRoot) { Log.d(ReactConstants.TAG, "ReactInstanceManager.attachRootViewToInstance()"); Systrace.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "attachRootViewToInstance"); - UIManager uiManager = UIManagerHelper.getUIManager(mCurrentReactContext, reactRoot.getUIManagerType()); + UIManager uiManager = + UIManagerHelper.getUIManager(mCurrentReactContext, reactRoot.getUIManagerType()); @Nullable Bundle initialProperties = reactRoot.getAppProperties(); - final int rootTag = uiManager.addRootView( - reactRoot.getRootViewGroup(), - initialProperties == null ? - new WritableNativeMap() : Arguments.fromBundle(initialProperties), - reactRoot.getInitialUITemplate()); + final int rootTag = + uiManager.addRootView( + reactRoot.getRootViewGroup(), + initialProperties == null + ? new WritableNativeMap() + : Arguments.fromBundle(initialProperties), + reactRoot.getInitialUITemplate()); reactRoot.setRootViewTag(rootTag); if (reactRoot.getUIManagerType() == FABRIC) { // Fabric requires to call updateRootLayoutSpecs before starting JS Application, // this ensures the root will hace the correct pointScaleFactor. - uiManager.updateRootLayoutSpecs(rootTag, reactRoot.getWidthMeasureSpec(), reactRoot.getHeightMeasureSpec()); + uiManager.updateRootLayoutSpecs( + rootTag, reactRoot.getWidthMeasureSpec(), reactRoot.getHeightMeasureSpec()); reactRoot.setShouldLogContentAppeared(true); } else { reactRoot.runApplication(); } Systrace.beginAsyncSection( - TRACE_TAG_REACT_JAVA_BRIDGE, - "pre_rootView.onAttachedToReactInstance", - rootTag); + TRACE_TAG_REACT_JAVA_BRIDGE, "pre_rootView.onAttachedToReactInstance", rootTag); UiThreadUtil.runOnUiThread( new Runnable() { @Override @@ -1091,19 +1079,18 @@ public class ReactInstanceManager { Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE); } - private void detachViewFromInstance( - ReactRoot reactRoot, - CatalystInstance catalystInstance) { + private void detachViewFromInstance(ReactRoot reactRoot, CatalystInstance catalystInstance) { Log.d(ReactConstants.TAG, "ReactInstanceManager.detachViewFromInstance()"); UiThreadUtil.assertOnUiThread(); if (reactRoot.getUIManagerType() == FABRIC) { - catalystInstance.getJSModule(ReactFabric.class) - .unmountComponentAtNode(reactRoot.getRootViewTag()); + catalystInstance + .getJSModule(ReactFabric.class) + .unmountComponentAtNode(reactRoot.getRootViewTag()); } else { - catalystInstance.getJSModule(AppRegistry.class) - .unmountApplicationComponentAtRootTag(reactRoot.getRootViewTag()); + catalystInstance + .getJSModule(AppRegistry.class) + .unmountApplicationComponentAtRootTag(reactRoot.getRootViewTag()); } - } private void tearDownReactContext(ReactContext reactContext) { @@ -1124,29 +1111,28 @@ public class ReactInstanceManager { mMemoryPressureRouter.removeMemoryPressureListener(reactContext.getCatalystInstance()); } - /** - * @return instance of {@link ReactContext} configured a {@link CatalystInstance} set - */ + /** @return instance of {@link ReactContext} configured a {@link CatalystInstance} set */ private ReactApplicationContext createReactContext( - JavaScriptExecutor jsExecutor, - JSBundleLoader jsBundleLoader) { + JavaScriptExecutor jsExecutor, JSBundleLoader jsBundleLoader) { Log.d(ReactConstants.TAG, "ReactInstanceManager.createReactContext()"); ReactMarker.logMarker(CREATE_REACT_CONTEXT_START, jsExecutor.getName()); final ReactApplicationContext reactContext = new ReactApplicationContext(mApplicationContext); - NativeModuleCallExceptionHandler exceptionHandler = mNativeModuleCallExceptionHandler != null - ? mNativeModuleCallExceptionHandler - : mDevSupportManager; + NativeModuleCallExceptionHandler exceptionHandler = + mNativeModuleCallExceptionHandler != null + ? mNativeModuleCallExceptionHandler + : mDevSupportManager; reactContext.setNativeModuleCallExceptionHandler(exceptionHandler); NativeModuleRegistry nativeModuleRegistry = processPackages(reactContext, mPackages, false); - CatalystInstanceImpl.Builder catalystInstanceBuilder = new CatalystInstanceImpl.Builder() - .setReactQueueConfigurationSpec(ReactQueueConfigurationSpec.createDefault()) - .setJSExecutor(jsExecutor) - .setRegistry(nativeModuleRegistry) - .setJSBundleLoader(jsBundleLoader) - .setNativeModuleCallExceptionHandler(exceptionHandler); + CatalystInstanceImpl.Builder catalystInstanceBuilder = + new CatalystInstanceImpl.Builder() + .setReactQueueConfigurationSpec(ReactQueueConfigurationSpec.createDefault()) + .setJSExecutor(jsExecutor) + .setRegistry(nativeModuleRegistry) + .setJSBundleLoader(jsBundleLoader) + .setNativeModuleCallExceptionHandler(exceptionHandler); ReactMarker.logMarker(CREATE_CATALYST_INSTANCE_START); // CREATE_CATALYST_INSTANCE_END is in JSCExecutor.cpp @@ -1162,11 +1148,13 @@ public class ReactInstanceManager { reactContext.initializeWithInstance(catalystInstance); if (mJSIModulePackage != null) { - catalystInstance.addJSIModules(mJSIModulePackage - .getJSIModules(reactContext, catalystInstance.getJavaScriptContextHolder())); + catalystInstance.addJSIModules( + mJSIModulePackage.getJSIModules( + reactContext, catalystInstance.getJavaScriptContextHolder())); if (ReactFeatureFlags.useTurboModules) { - catalystInstance.setTurboModuleManager(catalystInstance.getJSIModule(JSIModuleType.TurboModuleManager)); + catalystInstance.setTurboModuleManager( + catalystInstance.getJSIModule(JSIModuleType.TurboModuleManager)); } } if (mBridgeIdleDebugListener != null) { @@ -1184,12 +1172,11 @@ public class ReactInstanceManager { } private NativeModuleRegistry processPackages( - ReactApplicationContext reactContext, - List packages, - boolean checkAndUpdatePackageMembership) { - NativeModuleRegistryBuilder nativeModuleRegistryBuilder = new NativeModuleRegistryBuilder( - reactContext, - this); + ReactApplicationContext reactContext, + List packages, + boolean checkAndUpdatePackageMembership) { + NativeModuleRegistryBuilder nativeModuleRegistryBuilder = + new NativeModuleRegistryBuilder(reactContext, this); ReactMarker.logMarker(PROCESS_PACKAGES_START); @@ -1226,11 +1213,10 @@ public class ReactInstanceManager { } private void processPackage( - ReactPackage reactPackage, - NativeModuleRegistryBuilder nativeModuleRegistryBuilder) { + ReactPackage reactPackage, NativeModuleRegistryBuilder nativeModuleRegistryBuilder) { SystraceMessage.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "processPackage") - .arg("className", reactPackage.getClass().getSimpleName()) - .flush(); + .arg("className", reactPackage.getClass().getSimpleName()) + .flush(); if (reactPackage instanceof ReactPackageLogger) { ((ReactPackageLogger) reactPackage).startProcessPackage(); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManagerBuilder.java b/ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManagerBuilder.java index 47fc17b0ee7..9d0a82c30f9 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManagerBuilder.java +++ b/ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManagerBuilder.java @@ -28,9 +28,7 @@ import java.util.List; import java.util.Map; import javax.annotation.Nullable; -/** - * Builder class for {@link ReactInstanceManager} - */ +/** Builder class for {@link ReactInstanceManager} */ public class ReactInstanceManagerBuilder { private final List mPackages = new ArrayList<>(); @@ -55,37 +53,31 @@ public class ReactInstanceManagerBuilder { private @Nullable JSIModulePackage mJSIModulesPackage; private @Nullable Map mCustomPackagerCommandHandlers; - /* package protected */ ReactInstanceManagerBuilder() { - } + /* package protected */ ReactInstanceManagerBuilder() {} - /** - * Sets a provider of {@link UIImplementation}. - * Uses default provider if null is passed. - */ + /** Sets a provider of {@link UIImplementation}. Uses default provider if null is passed. */ public ReactInstanceManagerBuilder setUIImplementationProvider( - @Nullable UIImplementationProvider uiImplementationProvider) { + @Nullable UIImplementationProvider uiImplementationProvider) { mUIImplementationProvider = uiImplementationProvider; return this; } public ReactInstanceManagerBuilder setJSIModulesPackage( - @Nullable JSIModulePackage jsiModulePackage) { + @Nullable JSIModulePackage jsiModulePackage) { mJSIModulesPackage = jsiModulePackage; return this; } - /** - * Factory for desired implementation of JavaScriptExecutor. - */ + /** Factory for desired implementation of JavaScriptExecutor. */ public ReactInstanceManagerBuilder setJavaScriptExecutorFactory( - @Nullable JavaScriptExecutorFactory javaScriptExecutorFactory) { + @Nullable JavaScriptExecutorFactory javaScriptExecutorFactory) { mJavaScriptExecutorFactory = javaScriptExecutorFactory; return this; } /** - * Name of the JS bundle file to be loaded from application's raw assets. - * Example: {@code "index.android.js"} + * Name of the JS bundle file to be loaded from application's raw assets. Example: {@code + * "index.android.js"} */ public ReactInstanceManagerBuilder setBundleAssetName(String bundleAssetName) { mJSBundleAssetUrl = (bundleAssetName == null ? null : "assets://" + bundleAssetName); @@ -96,7 +88,7 @@ public class ReactInstanceManagerBuilder { /** * Path to the JS bundle file to be loaded from the file system. * - * Example: {@code "assets://index.android.js" or "/sdcard/main.jsbundle"} + *

Example: {@code "assets://index.android.js" or "/sdcard/main.jsbundle"} */ public ReactInstanceManagerBuilder setJSBundleFile(String jsBundleFile) { if (jsBundleFile.startsWith("assets://")) { @@ -108,10 +100,10 @@ public class ReactInstanceManagerBuilder { } /** - * Bundle loader to use when setting up JS environment. This supersedes - * prior invocations of {@link setJSBundleFile} and {@link setBundleAssetName}. + * Bundle loader to use when setting up JS environment. This supersedes prior invocations of + * {@link setJSBundleFile} and {@link setBundleAssetName}. * - * Example: {@code JSBundleLoader.createFileLoader(application, bundleFile)} + *

Example: {@code JSBundleLoader.createFileLoader(application, bundleFile)} */ public ReactInstanceManagerBuilder setJSBundleLoader(JSBundleLoader jsBundleLoader) { mJSBundleLoader = jsBundleLoader; @@ -120,12 +112,9 @@ public class ReactInstanceManagerBuilder { } /** - * Path to your app's main module on the packager server. This is used when - * reloading JS during development. All paths are relative to the root folder - * the packager is serving files from. - * Examples: - * {@code "index.android"} or - * {@code "subdirectory/index.android"} + * Path to your app's main module on the packager server. This is used when reloading JS during + * development. All paths are relative to the root folder the packager is serving files from. + * Examples: {@code "index.android"} or {@code "subdirectory/index.android"} */ public ReactInstanceManagerBuilder setJSMainModulePath(String jsMainModulePath) { mJSMainModulePath = jsMainModulePath; @@ -143,14 +132,12 @@ public class ReactInstanceManagerBuilder { } public ReactInstanceManagerBuilder setBridgeIdleDebugListener( - NotThreadSafeBridgeIdleDebugListener bridgeIdleDebugListener) { + NotThreadSafeBridgeIdleDebugListener bridgeIdleDebugListener) { mBridgeIdleDebugListener = bridgeIdleDebugListener; return this; } - /** - * Required. This must be your {@code Application} instance. - */ + /** Required. This must be your {@code Application} instance. */ public ReactInstanceManagerBuilder setApplication(Application application) { mApplication = application; return this; @@ -162,15 +149,15 @@ public class ReactInstanceManagerBuilder { } public ReactInstanceManagerBuilder setDefaultHardwareBackBtnHandler( - DefaultHardwareBackBtnHandler defaultHardwareBackBtnHandler) { + DefaultHardwareBackBtnHandler defaultHardwareBackBtnHandler) { mDefaultHardwareBackBtnHandler = defaultHardwareBackBtnHandler; return this; } /** - * When {@code true}, developer options such as JS reloading and debugging are enabled. - * Note you still have to call {@link #showDevOptionsDialog} to show the dev menu, - * e.g. when the device Menu button is pressed. + * When {@code true}, developer options such as JS reloading and debugging are enabled. Note you + * still have to call {@link #showDevOptionsDialog} to show the dev menu, e.g. when the device + * Menu button is pressed. */ public ReactInstanceManagerBuilder setUseDeveloperSupport(boolean useDeveloperSupport) { mUseDeveloperSupport = useDeveloperSupport; @@ -182,18 +169,18 @@ public class ReactInstanceManagerBuilder { * creation time, we wouldn't expect an onResume call until we get an onPause call. */ public ReactInstanceManagerBuilder setInitialLifecycleState( - LifecycleState initialLifecycleState) { + LifecycleState initialLifecycleState) { mInitialLifecycleState = initialLifecycleState; return this; } /** - * Set the exception handler for all native module calls. If not set, the default - * {@link DevSupportManager} will be used, which shows a redbox in dev mode and rethrows - * (crashes the app) in prod mode. + * Set the exception handler for all native module calls. If not set, the default {@link + * DevSupportManager} will be used, which shows a redbox in dev mode and rethrows (crashes the + * app) in prod mode. */ public ReactInstanceManagerBuilder setNativeModuleCallExceptionHandler( - NativeModuleCallExceptionHandler handler) { + NativeModuleCallExceptionHandler handler) { mNativeModuleCallExceptionHandler = handler; return this; } @@ -209,7 +196,7 @@ public class ReactInstanceManagerBuilder { } public ReactInstanceManagerBuilder setDevBundleDownloadListener( - @Nullable DevBundleDownloadListener listener) { + @Nullable DevBundleDownloadListener listener) { mDevBundleDownloadListener = listener; return this; } @@ -232,33 +219,32 @@ public class ReactInstanceManagerBuilder { } /** - * Instantiates a new {@link ReactInstanceManager}. - * Before calling {@code build}, the following must be called: + * Instantiates a new {@link ReactInstanceManager}. Before calling {@code build}, the following + * must be called: + * *

*/ public ReactInstanceManager build() { Assertions.assertNotNull( - mApplication, - "Application property has not been set with this builder"); + mApplication, "Application property has not been set with this builder"); if (mInitialLifecycleState == LifecycleState.RESUMED) { Assertions.assertNotNull( - mCurrentActivity, - "Activity needs to be set if initial lifecycle state is resumed"); + mCurrentActivity, "Activity needs to be set if initial lifecycle state is resumed"); } Assertions.assertCondition( - mUseDeveloperSupport || mJSBundleAssetUrl != null || mJSBundleLoader != null, - "JS Bundle File or Asset URL has to be provided when dev support is disabled"); + mUseDeveloperSupport || mJSBundleAssetUrl != null || mJSBundleLoader != null, + "JS Bundle File or Asset URL has to be provided when dev support is disabled"); Assertions.assertCondition( - mJSMainModulePath != null || mJSBundleAssetUrl != null || mJSBundleLoader != null, - "Either MainModulePath or JS Bundle File needs to be provided"); + mJSMainModulePath != null || mJSBundleAssetUrl != null || mJSBundleLoader != null, + "Either MainModulePath or JS Bundle File needs to be provided"); if (mUIImplementationProvider == null) { // create default UIImplementationProvider if the provided one is null. diff --git a/ReactAndroid/src/main/java/com/facebook/react/ReactInstancePackage.java b/ReactAndroid/src/main/java/com/facebook/react/ReactInstancePackage.java index 3095ff155bf..63f86e4d6b3 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/ReactInstancePackage.java +++ b/ReactAndroid/src/main/java/com/facebook/react/ReactInstancePackage.java @@ -1,31 +1,28 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react; -import java.util.List; - import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; +import java.util.List; /** - * A simple wrapper for ReactPackage to make it aware of its {@link ReactInstanceManager} - * when creating native modules. This is useful when the package needs to ask - * the instance manager for more information, like {@link DevSupportManager}. + * A simple wrapper for ReactPackage to make it aware of its {@link ReactInstanceManager} when + * creating native modules. This is useful when the package needs to ask the instance manager for + * more information, like {@link DevSupportManager}. * - * TODO(t11394819): Consolidate this with LazyReactPackage - * Use {@link ReactPackage} or {@link LazyReactPackage} and inject reactInstanceManager as a part of when plugins are initialized. + *

TODO(t11394819): Consolidate this with LazyReactPackage Use {@link ReactPackage} or {@link + * LazyReactPackage} and inject reactInstanceManager as a part of when plugins are initialized. */ @Deprecated public abstract class ReactInstancePackage implements ReactPackage { public abstract List createNativeModules( - ReactApplicationContext reactContext, - ReactInstanceManager reactInstanceManager); + ReactApplicationContext reactContext, ReactInstanceManager reactInstanceManager); @Override public List createNativeModules(ReactApplicationContext reactContext) { diff --git a/ReactAndroid/src/main/java/com/facebook/react/ReactNativeHost.java b/ReactAndroid/src/main/java/com/facebook/react/ReactNativeHost.java index d15abba7f76..fe0ec8b4192 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/ReactNativeHost.java +++ b/ReactAndroid/src/main/java/com/facebook/react/ReactNativeHost.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react; import android.app.Application; @@ -32,9 +31,7 @@ public abstract class ReactNativeHost { mApplication = application; } - /** - * Get the current {@link ReactInstanceManager} instance, or create one. - */ + /** Get the current {@link ReactInstanceManager} instance, or create one. */ public ReactInstanceManager getReactInstanceManager() { if (mReactInstanceManager == null) { ReactMarker.logMarker(ReactMarkerConstants.GET_REACT_INSTANCE_MANAGER_START); @@ -65,15 +62,16 @@ public abstract class ReactNativeHost { protected ReactInstanceManager createReactInstanceManager() { ReactMarker.logMarker(ReactMarkerConstants.BUILD_REACT_INSTANCE_MANAGER_START); - ReactInstanceManagerBuilder builder = ReactInstanceManager.builder() - .setApplication(mApplication) - .setJSMainModulePath(getJSMainModuleName()) - .setUseDeveloperSupport(getUseDeveloperSupport()) - .setRedBoxHandler(getRedBoxHandler()) - .setJavaScriptExecutorFactory(getJavaScriptExecutorFactory()) - .setUIImplementationProvider(getUIImplementationProvider()) - .setJSIModulesPackage(getJSIModulePackage()) - .setInitialLifecycleState(LifecycleState.BEFORE_CREATE); + ReactInstanceManagerBuilder builder = + ReactInstanceManager.builder() + .setApplication(mApplication) + .setJSMainModulePath(getJSMainModuleName()) + .setUseDeveloperSupport(getUseDeveloperSupport()) + .setRedBoxHandler(getRedBoxHandler()) + .setJavaScriptExecutorFactory(getJavaScriptExecutorFactory()) + .setUIImplementationProvider(getUIImplementationProvider()) + .setJSIModulesPackage(getJSIModulePackage()) + .setInitialLifecycleState(LifecycleState.BEFORE_CREATE); for (ReactPackage reactPackage : getPackages()) { builder.addPackage(reactPackage); @@ -90,17 +88,12 @@ public abstract class ReactNativeHost { return reactInstanceManager; } - /** - * Get the {@link RedBoxHandler} to send RedBox-related callbacks to. - */ + /** Get the {@link RedBoxHandler} to send RedBox-related callbacks to. */ protected @Nullable RedBoxHandler getRedBoxHandler() { return null; } - /** - * Get the {@link JavaScriptExecutorFactory}. Override this to use a custom - * Executor. - */ + /** Get the {@link JavaScriptExecutorFactory}. Override this to use a custom Executor. */ protected @Nullable JavaScriptExecutorFactory getJavaScriptExecutorFactory() { return null; } @@ -113,22 +106,20 @@ public abstract class ReactNativeHost { * Get the {@link UIImplementationProvider} to use. Override this method if you want to use a * custom UI implementation. * - * Note: this is very advanced functionality, in 99% of cases you don't need to override this. + *

Note: this is very advanced functionality, in 99% of cases you don't need to override this. */ protected UIImplementationProvider getUIImplementationProvider() { return new UIImplementationProvider(); } - protected @Nullable - JSIModulePackage getJSIModulePackage() { + protected @Nullable JSIModulePackage getJSIModulePackage() { return null; } /** - * Returns the name of the main module. Determines the URL used to fetch the JS bundle - * from the packager server. It is only used when dev support is enabled. - * This is the first file to be executed once the {@link ReactInstanceManager} is created. - * e.g. "index.android" + * Returns the name of the main module. Determines the URL used to fetch the JS bundle from the + * packager server. It is only used when dev support is enabled. This is the first file to be + * executed once the {@link ReactInstanceManager} is created. e.g. "index.android" */ protected String getJSMainModuleName() { return "index.android"; @@ -136,9 +127,8 @@ public abstract class ReactNativeHost { /** * Returns a custom path of the bundle file. This is used in cases the bundle should be loaded - * from a custom path. By default it is loaded from Android assets, from a path specified - * by {@link getBundleAssetName}. - * e.g. "file://sdcard/myapp_cache/index.android.bundle" + * from a custom path. By default it is loaded from Android assets, from a path specified by + * {@link getBundleAssetName}. e.g. "file://sdcard/myapp_cache/index.android.bundle" */ protected @Nullable String getJSBundleFile() { return null; @@ -146,24 +136,20 @@ public abstract class ReactNativeHost { /** * Returns the name of the bundle in assets. If this is null, and no file path is specified for - * the bundle, the app will only work with {@code getUseDeveloperSupport} enabled and will - * always try to load the JS bundle from the packager server. - * e.g. "index.android.bundle" + * the bundle, the app will only work with {@code getUseDeveloperSupport} enabled and will always + * try to load the JS bundle from the packager server. e.g. "index.android.bundle" */ protected @Nullable String getBundleAssetName() { return "index.android.bundle"; } - /** - * Returns whether dev mode should be enabled. This enables e.g. the dev menu. - */ + /** Returns whether dev mode should be enabled. This enables e.g. the dev menu. */ public abstract boolean getUseDeveloperSupport(); /** - * Returns a list of {@link ReactPackage} used by the app. - * You'll most likely want to return at least the {@code MainReactPackage}. - * If your app uses additional views or modules besides the default ones, - * you'll want to include more packages here. + * Returns a list of {@link ReactPackage} used by the app. You'll most likely want to return at + * least the {@code MainReactPackage}. If your app uses additional views or modules besides the + * default ones, you'll want to include more packages here. */ protected abstract List getPackages(); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/ReactPackage.java b/ReactAndroid/src/main/java/com/facebook/react/ReactPackage.java index 7bf8569d7bc..047455dadf2 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/ReactPackage.java +++ b/ReactAndroid/src/main/java/com/facebook/react/ReactPackage.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react; import com.facebook.react.bridge.NativeModule; @@ -12,21 +11,18 @@ import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.uimanager.UIManagerModule; import com.facebook.react.uimanager.ViewManager; import java.util.List; - import javax.annotation.Nonnull; /** * Main interface for providing additional capabilities to the catalyst framework by couple of - * different means: - * 1) Registering new native modules - * 2) Registering new JS modules that may be accessed from native modules or from other parts of the - * native code (requiring JS modules from the package doesn't mean it will automatically be included - * as a part of the JS bundle, so there should be a corresponding piece of code on JS side that will - * require implementation of that JS module so that it gets bundled) - * 3) Registering custom native views (view managers) and custom event types - * 4) Registering natively packaged assets/resources (e.g. images) exposed to JS + * different means: 1) Registering new native modules 2) Registering new JS modules that may be + * accessed from native modules or from other parts of the native code (requiring JS modules from + * the package doesn't mean it will automatically be included as a part of the JS bundle, so there + * should be a corresponding piece of code on JS side that will require implementation of that JS + * module so that it gets bundled) 3) Registering custom native views (view managers) and custom + * event types 4) Registering natively packaged assets/resources (e.g. images) exposed to JS * - * TODO(6788500, 6788507): Implement support for adding custom views, events and resources + *

TODO(6788500, 6788507): Implement support for adding custom views, events and resources */ public interface ReactPackage { @@ -37,9 +33,7 @@ public interface ReactPackage { @Nonnull List createNativeModules(@Nonnull ReactApplicationContext reactContext); - /** - * @return a list of view managers that should be registered with {@link UIManagerModule} - */ + /** @return a list of view managers that should be registered with {@link UIManagerModule} */ @Nonnull List createViewManagers(@Nonnull ReactApplicationContext reactContext); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/ReactPackageHelper.java b/ReactAndroid/src/main/java/com/facebook/react/ReactPackageHelper.java index 105f13ff883..cb750d5bb32 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/ReactPackageHelper.java +++ b/ReactAndroid/src/main/java/com/facebook/react/ReactPackageHelper.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react; import androidx.annotation.NonNull; diff --git a/ReactAndroid/src/main/java/com/facebook/react/ReactPackageLogger.java b/ReactAndroid/src/main/java/com/facebook/react/ReactPackageLogger.java index 38b2f2bddb6..526e4d4739c 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/ReactPackageLogger.java +++ b/ReactAndroid/src/main/java/com/facebook/react/ReactPackageLogger.java @@ -5,11 +5,10 @@ package com.facebook.react; -/** - * Interface for the bridge to call for TTI start and end markers. - */ +/** Interface for the bridge to call for TTI start and end markers. */ public interface ReactPackageLogger { void startProcessPackage(); + void endProcessPackage(); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/ReactRootView.java b/ReactAndroid/src/main/java/com/facebook/react/ReactRootView.java index 1a98fd22479..50703ed524e 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/ReactRootView.java +++ b/ReactAndroid/src/main/java/com/facebook/react/ReactRootView.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react; import static com.facebook.react.uimanager.common.UIManagerType.DEFAULT; @@ -46,8 +45,8 @@ import com.facebook.react.uimanager.DisplayMetricsHolder; import com.facebook.react.uimanager.IllegalViewOperationException; import com.facebook.react.uimanager.JSTouchDispatcher; import com.facebook.react.uimanager.PixelUtil; -import com.facebook.react.uimanager.RootView; import com.facebook.react.uimanager.ReactRoot; +import com.facebook.react.uimanager.RootView; import com.facebook.react.uimanager.UIManagerHelper; import com.facebook.react.uimanager.UIManagerModule; import com.facebook.react.uimanager.common.UIManagerType; @@ -62,20 +61,16 @@ import javax.annotation.Nullable; * ViewGroup#onInterceptTouchEvent} method in order to be notified about the events for all of its * children and it's also overriding {@link ViewGroup#requestDisallowInterceptTouchEvent} to make * sure that {@link ViewGroup#onInterceptTouchEvent} will get events even when some child view start - * intercepting it. In case when no child view is interested in handling some particular touch event, - * this view's {@link View#onTouchEvent} will still return true in order to be notified about all - * subsequent touch events related to that gesture (in case when JS code wants to handle that + * intercepting it. In case when no child view is interested in handling some particular touch + * event, this view's {@link View#onTouchEvent} will still return true in order to be notified about + * all subsequent touch events related to that gesture (in case when JS code wants to handle that * gesture). */ public class ReactRootView extends FrameLayout implements RootView, ReactRoot { - /** - * Listener interface for react root view events - */ + /** Listener interface for react root view events */ public interface ReactRootViewEventListener { - /** - * Called when the react context is attached to a ReactRootView. - */ + /** Called when the react context is attached to a ReactRootView. */ void onAttachedToReactInstance(ReactRootView rootView); } @@ -89,7 +84,8 @@ public class ReactRootView extends FrameLayout implements RootView, ReactRoot { private boolean mIsAttachedToInstance; private boolean mShouldLogContentAppeared; private @Nullable JSTouchDispatcher mJSTouchDispatcher; - private final ReactAndroidHWInputDeviceHelper mAndroidHWInputDeviceHelper = new ReactAndroidHWInputDeviceHelper(this); + private final ReactAndroidHWInputDeviceHelper mAndroidHWInputDeviceHelper = + new ReactAndroidHWInputDeviceHelper(this); private boolean mWasMeasured = false; private int mWidthMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); private int mHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); @@ -135,8 +131,8 @@ public class ReactRootView extends FrameLayout implements RootView, ReactRoot { Systrace.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "ReactRootView.onMeasure"); try { - boolean measureSpecsUpdated = widthMeasureSpec != mWidthMeasureSpec || - heightMeasureSpec != mHeightMeasureSpec; + boolean measureSpecsUpdated = + widthMeasureSpec != mWidthMeasureSpec || heightMeasureSpec != mHeightMeasureSpec; mWidthMeasureSpec = widthMeasureSpec; mHeightMeasureSpec = heightMeasureSpec; @@ -189,21 +185,22 @@ public class ReactRootView extends FrameLayout implements RootView, ReactRoot { @Override public void onChildStartedNativeGesture(MotionEvent androidEvent) { - if (mReactInstanceManager == null || !mIsAttachedToInstance || - mReactInstanceManager.getCurrentReactContext() == null) { + if (mReactInstanceManager == null + || !mIsAttachedToInstance + || mReactInstanceManager.getCurrentReactContext() == null) { FLog.w( - ReactConstants.TAG, - "Unable to dispatch touch to JS as the catalyst instance has not been attached"); + ReactConstants.TAG, + "Unable to dispatch touch to JS as the catalyst instance has not been attached"); return; } if (mJSTouchDispatcher == null) { FLog.w( - ReactConstants.TAG, - "Unable to dispatch touch to JS before the dispatcher is available"); + ReactConstants.TAG, "Unable to dispatch touch to JS before the dispatcher is available"); return; } ReactContext reactContext = mReactInstanceManager.getCurrentReactContext(); - EventDispatcher eventDispatcher = reactContext.getNativeModule(UIManagerModule.class).getEventDispatcher(); + EventDispatcher eventDispatcher = + reactContext.getNativeModule(UIManagerModule.class).getEventDispatcher(); mJSTouchDispatcher.onChildStartedNativeGesture(androidEvent, eventDispatcher); } @@ -235,11 +232,12 @@ public class ReactRootView extends FrameLayout implements RootView, ReactRoot { @Override public boolean dispatchKeyEvent(KeyEvent ev) { - if (mReactInstanceManager == null || !mIsAttachedToInstance || - mReactInstanceManager.getCurrentReactContext() == null) { + if (mReactInstanceManager == null + || !mIsAttachedToInstance + || mReactInstanceManager.getCurrentReactContext() == null) { FLog.w( - ReactConstants.TAG, - "Unable to handle key event as the catalyst instance has not been attached"); + ReactConstants.TAG, + "Unable to handle key event as the catalyst instance has not been attached"); return super.dispatchKeyEvent(ev); } mAndroidHWInputDeviceHelper.handleKeyEvent(ev); @@ -248,11 +246,12 @@ public class ReactRootView extends FrameLayout implements RootView, ReactRoot { @Override protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) { - if (mReactInstanceManager == null || !mIsAttachedToInstance || - mReactInstanceManager.getCurrentReactContext() == null) { + if (mReactInstanceManager == null + || !mIsAttachedToInstance + || mReactInstanceManager.getCurrentReactContext() == null) { FLog.w( - ReactConstants.TAG, - "Unable to handle focus changed event as the catalyst instance has not been attached"); + ReactConstants.TAG, + "Unable to handle focus changed event as the catalyst instance has not been attached"); super.onFocusChanged(gainFocus, direction, previouslyFocusedRect); return; } @@ -262,11 +261,12 @@ public class ReactRootView extends FrameLayout implements RootView, ReactRoot { @Override public void requestChildFocus(View child, View focused) { - if (mReactInstanceManager == null || !mIsAttachedToInstance || - mReactInstanceManager.getCurrentReactContext() == null) { + if (mReactInstanceManager == null + || !mIsAttachedToInstance + || mReactInstanceManager.getCurrentReactContext() == null) { FLog.w( - ReactConstants.TAG, - "Unable to handle child focus changed event as the catalyst instance has not been attached"); + ReactConstants.TAG, + "Unable to handle child focus changed event as the catalyst instance has not been attached"); super.requestChildFocus(child, focused); return; } @@ -275,21 +275,22 @@ public class ReactRootView extends FrameLayout implements RootView, ReactRoot { } private void dispatchJSTouchEvent(MotionEvent event) { - if (mReactInstanceManager == null || !mIsAttachedToInstance || - mReactInstanceManager.getCurrentReactContext() == null) { + if (mReactInstanceManager == null + || !mIsAttachedToInstance + || mReactInstanceManager.getCurrentReactContext() == null) { FLog.w( - ReactConstants.TAG, - "Unable to dispatch touch to JS as the catalyst instance has not been attached"); + ReactConstants.TAG, + "Unable to dispatch touch to JS as the catalyst instance has not been attached"); return; } if (mJSTouchDispatcher == null) { FLog.w( - ReactConstants.TAG, - "Unable to dispatch touch to JS before the dispatcher is available"); + ReactConstants.TAG, "Unable to dispatch touch to JS before the dispatcher is available"); return; } ReactContext reactContext = mReactInstanceManager.getCurrentReactContext(); - EventDispatcher eventDispatcher = reactContext.getNativeModule(UIManagerModule.class).getEventDispatcher(); + EventDispatcher eventDispatcher = + reactContext.getNativeModule(UIManagerModule.class).getEventDispatcher(); mJSTouchDispatcher.handleTouchEvent(event, eventDispatcher); } @@ -349,24 +350,23 @@ public class ReactRootView extends FrameLayout implements RootView, ReactRoot { return this; } - /** - * {@see #startReactApplication(ReactInstanceManager, String, android.os.Bundle)} - */ + /** {@see #startReactApplication(ReactInstanceManager, String, android.os.Bundle)} */ public void startReactApplication(ReactInstanceManager reactInstanceManager, String moduleName) { startReactApplication(reactInstanceManager, moduleName, null); } - /** - * {@see #startReactApplication(ReactInstanceManager, String, android.os.Bundle, String)} - */ - public void startReactApplication(ReactInstanceManager reactInstanceManager, String moduleName, @Nullable Bundle initialProperties) { + /** {@see #startReactApplication(ReactInstanceManager, String, android.os.Bundle, String)} */ + public void startReactApplication( + ReactInstanceManager reactInstanceManager, + String moduleName, + @Nullable Bundle initialProperties) { startReactApplication(reactInstanceManager, moduleName, initialProperties, null); } /** * Schedule rendering of the react component rendered by the JS application from the given JS - * module (@{param moduleName}) using provided {@param reactInstanceManager} to attach to the - * JS context of that manager. Extra parameter {@param launchOptions} can be used to pass initial + * module (@{param moduleName}) using provided {@param reactInstanceManager} to attach to the JS + * context of that manager. Extra parameter {@param launchOptions} can be used to pass initial * properties for the react component. */ public void startReactApplication( @@ -382,8 +382,8 @@ public class ReactRootView extends FrameLayout implements RootView, ReactRoot { // here as it may be deallocated in native after passing via JNI bridge, but we want to reuse // it in the case of re-creating the catalyst instance Assertions.assertCondition( - mReactInstanceManager == null, - "This root view has already been attached to a catalyst instance manager"); + mReactInstanceManager == null, + "This root view has already been attached to a catalyst instance manager"); mReactInstanceManager = reactInstanceManager; mJSModuleName = moduleName; @@ -429,7 +429,7 @@ public class ReactRootView extends FrameLayout implements RootView, ReactRoot { if (reactApplicationContext != null) { UIManagerHelper.getUIManager(reactApplicationContext, getUIManagerType()) - .updateRootLayoutSpecs(getRootViewTag(), widthMeasureSpec, heightMeasureSpec); + .updateRootLayoutSpecs(getRootViewTag(), widthMeasureSpec, heightMeasureSpec); } } @@ -450,7 +450,7 @@ public class ReactRootView extends FrameLayout implements RootView, ReactRoot { @Override public void onStage(int stage) { - switch(stage) { + switch (stage) { case ReactStage.ON_ATTACH_TO_INSTANCE: onAttachedToReactInstance(); break; @@ -498,51 +498,51 @@ public class ReactRootView extends FrameLayout implements RootView, ReactRoot { } /** - * Calls into JS to start the React application. Can be called multiple times with the - * same rootTag, which will re-render the application from the root. + * Calls into JS to start the React application. Can be called multiple times with the same + * rootTag, which will re-render the application from the root. */ @Override public void runApplication() { - Systrace.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "ReactRootView.runApplication"); - try { - if (mReactInstanceManager == null || !mIsAttachedToInstance) { - return; - } - - ReactContext reactContext = mReactInstanceManager.getCurrentReactContext(); - if (reactContext == null) { - return; - } - - CatalystInstance catalystInstance = reactContext.getCatalystInstance(); - String jsAppModuleName = getJSModuleName(); - - if (mUseSurface) { - // TODO call surface's runApplication - } else { - if (mWasMeasured) { - updateRootLayoutSpecs(mWidthMeasureSpec, mHeightMeasureSpec); - } - - WritableNativeMap appParams = new WritableNativeMap(); - appParams.putDouble("rootTag", getRootViewTag()); - @Nullable Bundle appProperties = getAppProperties(); - if (appProperties != null) { - appParams.putMap("initialProps", Arguments.fromBundle(appProperties)); - } - - mShouldLogContentAppeared = true; - - catalystInstance.getJSModule(AppRegistry.class).runApplication(jsAppModuleName, appParams); - } - } finally { - Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE); + Systrace.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "ReactRootView.runApplication"); + try { + if (mReactInstanceManager == null || !mIsAttachedToInstance) { + return; } + + ReactContext reactContext = mReactInstanceManager.getCurrentReactContext(); + if (reactContext == null) { + return; + } + + CatalystInstance catalystInstance = reactContext.getCatalystInstance(); + String jsAppModuleName = getJSModuleName(); + + if (mUseSurface) { + // TODO call surface's runApplication + } else { + if (mWasMeasured) { + updateRootLayoutSpecs(mWidthMeasureSpec, mHeightMeasureSpec); + } + + WritableNativeMap appParams = new WritableNativeMap(); + appParams.putDouble("rootTag", getRootViewTag()); + @Nullable Bundle appProperties = getAppProperties(); + if (appProperties != null) { + appParams.putMap("initialProps", Arguments.fromBundle(appProperties)); + } + + mShouldLogContentAppeared = true; + + catalystInstance.getJSModule(AppRegistry.class).runApplication(jsAppModuleName, appParams); + } + } finally { + Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE); + } } /** - * Is used by unit test to setup mIsAttachedToWindow flags, that will let this - * view to be properly attached to catalyst instance by startReactApplication call + * Is used by unit test to setup mIsAttachedToWindow flags, that will let this view to be properly + * attached to catalyst instance by startReactApplication call */ @VisibleForTesting /* package */ void simulateAttachForTesting() { @@ -576,12 +576,12 @@ public class ReactRootView extends FrameLayout implements RootView, ReactRoot { protected void finalize() throws Throwable { super.finalize(); Assertions.assertCondition( - !mIsAttachedToInstance, - "The application this ReactRootView was rendering was not unmounted before the " + - "ReactRootView was garbage collected. This usually means that your application is " + - "leaking large amounts of memory. To solve this, make sure to call " + - "ReactRootView#unmountReactApplication in the onDestroy() of your hosting Activity or in " + - "the onDestroyView() of your hosting Fragment."); + !mIsAttachedToInstance, + "The application this ReactRootView was rendering was not unmounted before the " + + "ReactRootView was garbage collected. This usually means that your application is " + + "leaking large amounts of memory. To solve this, make sure to call " + + "ReactRootView#unmountReactApplication in the onDestroy() of your hosting Activity or in " + + "the onDestroyView() of your hosting Fragment."); } public int getRootViewTag() { @@ -594,9 +594,8 @@ public class ReactRootView extends FrameLayout implements RootView, ReactRoot { @Override public void handleException(final Throwable t) { - if (mReactInstanceManager == null - || mReactInstanceManager.getCurrentReactContext() == null) { - throw new RuntimeException(t); + if (mReactInstanceManager == null || mReactInstanceManager.getCurrentReactContext() == null) { + throw new RuntimeException(t); } Exception e = new IllegalViewOperationException(t.getMessage(), this, t); @@ -619,9 +618,10 @@ public class ReactRootView extends FrameLayout implements RootView, ReactRoot { /* package */ void sendEvent(String eventName, @Nullable WritableMap params) { if (mReactInstanceManager != null) { - mReactInstanceManager.getCurrentReactContext() - .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) - .emit(eventName, params); + mReactInstanceManager + .getCurrentReactContext() + .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) + .emit(eventName, params); } } @@ -642,8 +642,9 @@ public class ReactRootView extends FrameLayout implements RootView, ReactRoot { @Override public void onGlobalLayout() { - if (mReactInstanceManager == null || !mIsAttachedToInstance || - mReactInstanceManager.getCurrentReactContext() == null) { + if (mReactInstanceManager == null + || !mIsAttachedToInstance + || mReactInstanceManager.getCurrentReactContext() == null) { return; } checkForKeyboardEvents(); @@ -654,41 +655,40 @@ public class ReactRootView extends FrameLayout implements RootView, ReactRoot { private void checkForKeyboardEvents() { getRootView().getWindowVisibleDisplayFrame(mVisibleViewArea); final int heightDiff = - DisplayMetricsHolder.getWindowDisplayMetrics().heightPixels - mVisibleViewArea.bottom; + DisplayMetricsHolder.getWindowDisplayMetrics().heightPixels - mVisibleViewArea.bottom; boolean isKeyboardShowingOrKeyboardHeightChanged = - mKeyboardHeight != heightDiff && heightDiff > mMinKeyboardHeightDetected; + mKeyboardHeight != heightDiff && heightDiff > mMinKeyboardHeightDetected; if (isKeyboardShowingOrKeyboardHeightChanged) { mKeyboardHeight = heightDiff; - sendEvent("keyboardDidShow", - createKeyboardEventPayload( - PixelUtil.toDIPFromPixel(mVisibleViewArea.bottom), - PixelUtil.toDIPFromPixel(mVisibleViewArea.left), - PixelUtil.toDIPFromPixel(mVisibleViewArea.width()), - PixelUtil.toDIPFromPixel(mKeyboardHeight)) - ); + sendEvent( + "keyboardDidShow", + createKeyboardEventPayload( + PixelUtil.toDIPFromPixel(mVisibleViewArea.bottom), + PixelUtil.toDIPFromPixel(mVisibleViewArea.left), + PixelUtil.toDIPFromPixel(mVisibleViewArea.width()), + PixelUtil.toDIPFromPixel(mKeyboardHeight))); return; } - boolean isKeyboardHidden = - mKeyboardHeight != 0 && heightDiff <= mMinKeyboardHeightDetected; + boolean isKeyboardHidden = mKeyboardHeight != 0 && heightDiff <= mMinKeyboardHeightDetected; if (isKeyboardHidden) { mKeyboardHeight = 0; - sendEvent("keyboardDidHide", - createKeyboardEventPayload( - PixelUtil.toDIPFromPixel(mVisibleViewArea.height()), - 0, - PixelUtil.toDIPFromPixel(mVisibleViewArea.width()), - 0 - ) - ); + sendEvent( + "keyboardDidHide", + createKeyboardEventPayload( + PixelUtil.toDIPFromPixel(mVisibleViewArea.height()), + 0, + PixelUtil.toDIPFromPixel(mVisibleViewArea.width()), + 0)); } } private void checkForDeviceOrientationChanges() { final int rotation = - ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE)) - .getDefaultDisplay().getRotation(); + ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE)) + .getDefaultDisplay() + .getRotation(); if (mDeviceRotation == rotation) { return; } @@ -699,9 +699,10 @@ public class ReactRootView extends FrameLayout implements RootView, ReactRoot { private void checkForDeviceDimensionsChanges() { // Get current display metrics. DisplayMetricsHolder.initDisplayMetrics(getContext()); - // Check changes to both window and screen display metrics since they may not update at the same time. - if (!areMetricsEqual(mWindowMetrics, DisplayMetricsHolder.getWindowDisplayMetrics()) || - !areMetricsEqual(mScreenMetrics, DisplayMetricsHolder.getScreenDisplayMetrics())) { + // Check changes to both window and screen display metrics since they may not update at the + // same time. + if (!areMetricsEqual(mWindowMetrics, DisplayMetricsHolder.getWindowDisplayMetrics()) + || !areMetricsEqual(mScreenMetrics, DisplayMetricsHolder.getScreenDisplayMetrics())) { mWindowMetrics.setTo(DisplayMetricsHolder.getWindowDisplayMetrics()); mScreenMetrics.setTo(DisplayMetricsHolder.getScreenDisplayMetrics()); emitUpdateDimensionsEvent(); @@ -714,13 +715,13 @@ public class ReactRootView extends FrameLayout implements RootView, ReactRoot { } else { // DisplayMetrics didn't have an equals method before API 17. // Check all public fields manually. - return displayMetrics.widthPixels == otherMetrics.widthPixels && - displayMetrics.heightPixels == otherMetrics.heightPixels && - displayMetrics.density == otherMetrics.density && - displayMetrics.densityDpi == otherMetrics.densityDpi && - displayMetrics.scaledDensity == otherMetrics.scaledDensity && - displayMetrics.xdpi == otherMetrics.xdpi && - displayMetrics.ydpi == otherMetrics.ydpi; + return displayMetrics.widthPixels == otherMetrics.widthPixels + && displayMetrics.heightPixels == otherMetrics.heightPixels + && displayMetrics.density == otherMetrics.density + && displayMetrics.densityDpi == otherMetrics.densityDpi + && displayMetrics.scaledDensity == otherMetrics.scaledDensity + && displayMetrics.xdpi == otherMetrics.xdpi + && displayMetrics.ydpi == otherMetrics.ydpi; } } @@ -766,7 +767,8 @@ public class ReactRootView extends FrameLayout implements RootView, ReactRoot { .emitUpdateDimensionsEvent(); } - private WritableMap createKeyboardEventPayload(double screenY, double screenX, double width, double height) { + private WritableMap createKeyboardEventPayload( + double screenY, double screenX, double width, double height) { WritableMap keyboardEventParams = Arguments.createMap(); WritableMap endCoordinates = Arguments.createMap(); diff --git a/ReactAndroid/src/main/java/com/facebook/react/TurboReactPackage.java b/ReactAndroid/src/main/java/com/facebook/react/TurboReactPackage.java index dfe86a3572f..1f72da8bb3c 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/TurboReactPackage.java +++ b/ReactAndroid/src/main/java/com/facebook/react/TurboReactPackage.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react; import androidx.annotation.NonNull; diff --git a/ReactAndroid/src/main/java/com/facebook/react/ViewManagerOnDemandReactPackage.java b/ReactAndroid/src/main/java/com/facebook/react/ViewManagerOnDemandReactPackage.java index c8bd730bb0c..bdb1d2cff76 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/ViewManagerOnDemandReactPackage.java +++ b/ReactAndroid/src/main/java/com/facebook/react/ViewManagerOnDemandReactPackage.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react; import com.facebook.react.bridge.ReactApplicationContext; @@ -17,7 +16,8 @@ public interface ViewManagerOnDemandReactPackage { * Provides a list of names of ViewManagers with which these modules can be accessed from JS. * Typically, this is ViewManager.getName(). */ - @Nullable List getViewManagerNames(ReactApplicationContext reactContext); + @Nullable + List getViewManagerNames(ReactApplicationContext reactContext); /** * Creates and returns a ViewManager with a specific name {@param viewManagerName}. It's up to an * implementing package how to interpret the name. diff --git a/ReactAndroid/src/main/java/com/facebook/react/animated/AdditionAnimatedNode.java b/ReactAndroid/src/main/java/com/facebook/react/animated/AdditionAnimatedNode.java index 221ba9e5363..c2112ac51bc 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/animated/AdditionAnimatedNode.java +++ b/ReactAndroid/src/main/java/com/facebook/react/animated/AdditionAnimatedNode.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.animated; import com.facebook.react.bridge.JSApplicationCausedNativeException; @@ -21,8 +20,7 @@ import com.facebook.react.bridge.ReadableMap; private final int[] mInputNodes; public AdditionAnimatedNode( - ReadableMap config, - NativeAnimatedNodesManager nativeAnimatedNodesManager) { + ReadableMap config, NativeAnimatedNodesManager nativeAnimatedNodesManager) { mNativeAnimatedNodesManager = nativeAnimatedNodesManager; ReadableArray inputNodes = config.getArray("input"); mInputNodes = new int[inputNodes.size()]; @@ -39,8 +37,8 @@ import com.facebook.react.bridge.ReadableMap; if (animatedNode != null && animatedNode instanceof ValueAnimatedNode) { mValue += ((ValueAnimatedNode) animatedNode).getValue(); } else { - throw new JSApplicationCausedNativeException("Illegal node ID set as an input for " + - "Animated.Add node"); + throw new JSApplicationCausedNativeException( + "Illegal node ID set as an input for " + "Animated.Add node"); } } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/animated/AnimatedNode.java b/ReactAndroid/src/main/java/com/facebook/react/animated/AnimatedNode.java index c4493b59b90..956c7695018 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/animated/AnimatedNode.java +++ b/ReactAndroid/src/main/java/com/facebook/react/animated/AnimatedNode.java @@ -1,22 +1,17 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.animated; import com.facebook.infer.annotation.Assertions; - import java.util.ArrayList; import java.util.List; - import javax.annotation.Nullable; -/** - * Base class for all Animated.js library node types that can be created on the "native" side. - */ +/** Base class for all Animated.js library node types that can be created on the "native" side. */ /*package*/ abstract class AnimatedNode { public static final int INITIAL_BFS_COLOR = 0; @@ -46,24 +41,19 @@ import javax.annotation.Nullable; /** * Subclasses may want to override this method in order to store a reference to the parent of a - * given node that can then be used to calculate current node's value in {@link #update}. - * In that case it is important to also override {@link #onDetachedFromNode} to clear that - * reference once current node gets detached. + * given node that can then be used to calculate current node's value in {@link #update}. In that + * case it is important to also override {@link #onDetachedFromNode} to clear that reference once + * current node gets detached. */ - public void onAttachedToNode(AnimatedNode parent) { - } + public void onAttachedToNode(AnimatedNode parent) {} - /** - * See {@link #onAttachedToNode} - */ - public void onDetachedFromNode(AnimatedNode parent) { - } + /** See {@link #onAttachedToNode} */ + public void onDetachedFromNode(AnimatedNode parent) {} /** * This method will be run on each node at most once every repetition of the animation loop. It * will be executed on a node only when all the node's parent has already been updated. Therefore * it can be used to calculate node's value. */ - public void update() { - } + public void update() {} } diff --git a/ReactAndroid/src/main/java/com/facebook/react/animated/AnimatedNodeValueListener.java b/ReactAndroid/src/main/java/com/facebook/react/animated/AnimatedNodeValueListener.java index 6c92345f11b..39b2a43ee7a 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/animated/AnimatedNodeValueListener.java +++ b/ReactAndroid/src/main/java/com/facebook/react/animated/AnimatedNodeValueListener.java @@ -1,15 +1,12 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.animated; -/** - * Interface used to listen to {@link ValueAnimatedNode} updates. - */ +/** Interface used to listen to {@link ValueAnimatedNode} updates. */ public interface AnimatedNodeValueListener { void onValueUpdate(double value); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/animated/AnimationDriver.java b/ReactAndroid/src/main/java/com/facebook/react/animated/AnimationDriver.java index 894a6d557f1..5900e28b28d 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/animated/AnimationDriver.java +++ b/ReactAndroid/src/main/java/com/facebook/react/animated/AnimationDriver.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.animated; import com.facebook.react.bridge.Callback; @@ -36,6 +35,6 @@ import com.facebook.react.bridge.ReadableMap; */ public void resetConfig(ReadableMap config) { throw new JSApplicationCausedNativeException( - "Animation config for " + getClass().getSimpleName() + " cannot be reset"); + "Animation config for " + getClass().getSimpleName() + " cannot be reset"); } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/animated/DecayAnimation.java b/ReactAndroid/src/main/java/com/facebook/react/animated/DecayAnimation.java index 1781cb83875..b6e043f8240 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/animated/DecayAnimation.java +++ b/ReactAndroid/src/main/java/com/facebook/react/animated/DecayAnimation.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.animated; import com.facebook.react.bridge.ReadableMap; @@ -54,9 +53,10 @@ public class DecayAnimation extends AnimationDriver { mLastValue = mAnimatedValue.mValue; } - final double value = mFromValue + - (mVelocity / (1 - mDeceleration)) * - (1 - Math.exp(-(1 - mDeceleration) * (frameTimeMillis - mStartFrameTimeMillis))); + final double value = + mFromValue + + (mVelocity / (1 - mDeceleration)) + * (1 - Math.exp(-(1 - mDeceleration) * (frameTimeMillis - mStartFrameTimeMillis))); if (Math.abs(mLastValue - value) < 0.1) { diff --git a/ReactAndroid/src/main/java/com/facebook/react/animated/DiffClampAnimatedNode.java b/ReactAndroid/src/main/java/com/facebook/react/animated/DiffClampAnimatedNode.java index 7f077a6610c..b40991d07f4 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/animated/DiffClampAnimatedNode.java +++ b/ReactAndroid/src/main/java/com/facebook/react/animated/DiffClampAnimatedNode.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.animated; import com.facebook.react.bridge.JSApplicationCausedNativeException; @@ -19,8 +18,7 @@ import com.facebook.react.bridge.ReadableMap; private double mLastValue; public DiffClampAnimatedNode( - ReadableMap config, - NativeAnimatedNodesManager nativeAnimatedNodesManager) { + ReadableMap config, NativeAnimatedNodesManager nativeAnimatedNodesManager) { mNativeAnimatedNodesManager = nativeAnimatedNodesManager; mInputNodeTag = config.getInt("input"); mMin = config.getDouble("min"); @@ -41,9 +39,8 @@ import com.facebook.react.bridge.ReadableMap; private double getInputNodeValue() { AnimatedNode animatedNode = mNativeAnimatedNodesManager.getNodeById(mInputNodeTag); if (animatedNode == null || !(animatedNode instanceof ValueAnimatedNode)) { - throw new JSApplicationCausedNativeException("Illegal node ID set as an input for " + - "Animated.DiffClamp node"); - + throw new JSApplicationCausedNativeException( + "Illegal node ID set as an input for " + "Animated.DiffClamp node"); } return ((ValueAnimatedNode) animatedNode).getValue(); diff --git a/ReactAndroid/src/main/java/com/facebook/react/animated/DivisionAnimatedNode.java b/ReactAndroid/src/main/java/com/facebook/react/animated/DivisionAnimatedNode.java index 96e96059e88..7d403a0f90f 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/animated/DivisionAnimatedNode.java +++ b/ReactAndroid/src/main/java/com/facebook/react/animated/DivisionAnimatedNode.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.animated; import com.facebook.react.bridge.JSApplicationCausedNativeException; @@ -12,8 +11,8 @@ import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableMap; /** - * Animated node which takes two or more value node as an input and outputs an in-order - * division of their values. + * Animated node which takes two or more value node as an input and outputs an in-order division of + * their values. */ /*package*/ class DivisionAnimatedNode extends ValueAnimatedNode { @@ -21,8 +20,7 @@ import com.facebook.react.bridge.ReadableMap; private final int[] mInputNodes; public DivisionAnimatedNode( - ReadableMap config, - NativeAnimatedNodesManager nativeAnimatedNodesManager) { + ReadableMap config, NativeAnimatedNodesManager nativeAnimatedNodesManager) { mNativeAnimatedNodesManager = nativeAnimatedNodesManager; ReadableArray inputNodes = config.getArray("input"); mInputNodes = new int[inputNodes.size()]; @@ -42,13 +40,13 @@ import com.facebook.react.bridge.ReadableMap; continue; } if (value == 0) { - throw new JSApplicationCausedNativeException("Detected a division by zero in " + - "Animated.divide node"); + throw new JSApplicationCausedNativeException( + "Detected a division by zero in " + "Animated.divide node"); } mValue /= value; } else { - throw new JSApplicationCausedNativeException("Illegal node ID set as an input for " + - "Animated.divide node"); + throw new JSApplicationCausedNativeException( + "Illegal node ID set as an input for " + "Animated.divide node"); } } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/animated/EventAnimationDriver.java b/ReactAndroid/src/main/java/com/facebook/react/animated/EventAnimationDriver.java index 7e2c46eef26..169808e04c6 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/animated/EventAnimationDriver.java +++ b/ReactAndroid/src/main/java/com/facebook/react/animated/EventAnimationDriver.java @@ -1,24 +1,19 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.animated; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.WritableArray; import com.facebook.react.bridge.WritableMap; import com.facebook.react.uimanager.events.RCTEventEmitter; - import java.util.List; - import javax.annotation.Nullable; -/** - * Handles updating a {@link ValueAnimatedNode} when an event gets dispatched. - */ +/** Handles updating a {@link ValueAnimatedNode} when an event gets dispatched. */ /* package */ class EventAnimationDriver implements RCTEventEmitter { private List mEventPath; /* package */ ValueAnimatedNode mValueNode; @@ -44,7 +39,8 @@ import javax.annotation.Nullable; } @Override - public void receiveTouches(String eventName, WritableArray touches, WritableArray changedIndices) { + public void receiveTouches( + String eventName, WritableArray touches, WritableArray changedIndices) { throw new RuntimeException("receiveTouches is not support by native animated events"); } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/animated/FrameBasedAnimationDriver.java b/ReactAndroid/src/main/java/com/facebook/react/animated/FrameBasedAnimationDriver.java index 9f29c619503..42b4b98bae4 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/animated/FrameBasedAnimationDriver.java +++ b/ReactAndroid/src/main/java/com/facebook/react/animated/FrameBasedAnimationDriver.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.animated; import com.facebook.react.bridge.ReadableArray; @@ -42,14 +41,14 @@ class FrameBasedAnimationDriver extends AnimationDriver { for (int i = 0; i < numberOfFrames; i++) { mFrames[i] = frames.getDouble(i); } - if(config.hasKey("toValue")) { + if (config.hasKey("toValue")) { mToValue = config.getType("toValue") == ReadableType.Number ? config.getDouble("toValue") : 0; } else { mToValue = 0; } - if(config.hasKey("iterations")) { - mIterations = config.getType("iterations") == ReadableType.Number ? - config.getInt("iterations") : 1; + if (config.hasKey("iterations")) { + mIterations = + config.getType("iterations") == ReadableType.Number ? config.getInt("iterations") : 1; } else { mIterations = 1; } diff --git a/ReactAndroid/src/main/java/com/facebook/react/animated/InterpolationAnimatedNode.java b/ReactAndroid/src/main/java/com/facebook/react/animated/InterpolationAnimatedNode.java index bc2e08c7ada..a1ce30cff29 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/animated/InterpolationAnimatedNode.java +++ b/ReactAndroid/src/main/java/com/facebook/react/animated/InterpolationAnimatedNode.java @@ -1,8 +1,8 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ package com.facebook.react.animated; @@ -10,17 +10,15 @@ import com.facebook.react.bridge.JSApplicationIllegalArgumentException; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.ReadableType; - import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; - import javax.annotation.Nullable; /** * Animated node that corresponds to {@code AnimatedInterpolation} from AnimatedImplementation.js. * - * Currently only a linear interpolation is supported on an input range of an arbitrary size. + *

Currently only a linear interpolation is supported on an input range of an arbitrary size. */ /*package*/ class InterpolationAnimatedNode extends ValueAnimatedNode { @@ -61,7 +59,7 @@ import javax.annotation.Nullable; break; default: throw new JSApplicationIllegalArgumentException( - "Invalid extrapolation type " + extrapolateLeft + "for left extrapolation"); + "Invalid extrapolation type " + extrapolateLeft + "for left extrapolation"); } } @@ -76,7 +74,7 @@ import javax.annotation.Nullable; break; default: throw new JSApplicationIllegalArgumentException( - "Invalid extrapolation type " + extrapolateRight + "for right extrapolation"); + "Invalid extrapolation type " + extrapolateRight + "for right extrapolation"); } } @@ -91,8 +89,7 @@ import javax.annotation.Nullable; return outputMax; } - return outputMin + (outputMax - outputMin) * - (result - inputMin) / (inputMax - inputMin); + return outputMin + (outputMax - outputMin) * (result - inputMin) / (inputMax - inputMin); } /*package*/ static double interpolate( @@ -100,17 +97,16 @@ import javax.annotation.Nullable; double[] inputRange, double[] outputRange, String extrapolateLeft, - String extrapolateRight - ) { + String extrapolateRight) { int rangeIndex = findRangeIndex(value, inputRange); return interpolate( - value, - inputRange[rangeIndex], - inputRange[rangeIndex + 1], - outputRange[rangeIndex], - outputRange[rangeIndex + 1], - extrapolateLeft, - extrapolateRight); + value, + inputRange[rangeIndex], + inputRange[rangeIndex + 1], + outputRange[rangeIndex], + outputRange[rangeIndex + 1], + extrapolateLeft, + extrapolateRight); } private static int findRangeIndex(double value, double[] ranges) { @@ -228,16 +224,19 @@ import javax.annotation.Nullable; int i = 0; mSOutputMatcher.reset(); while (mSOutputMatcher.find()) { - double val = interpolate(value, mInputRange, mOutputs[i++], mExtrapolateLeft, mExtrapolateRight); + double val = + interpolate(value, mInputRange, mOutputs[i++], mExtrapolateLeft, mExtrapolateRight); if (mShouldRound) { - // rgba requires that the r,g,b are integers.... so we want to round them, but we *dont* want to + // rgba requires that the r,g,b are integers.... so we want to round them, but we *dont* + // want to // round the opacity (4th column). boolean isAlpha = i == 4; - int rounded = (int)Math.round(isAlpha ? val * 1000 : val); - String num = isAlpha ? Double.toString((double)rounded / 1000) : Integer.toString(rounded); + int rounded = (int) Math.round(isAlpha ? val * 1000 : val); + String num = + isAlpha ? Double.toString((double) rounded / 1000) : Integer.toString(rounded); mSOutputMatcher.appendReplacement(sb, num); } else { - int intVal = (int)val; + int intVal = (int) val; String num = intVal != val ? Double.toString(val) : Integer.toString(intVal); mSOutputMatcher.appendReplacement(sb, num); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/animated/ModulusAnimatedNode.java b/ReactAndroid/src/main/java/com/facebook/react/animated/ModulusAnimatedNode.java index e1e7be68535..0a1cbf47543 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/animated/ModulusAnimatedNode.java +++ b/ReactAndroid/src/main/java/com/facebook/react/animated/ModulusAnimatedNode.java @@ -1,14 +1,12 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.animated; import com.facebook.react.bridge.JSApplicationCausedNativeException; -import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableMap; /*package*/ class ModulusAnimatedNode extends ValueAnimatedNode { @@ -18,8 +16,7 @@ import com.facebook.react.bridge.ReadableMap; private final double mModulus; public ModulusAnimatedNode( - ReadableMap config, - NativeAnimatedNodesManager nativeAnimatedNodesManager) { + ReadableMap config, NativeAnimatedNodesManager nativeAnimatedNodesManager) { mNativeAnimatedNodesManager = nativeAnimatedNodesManager; mInputNode = config.getInt("input"); mModulus = config.getDouble("modulus"); @@ -32,8 +29,8 @@ import com.facebook.react.bridge.ReadableMap; final double value = ((ValueAnimatedNode) animatedNode).getValue(); mValue = (value % mModulus + mModulus) % mModulus; } else { - throw new JSApplicationCausedNativeException("Illegal node ID set as an input for " + - "Animated.modulus node"); + throw new JSApplicationCausedNativeException( + "Illegal node ID set as an input for " + "Animated.modulus node"); } } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/animated/MultiplicationAnimatedNode.java b/ReactAndroid/src/main/java/com/facebook/react/animated/MultiplicationAnimatedNode.java index 23839c5c221..41f69b70340 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/animated/MultiplicationAnimatedNode.java +++ b/ReactAndroid/src/main/java/com/facebook/react/animated/MultiplicationAnimatedNode.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.animated; import com.facebook.react.bridge.JSApplicationCausedNativeException; @@ -21,8 +20,7 @@ import com.facebook.react.bridge.ReadableMap; private final int[] mInputNodes; public MultiplicationAnimatedNode( - ReadableMap config, - NativeAnimatedNodesManager nativeAnimatedNodesManager) { + ReadableMap config, NativeAnimatedNodesManager nativeAnimatedNodesManager) { mNativeAnimatedNodesManager = nativeAnimatedNodesManager; ReadableArray inputNodes = config.getArray("input"); mInputNodes = new int[inputNodes.size()]; @@ -39,8 +37,8 @@ import com.facebook.react.bridge.ReadableMap; if (animatedNode != null && animatedNode instanceof ValueAnimatedNode) { mValue *= ((ValueAnimatedNode) animatedNode).getValue(); } else { - throw new JSApplicationCausedNativeException("Illegal node ID set as an input for " + - "Animated.multiply node"); + throw new JSApplicationCausedNativeException( + "Illegal node ID set as an input for " + "Animated.multiply node"); } } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/animated/NativeAnimatedModule.java b/ReactAndroid/src/main/java/com/facebook/react/animated/NativeAnimatedModule.java index b4596f18edc..962730b06b1 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/animated/NativeAnimatedModule.java +++ b/ReactAndroid/src/main/java/com/facebook/react/animated/NativeAnimatedModule.java @@ -1,16 +1,11 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.animated; -import javax.annotation.Nullable; - -import java.util.ArrayList; - import com.facebook.infer.annotation.Assertions; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.Callback; @@ -29,51 +24,51 @@ import com.facebook.react.uimanager.NativeViewHierarchyManager; import com.facebook.react.uimanager.UIBlock; import com.facebook.react.uimanager.UIManagerModule; import com.facebook.react.uimanager.UIManagerModuleListener; +import java.util.ArrayList; +import javax.annotation.Nullable; /** * Module that exposes interface for creating and managing animated nodes on the "native" side. * - * Animated.js library is based on a concept of a graph where nodes are values or transform + *

Animated.js library is based on a concept of a graph where nodes are values or transform * operations (such as interpolation, addition, etc) and connection are used to describe how change * of the value in one node can affect other nodes. * - * Few examples of the nodes that can be created on the JS side: - * - Animated.Value is a simplest type of node with a numeric value which can be driven by an - * animation engine (spring, decay, etc) or by calling setValue on it directly from JS - * - Animated.add is a type of node that may have two or more input nodes. It outputs the sum of - * all the input node values - * - interpolate - is actually a method you can call on any node and it creates a new node that - * takes the parent node as an input and outputs its interpolated value (e.g. if you have value - * that can animate from 0 to 1 you can create interpolated node and set output range to be 0 to - * 100 and when the input node changes the output of interpolated node will multiply the values - * by 100) + *

Few examples of the nodes that can be created on the JS side: - Animated.Value is a simplest + * type of node with a numeric value which can be driven by an animation engine (spring, decay, etc) + * or by calling setValue on it directly from JS - Animated.add is a type of node that may have two + * or more input nodes. It outputs the sum of all the input node values - interpolate - is actually + * a method you can call on any node and it creates a new node that takes the parent node as an + * input and outputs its interpolated value (e.g. if you have value that can animate from 0 to 1 you + * can create interpolated node and set output range to be 0 to 100 and when the input node changes + * the output of interpolated node will multiply the values by 100) * - * You can mix and chain nodes however you like and this way create nodes graph with connections + *

You can mix and chain nodes however you like and this way create nodes graph with connections * between them. * - * To map animated node values to view properties there is a special type of a node: AnimatedProps. - * It is created by AnimatedImplementation whenever you render Animated.View and stores a mapping - * from the view properties to the corresponding animated values (so it's actually also a node with - * connections to the value nodes). + *

To map animated node values to view properties there is a special type of a node: + * AnimatedProps. It is created by AnimatedImplementation whenever you render Animated.View and + * stores a mapping from the view properties to the corresponding animated values (so it's actually + * also a node with connections to the value nodes). * - * Last "special" elements of the the graph are "animation drivers". Those are objects (represented - * as a graph nodes too) that based on some criteria updates attached values every frame (we have - * few types of those, e.g., spring, timing, decay). Animation objects can be "started" and - * "stopped". Those are like "pulse generators" for the rest of the nodes graph. Those pulses then - * propagate along the graph to the children nodes up to the special node type: AnimatedProps which - * then can be used to calculate property update map for a view. + *

Last "special" elements of the the graph are "animation drivers". Those are objects + * (represented as a graph nodes too) that based on some criteria updates attached values every + * frame (we have few types of those, e.g., spring, timing, decay). Animation objects can be + * "started" and "stopped". Those are like "pulse generators" for the rest of the nodes graph. Those + * pulses then propagate along the graph to the children nodes up to the special node type: + * AnimatedProps which then can be used to calculate property update map for a view. * - * This class acts as a proxy between the "native" API that can be called from JS and the main class - * that coordinates all the action: {@link NativeAnimatedNodesManager}. Since all the methods from - * {@link NativeAnimatedNodesManager} need to be called from the UI thread, we we create a queue of - * animated graph operations that is then enqueued to be executed in the UI Thread at the end of the - * batch of JS->native calls (similarly to how it's handled in {@link UIManagerModule}). This - * isolates us from the problems that may be caused by concurrent updates of animated graph while UI - * thread is "executing" the animation loop. + *

This class acts as a proxy between the "native" API that can be called from JS and the main + * class that coordinates all the action: {@link NativeAnimatedNodesManager}. Since all the methods + * from {@link NativeAnimatedNodesManager} need to be called from the UI thread, we we create a + * queue of animated graph operations that is then enqueued to be executed in the UI Thread at the + * end of the batch of JS->native calls (similarly to how it's handled in {@link UIManagerModule}). + * This isolates us from the problems that may be caused by concurrent updates of animated graph + * while UI thread is "executing" the animation loop. */ @ReactModule(name = NativeAnimatedModule.NAME) -public class NativeAnimatedModule extends ReactContextBaseJavaModule implements - LifecycleEventListener, UIManagerModuleListener { +public class NativeAnimatedModule extends ReactContextBaseJavaModule + implements LifecycleEventListener, UIManagerModuleListener { public static final String NAME = "NativeAnimatedModule"; @@ -92,23 +87,25 @@ public class NativeAnimatedModule extends ReactContextBaseJavaModule implements super(reactContext); mReactChoreographer = ReactChoreographer.getInstance(); - mAnimatedFrameCallback = new GuardedFrameCallback(reactContext) { - @Override - protected void doFrameGuarded(final long frameTimeNanos) { - NativeAnimatedNodesManager nodesManager = getNodesManager(); - if (nodesManager.hasActiveAnimations()) { - nodesManager.runUpdates(frameTimeNanos); - } + mAnimatedFrameCallback = + new GuardedFrameCallback(reactContext) { + @Override + protected void doFrameGuarded(final long frameTimeNanos) { + NativeAnimatedNodesManager nodesManager = getNodesManager(); + if (nodesManager.hasActiveAnimations()) { + nodesManager.runUpdates(frameTimeNanos); + } - // TODO: Would be great to avoid adding this callback in case there are no active animations - // and no outstanding tasks on the operations queue. Apparently frame callbacks can only - // be posted from the UI thread and therefore we cannot schedule them directly from - // @ReactMethod methods - Assertions.assertNotNull(mReactChoreographer).postFrameCallback( - ReactChoreographer.CallbackType.NATIVE_ANIMATED_MODULE, - mAnimatedFrameCallback); - } - }; + // TODO: Would be great to avoid adding this callback in case there are no active + // animations + // and no outstanding tasks on the operations queue. Apparently frame callbacks can only + // be posted from the UI thread and therefore we cannot schedule them directly from + // @ReactMethod methods + Assertions.assertNotNull(mReactChoreographer) + .postFrameCallback( + ReactChoreographer.CallbackType.NATIVE_ANIMATED_MODULE, mAnimatedFrameCallback); + } + }; } @Override @@ -133,24 +130,26 @@ public class NativeAnimatedModule extends ReactContextBaseJavaModule implements final ArrayList operations = mOperations; mPreOperations = new ArrayList<>(); mOperations = new ArrayList<>(); - uiManager.prependUIBlock(new UIBlock() { - @Override - public void execute(NativeViewHierarchyManager nativeViewHierarchyManager) { - NativeAnimatedNodesManager nodesManager = getNodesManager(); - for (UIThreadOperation operation : preOperations) { - operation.execute(nodesManager); - } - } - }); - uiManager.addUIBlock(new UIBlock() { - @Override - public void execute(NativeViewHierarchyManager nativeViewHierarchyManager) { - NativeAnimatedNodesManager nodesManager = getNodesManager(); - for (UIThreadOperation operation : operations) { - operation.execute(nodesManager); - } - } - }); + uiManager.prependUIBlock( + new UIBlock() { + @Override + public void execute(NativeViewHierarchyManager nativeViewHierarchyManager) { + NativeAnimatedNodesManager nodesManager = getNodesManager(); + for (UIThreadOperation operation : preOperations) { + operation.execute(nodesManager); + } + } + }); + uiManager.addUIBlock( + new UIBlock() { + @Override + public void execute(NativeViewHierarchyManager nativeViewHierarchyManager) { + NativeAnimatedNodesManager nodesManager = getNodesManager(); + for (UIThreadOperation operation : operations) { + operation.execute(nodesManager); + } + } + }); } @Override @@ -170,7 +169,8 @@ public class NativeAnimatedModule extends ReactContextBaseJavaModule implements private NativeAnimatedNodesManager getNodesManager() { if (mNodesManager == null) { - UIManagerModule uiManager = getReactApplicationContext().getNativeModule(UIManagerModule.class); + UIManagerModule uiManager = + getReactApplicationContext().getNativeModule(UIManagerModule.class); mNodesManager = new NativeAnimatedNodesManager(uiManager); } @@ -178,15 +178,15 @@ public class NativeAnimatedModule extends ReactContextBaseJavaModule implements } private void clearFrameCallback() { - Assertions.assertNotNull(mReactChoreographer).removeFrameCallback( - ReactChoreographer.CallbackType.NATIVE_ANIMATED_MODULE, - mAnimatedFrameCallback); + Assertions.assertNotNull(mReactChoreographer) + .removeFrameCallback( + ReactChoreographer.CallbackType.NATIVE_ANIMATED_MODULE, mAnimatedFrameCallback); } private void enqueueFrameCallback() { - Assertions.assertNotNull(mReactChoreographer).postFrameCallback( - ReactChoreographer.CallbackType.NATIVE_ANIMATED_MODULE, - mAnimatedFrameCallback); + Assertions.assertNotNull(mReactChoreographer) + .postFrameCallback( + ReactChoreographer.CallbackType.NATIVE_ANIMATED_MODULE, mAnimatedFrameCallback); } @VisibleForTesting @@ -196,92 +196,102 @@ public class NativeAnimatedModule extends ReactContextBaseJavaModule implements @ReactMethod public void createAnimatedNode(final int tag, final ReadableMap config) { - mOperations.add(new UIThreadOperation() { - @Override - public void execute(NativeAnimatedNodesManager animatedNodesManager) { - animatedNodesManager.createAnimatedNode(tag, config); - } - }); + mOperations.add( + new UIThreadOperation() { + @Override + public void execute(NativeAnimatedNodesManager animatedNodesManager) { + animatedNodesManager.createAnimatedNode(tag, config); + } + }); } @ReactMethod public void startListeningToAnimatedNodeValue(final int tag) { - final AnimatedNodeValueListener listener = new AnimatedNodeValueListener() { - public void onValueUpdate(double value) { - WritableMap onAnimatedValueData = Arguments.createMap(); - onAnimatedValueData.putInt("tag", tag); - onAnimatedValueData.putDouble("value", value); - getReactApplicationContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) - .emit("onAnimatedValueUpdate", onAnimatedValueData); - } - }; + final AnimatedNodeValueListener listener = + new AnimatedNodeValueListener() { + public void onValueUpdate(double value) { + WritableMap onAnimatedValueData = Arguments.createMap(); + onAnimatedValueData.putInt("tag", tag); + onAnimatedValueData.putDouble("value", value); + getReactApplicationContext() + .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) + .emit("onAnimatedValueUpdate", onAnimatedValueData); + } + }; - mOperations.add(new UIThreadOperation() { - @Override - public void execute(NativeAnimatedNodesManager animatedNodesManager) { - animatedNodesManager.startListeningToAnimatedNodeValue(tag, listener); - } - }); + mOperations.add( + new UIThreadOperation() { + @Override + public void execute(NativeAnimatedNodesManager animatedNodesManager) { + animatedNodesManager.startListeningToAnimatedNodeValue(tag, listener); + } + }); } @ReactMethod public void stopListeningToAnimatedNodeValue(final int tag) { - mOperations.add(new UIThreadOperation() { - @Override - public void execute(NativeAnimatedNodesManager animatedNodesManager) { - animatedNodesManager.stopListeningToAnimatedNodeValue(tag); - } - }); + mOperations.add( + new UIThreadOperation() { + @Override + public void execute(NativeAnimatedNodesManager animatedNodesManager) { + animatedNodesManager.stopListeningToAnimatedNodeValue(tag); + } + }); } @ReactMethod public void dropAnimatedNode(final int tag) { - mOperations.add(new UIThreadOperation() { - @Override - public void execute(NativeAnimatedNodesManager animatedNodesManager) { - animatedNodesManager.dropAnimatedNode(tag); - } - }); + mOperations.add( + new UIThreadOperation() { + @Override + public void execute(NativeAnimatedNodesManager animatedNodesManager) { + animatedNodesManager.dropAnimatedNode(tag); + } + }); } @ReactMethod public void setAnimatedNodeValue(final int tag, final double value) { - mOperations.add(new UIThreadOperation() { - @Override - public void execute(NativeAnimatedNodesManager animatedNodesManager) { - animatedNodesManager.setAnimatedNodeValue(tag, value); - } - }); + mOperations.add( + new UIThreadOperation() { + @Override + public void execute(NativeAnimatedNodesManager animatedNodesManager) { + animatedNodesManager.setAnimatedNodeValue(tag, value); + } + }); } @ReactMethod public void setAnimatedNodeOffset(final int tag, final double value) { - mOperations.add(new UIThreadOperation() { - @Override - public void execute(NativeAnimatedNodesManager animatedNodesManager) { - animatedNodesManager.setAnimatedNodeOffset(tag, value); - } - }); + mOperations.add( + new UIThreadOperation() { + @Override + public void execute(NativeAnimatedNodesManager animatedNodesManager) { + animatedNodesManager.setAnimatedNodeOffset(tag, value); + } + }); } @ReactMethod public void flattenAnimatedNodeOffset(final int tag) { - mOperations.add(new UIThreadOperation() { - @Override - public void execute(NativeAnimatedNodesManager animatedNodesManager) { - animatedNodesManager.flattenAnimatedNodeOffset(tag); - } - }); + mOperations.add( + new UIThreadOperation() { + @Override + public void execute(NativeAnimatedNodesManager animatedNodesManager) { + animatedNodesManager.flattenAnimatedNodeOffset(tag); + } + }); } @ReactMethod public void extractAnimatedNodeOffset(final int tag) { - mOperations.add(new UIThreadOperation() { - @Override - public void execute(NativeAnimatedNodesManager animatedNodesManager) { - animatedNodesManager.extractAnimatedNodeOffset(tag); - } - }); + mOperations.add( + new UIThreadOperation() { + @Override + public void execute(NativeAnimatedNodesManager animatedNodesManager) { + animatedNodesManager.extractAnimatedNodeOffset(tag); + } + }); } @ReactMethod @@ -290,91 +300,99 @@ public class NativeAnimatedModule extends ReactContextBaseJavaModule implements final int animatedNodeTag, final ReadableMap animationConfig, final Callback endCallback) { - mOperations.add(new UIThreadOperation() { - @Override - public void execute(NativeAnimatedNodesManager animatedNodesManager) { - animatedNodesManager.startAnimatingNode( - animationId, - animatedNodeTag, - animationConfig, - endCallback); - } - }); + mOperations.add( + new UIThreadOperation() { + @Override + public void execute(NativeAnimatedNodesManager animatedNodesManager) { + animatedNodesManager.startAnimatingNode( + animationId, animatedNodeTag, animationConfig, endCallback); + } + }); } @ReactMethod public void stopAnimation(final int animationId) { - mOperations.add(new UIThreadOperation() { - @Override - public void execute(NativeAnimatedNodesManager animatedNodesManager) { - animatedNodesManager.stopAnimation(animationId); - } - }); + mOperations.add( + new UIThreadOperation() { + @Override + public void execute(NativeAnimatedNodesManager animatedNodesManager) { + animatedNodesManager.stopAnimation(animationId); + } + }); } @ReactMethod public void connectAnimatedNodes(final int parentNodeTag, final int childNodeTag) { - mOperations.add(new UIThreadOperation() { - @Override - public void execute(NativeAnimatedNodesManager animatedNodesManager) { - animatedNodesManager.connectAnimatedNodes(parentNodeTag, childNodeTag); - } - }); + mOperations.add( + new UIThreadOperation() { + @Override + public void execute(NativeAnimatedNodesManager animatedNodesManager) { + animatedNodesManager.connectAnimatedNodes(parentNodeTag, childNodeTag); + } + }); } @ReactMethod public void disconnectAnimatedNodes(final int parentNodeTag, final int childNodeTag) { - mOperations.add(new UIThreadOperation() { - @Override - public void execute(NativeAnimatedNodesManager animatedNodesManager) { - animatedNodesManager.disconnectAnimatedNodes(parentNodeTag, childNodeTag); - } - }); + mOperations.add( + new UIThreadOperation() { + @Override + public void execute(NativeAnimatedNodesManager animatedNodesManager) { + animatedNodesManager.disconnectAnimatedNodes(parentNodeTag, childNodeTag); + } + }); } @ReactMethod public void connectAnimatedNodeToView(final int animatedNodeTag, final int viewTag) { - mOperations.add(new UIThreadOperation() { - @Override - public void execute(NativeAnimatedNodesManager animatedNodesManager) { - animatedNodesManager.connectAnimatedNodeToView(animatedNodeTag, viewTag); - } - }); + mOperations.add( + new UIThreadOperation() { + @Override + public void execute(NativeAnimatedNodesManager animatedNodesManager) { + animatedNodesManager.connectAnimatedNodeToView(animatedNodeTag, viewTag); + } + }); } @ReactMethod public void disconnectAnimatedNodeFromView(final int animatedNodeTag, final int viewTag) { - mPreOperations.add(new UIThreadOperation() { - @Override - public void execute(NativeAnimatedNodesManager animatedNodesManager) { - animatedNodesManager.restoreDefaultValues(animatedNodeTag, viewTag); - } - }); - mOperations.add(new UIThreadOperation() { - @Override - public void execute(NativeAnimatedNodesManager animatedNodesManager) { - animatedNodesManager.disconnectAnimatedNodeFromView(animatedNodeTag, viewTag); - } - }); + mPreOperations.add( + new UIThreadOperation() { + @Override + public void execute(NativeAnimatedNodesManager animatedNodesManager) { + animatedNodesManager.restoreDefaultValues(animatedNodeTag, viewTag); + } + }); + mOperations.add( + new UIThreadOperation() { + @Override + public void execute(NativeAnimatedNodesManager animatedNodesManager) { + animatedNodesManager.disconnectAnimatedNodeFromView(animatedNodeTag, viewTag); + } + }); } @ReactMethod - public void addAnimatedEventToView(final int viewTag, final String eventName, final ReadableMap eventMapping) { - mOperations.add(new UIThreadOperation() { - @Override - public void execute(NativeAnimatedNodesManager animatedNodesManager) { - animatedNodesManager.addAnimatedEventToView(viewTag, eventName, eventMapping); - } - }); + public void addAnimatedEventToView( + final int viewTag, final String eventName, final ReadableMap eventMapping) { + mOperations.add( + new UIThreadOperation() { + @Override + public void execute(NativeAnimatedNodesManager animatedNodesManager) { + animatedNodesManager.addAnimatedEventToView(viewTag, eventName, eventMapping); + } + }); } @ReactMethod - public void removeAnimatedEventFromView(final int viewTag, final String eventName, final int animatedValueTag) { - mOperations.add(new UIThreadOperation() { - @Override - public void execute(NativeAnimatedNodesManager animatedNodesManager) { - animatedNodesManager.removeAnimatedEventFromView(viewTag, eventName, animatedValueTag); - } - }); + public void removeAnimatedEventFromView( + final int viewTag, final String eventName, final int animatedValueTag) { + mOperations.add( + new UIThreadOperation() { + @Override + public void execute(NativeAnimatedNodesManager animatedNodesManager) { + animatedNodesManager.removeAnimatedEventFromView(viewTag, eventName, animatedValueTag); + } + }); } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/animated/NativeAnimatedNodesManager.java b/ReactAndroid/src/main/java/com/facebook/react/animated/NativeAnimatedNodesManager.java index 1dff9639cdd..2e45456e0b9 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/animated/NativeAnimatedNodesManager.java +++ b/ReactAndroid/src/main/java/com/facebook/react/animated/NativeAnimatedNodesManager.java @@ -1,14 +1,12 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.animated; import android.util.SparseArray; - import com.facebook.common.logging.FLog; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.Callback; @@ -22,7 +20,6 @@ import com.facebook.react.uimanager.IllegalViewOperationException; import com.facebook.react.uimanager.UIManagerModule; import com.facebook.react.uimanager.events.Event; import com.facebook.react.uimanager.events.EventDispatcherListener; - import java.util.ArrayDeque; import java.util.ArrayList; import java.util.HashMap; @@ -31,21 +28,20 @@ import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Queue; - import javax.annotation.Nullable; /** * This is the main class that coordinates how native animated JS implementation drives UI changes. * - * It implements a management interface for animated nodes graph as well as implements a graph + *

It implements a management interface for animated nodes graph as well as implements a graph * traversal algorithm that is run for each animation frame. * - * For each animation frame we visit animated nodes that might've been updated as well as their + *

For each animation frame we visit animated nodes that might've been updated as well as their * children that may use parent's values to update themselves. At the end of the traversal algorithm * we expect to reach a special type of the node: PropsAnimatedNode that is then responsible for * calculating property map which can be sent to native view hierarchy to update the view. * - * IMPORTANT: This class should be accessed only from the UI Thread + *

IMPORTANT: This class should be accessed only from the UI Thread */ /*package*/ class NativeAnimatedNodesManager implements EventDispatcherListener { @@ -67,7 +63,8 @@ import javax.annotation.Nullable; mCustomEventNamesResolver = uiManager.getDirectEventNamesResolver(); } - /*package*/ @Nullable AnimatedNode getNodeById(int id) { + /*package*/ @Nullable + AnimatedNode getNodeById(int id) { return mAnimatedNodes.get(id); } @@ -77,8 +74,8 @@ import javax.annotation.Nullable; public void createAnimatedNode(int tag, ReadableMap config) { if (mAnimatedNodes.get(tag) != null) { - throw new JSApplicationIllegalArgumentException("Animated node with tag " + tag + - " already exists"); + throw new JSApplicationIllegalArgumentException( + "Animated node with tag " + tag + " already exists"); } String type = config.getString("type"); final AnimatedNode node; @@ -122,8 +119,8 @@ import javax.annotation.Nullable; public void startListeningToAnimatedNodeValue(int tag, AnimatedNodeValueListener listener) { AnimatedNode node = mAnimatedNodes.get(tag); if (node == null || !(node instanceof ValueAnimatedNode)) { - throw new JSApplicationIllegalArgumentException("Animated node with tag " + tag + - " does not exists or is not a 'value' node"); + throw new JSApplicationIllegalArgumentException( + "Animated node with tag " + tag + " does not exists or is not a 'value' node"); } ((ValueAnimatedNode) node).setValueListener(listener); } @@ -131,8 +128,8 @@ import javax.annotation.Nullable; public void stopListeningToAnimatedNodeValue(int tag) { AnimatedNode node = mAnimatedNodes.get(tag); if (node == null || !(node instanceof ValueAnimatedNode)) { - throw new JSApplicationIllegalArgumentException("Animated node with tag " + tag + - " does not exists or is not a 'value' node"); + throw new JSApplicationIllegalArgumentException( + "Animated node with tag " + tag + " does not exists or is not a 'value' node"); } ((ValueAnimatedNode) node).setValueListener(null); } @@ -140,8 +137,8 @@ import javax.annotation.Nullable; public void setAnimatedNodeValue(int tag, double value) { AnimatedNode node = mAnimatedNodes.get(tag); if (node == null || !(node instanceof ValueAnimatedNode)) { - throw new JSApplicationIllegalArgumentException("Animated node with tag " + tag + - " does not exists or is not a 'value' node"); + throw new JSApplicationIllegalArgumentException( + "Animated node with tag " + tag + " does not exists or is not a 'value' node"); } stopAnimationsForNode(node); ((ValueAnimatedNode) node).mValue = value; @@ -151,8 +148,8 @@ import javax.annotation.Nullable; public void setAnimatedNodeOffset(int tag, double offset) { AnimatedNode node = mAnimatedNodes.get(tag); if (node == null || !(node instanceof ValueAnimatedNode)) { - throw new JSApplicationIllegalArgumentException("Animated node with tag " + tag + - " does not exists or is not a 'value' node"); + throw new JSApplicationIllegalArgumentException( + "Animated node with tag " + tag + " does not exists or is not a 'value' node"); } ((ValueAnimatedNode) node).mOffset = offset; mUpdatedNodes.put(tag, node); @@ -161,8 +158,8 @@ import javax.annotation.Nullable; public void flattenAnimatedNodeOffset(int tag) { AnimatedNode node = mAnimatedNodes.get(tag); if (node == null || !(node instanceof ValueAnimatedNode)) { - throw new JSApplicationIllegalArgumentException("Animated node with tag " + tag + - " does not exists or is not a 'value' node"); + throw new JSApplicationIllegalArgumentException( + "Animated node with tag " + tag + " does not exists or is not a 'value' node"); } ((ValueAnimatedNode) node).flattenOffset(); } @@ -170,25 +167,22 @@ import javax.annotation.Nullable; public void extractAnimatedNodeOffset(int tag) { AnimatedNode node = mAnimatedNodes.get(tag); if (node == null || !(node instanceof ValueAnimatedNode)) { - throw new JSApplicationIllegalArgumentException("Animated node with tag " + tag + - " does not exists or is not a 'value' node"); + throw new JSApplicationIllegalArgumentException( + "Animated node with tag " + tag + " does not exists or is not a 'value' node"); } ((ValueAnimatedNode) node).extractOffset(); } public void startAnimatingNode( - int animationId, - int animatedNodeTag, - ReadableMap animationConfig, - Callback endCallback) { + int animationId, int animatedNodeTag, ReadableMap animationConfig, Callback endCallback) { AnimatedNode node = mAnimatedNodes.get(animatedNodeTag); if (node == null) { - throw new JSApplicationIllegalArgumentException("Animated node with tag " + animatedNodeTag + - " does not exists"); + throw new JSApplicationIllegalArgumentException( + "Animated node with tag " + animatedNodeTag + " does not exists"); } if (!(node instanceof ValueAnimatedNode)) { - throw new JSApplicationIllegalArgumentException("Animated node should be of type " + - ValueAnimatedNode.class.getName()); + throw new JSApplicationIllegalArgumentException( + "Animated node should be of type " + ValueAnimatedNode.class.getName()); } final AnimationDriver existingDriver = mActiveAnimations.get(animationId); @@ -263,13 +257,13 @@ import javax.annotation.Nullable; public void connectAnimatedNodes(int parentNodeTag, int childNodeTag) { AnimatedNode parentNode = mAnimatedNodes.get(parentNodeTag); if (parentNode == null) { - throw new JSApplicationIllegalArgumentException("Animated node with tag " + parentNodeTag + - " does not exists"); + throw new JSApplicationIllegalArgumentException( + "Animated node with tag " + parentNodeTag + " does not exists"); } AnimatedNode childNode = mAnimatedNodes.get(childNodeTag); if (childNode == null) { - throw new JSApplicationIllegalArgumentException("Animated node with tag " + childNodeTag + - " does not exists"); + throw new JSApplicationIllegalArgumentException( + "Animated node with tag " + childNodeTag + " does not exists"); } parentNode.addChild(childNode); mUpdatedNodes.put(childNodeTag, childNode); @@ -278,13 +272,13 @@ import javax.annotation.Nullable; public void disconnectAnimatedNodes(int parentNodeTag, int childNodeTag) { AnimatedNode parentNode = mAnimatedNodes.get(parentNodeTag); if (parentNode == null) { - throw new JSApplicationIllegalArgumentException("Animated node with tag " + parentNodeTag + - " does not exists"); + throw new JSApplicationIllegalArgumentException( + "Animated node with tag " + parentNodeTag + " does not exists"); } AnimatedNode childNode = mAnimatedNodes.get(childNodeTag); if (childNode == null) { - throw new JSApplicationIllegalArgumentException("Animated node with tag " + childNodeTag + - " does not exists"); + throw new JSApplicationIllegalArgumentException( + "Animated node with tag " + childNodeTag + " does not exists"); } parentNode.removeChild(childNode); mUpdatedNodes.put(childNodeTag, childNode); @@ -293,12 +287,14 @@ import javax.annotation.Nullable; public void connectAnimatedNodeToView(int animatedNodeTag, int viewTag) { AnimatedNode node = mAnimatedNodes.get(animatedNodeTag); if (node == null) { - throw new JSApplicationIllegalArgumentException("Animated node with tag " + animatedNodeTag + - " does not exists"); + throw new JSApplicationIllegalArgumentException( + "Animated node with tag " + animatedNodeTag + " does not exists"); } if (!(node instanceof PropsAnimatedNode)) { - throw new JSApplicationIllegalArgumentException("Animated node connected to view should be" + - "of type " + PropsAnimatedNode.class.getName()); + throw new JSApplicationIllegalArgumentException( + "Animated node connected to view should be" + + "of type " + + PropsAnimatedNode.class.getName()); } PropsAnimatedNode propsAnimatedNode = (PropsAnimatedNode) node; propsAnimatedNode.connectToView(viewTag); @@ -308,12 +304,14 @@ import javax.annotation.Nullable; public void disconnectAnimatedNodeFromView(int animatedNodeTag, int viewTag) { AnimatedNode node = mAnimatedNodes.get(animatedNodeTag); if (node == null) { - throw new JSApplicationIllegalArgumentException("Animated node with tag " + animatedNodeTag + - " does not exists"); + throw new JSApplicationIllegalArgumentException( + "Animated node with tag " + animatedNodeTag + " does not exists"); } if (!(node instanceof PropsAnimatedNode)) { - throw new JSApplicationIllegalArgumentException("Animated node connected to view should be" + - "of type " + PropsAnimatedNode.class.getName()); + throw new JSApplicationIllegalArgumentException( + "Animated node connected to view should be" + + "of type " + + PropsAnimatedNode.class.getName()); } PropsAnimatedNode propsAnimatedNode = (PropsAnimatedNode) node; propsAnimatedNode.disconnectFromView(viewTag); @@ -329,8 +327,10 @@ import javax.annotation.Nullable; return; } if (!(node instanceof PropsAnimatedNode)) { - throw new JSApplicationIllegalArgumentException("Animated node connected to view should be" + - "of type " + PropsAnimatedNode.class.getName()); + throw new JSApplicationIllegalArgumentException( + "Animated node connected to view should be" + + "of type " + + PropsAnimatedNode.class.getName()); } PropsAnimatedNode propsAnimatedNode = (PropsAnimatedNode) node; propsAnimatedNode.restoreDefaultValues(); @@ -340,12 +340,14 @@ import javax.annotation.Nullable; int nodeTag = eventMapping.getInt("animatedValueTag"); AnimatedNode node = mAnimatedNodes.get(nodeTag); if (node == null) { - throw new JSApplicationIllegalArgumentException("Animated node with tag " + nodeTag + - " does not exists"); + throw new JSApplicationIllegalArgumentException( + "Animated node with tag " + nodeTag + " does not exists"); } if (!(node instanceof ValueAnimatedNode)) { - throw new JSApplicationIllegalArgumentException("Animated node connected to event should be" + - "of type " + ValueAnimatedNode.class.getName()); + throw new JSApplicationIllegalArgumentException( + "Animated node connected to event should be" + + "of type " + + ValueAnimatedNode.class.getName()); } ReadableArray path = eventMapping.getArray("nativeEventPath"); @@ -390,12 +392,13 @@ import javax.annotation.Nullable; if (UiThreadUtil.isOnUiThread()) { handleEvent(event); } else { - UiThreadUtil.runOnUiThread(new Runnable() { - @Override - public void run() { - handleEvent(event); - } - }); + UiThreadUtil.runOnUiThread( + new Runnable() { + @Override + public void run() { + handleEvent(event); + } + }); } } @@ -417,12 +420,12 @@ import javax.annotation.Nullable; } /** - * Animation loop performs two BFSes over the graph of animated nodes. We use incremented - * {@code mAnimatedGraphBFSColor} to mark nodes as visited in each of the BFSes which saves - * additional loops for clearing "visited" states. + * Animation loop performs two BFSes over the graph of animated nodes. We use incremented {@code + * mAnimatedGraphBFSColor} to mark nodes as visited in each of the BFSes which saves additional + * loops for clearing "visited" states. * - * First BFS starts with nodes that are in {@code mUpdatedNodes} (that is, their value have been - * modified from JS in the last batch of JS operations) or directly attached to an active + *

First BFS starts with nodes that are in {@code mUpdatedNodes} (that is, their value have + * been modified from JS in the last batch of JS operations) or directly attached to an active * animation (hence linked to objects from {@code mActiveAnimations}). In that step we calculate * an attribute {@code mActiveIncomingNodes}. The second BFS runs in topological order over the * sub-graph of *active* nodes. This is done by adding node to the BFS queue only if all its @@ -543,14 +546,20 @@ import javax.annotation.Nullable; try { ((PropsAnimatedNode) nextNode).updateView(); } catch (IllegalViewOperationException e) { - // An exception is thrown if the view hasn't been created yet. This can happen because views are - // created in batches. If this particular view didn't make it into a batch yet, the view won't - // exist and an exception will be thrown when attempting to start an animation on it. - // - // Eat the exception rather than crashing. The impact is that we may drop one or more frames of the - // animation. - FLog.e(ReactConstants.TAG, "Native animation workaround, frame lost as result of race condition", e); - } + // An exception is thrown if the view hasn't been created yet. This can happen because + // views are + // created in batches. If this particular view didn't make it into a batch yet, the view + // won't + // exist and an exception will be thrown when attempting to start an animation on it. + // + // Eat the exception rather than crashing. The impact is that we may drop one or more + // frames of the + // animation. + FLog.e( + ReactConstants.TAG, + "Native animation workaround, frame lost as result of race condition", + e); + } } if (nextNode instanceof ValueAnimatedNode) { // Potentially send events to JS when the node's value is updated @@ -574,8 +583,11 @@ import javax.annotation.Nullable; // visited in the step above so that all the nodes properties `mActiveIncomingNodes` are set to // zero if (activeNodesCount != updatedNodesCount) { - throw new IllegalStateException("Looks like animated nodes graph has cycles, there are " - + activeNodesCount + " but toposort visited only " + updatedNodesCount); + throw new IllegalStateException( + "Looks like animated nodes graph has cycles, there are " + + activeNodesCount + + " but toposort visited only " + + updatedNodesCount); } } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/animated/PropsAnimatedNode.java b/ReactAndroid/src/main/java/com/facebook/react/animated/PropsAnimatedNode.java index 7bb7eaaeba2..0a56eb96e3b 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/animated/PropsAnimatedNode.java +++ b/ReactAndroid/src/main/java/com/facebook/react/animated/PropsAnimatedNode.java @@ -1,27 +1,24 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.animated; import com.facebook.react.bridge.JSApplicationIllegalArgumentException; import com.facebook.react.bridge.JavaOnlyMap; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.ReadableMapKeySetIterator; - import com.facebook.react.bridge.UIManager; import java.util.HashMap; import java.util.Map; - import javax.annotation.Nullable; /** * Animated node that represents view properties. There is a special handling logic implemented for - * the nodes of this type in {@link NativeAnimatedNodesManager} that is responsible for extracting - * a map of updated properties, which can be then passed down to the view. + * the nodes of this type in {@link NativeAnimatedNodesManager} that is responsible for extracting a + * map of updated properties, which can be then passed down to the view. */ /*package*/ class PropsAnimatedNode extends AnimatedNode { @@ -31,7 +28,10 @@ import javax.annotation.Nullable; private final Map mPropNodeMapping; private final JavaOnlyMap mPropMap; - PropsAnimatedNode(ReadableMap config, NativeAnimatedNodesManager nativeAnimatedNodesManager, UIManager uiManager) { + PropsAnimatedNode( + ReadableMap config, + NativeAnimatedNodesManager nativeAnimatedNodesManager, + UIManager uiManager) { ReadableMap props = config.getMap("props"); ReadableMapKeySetIterator iter = props.keySetIterator(); mPropNodeMapping = new HashMap<>(); @@ -47,16 +47,17 @@ import javax.annotation.Nullable; public void connectToView(int viewTag) { if (mConnectedViewTag != -1) { - throw new JSApplicationIllegalArgumentException("Animated node " + mTag + " is " + - "already attached to a view"); + throw new JSApplicationIllegalArgumentException( + "Animated node " + mTag + " is " + "already attached to a view"); } mConnectedViewTag = viewTag; } public void disconnectFromView(int viewTag) { if (mConnectedViewTag != viewTag) { - throw new JSApplicationIllegalArgumentException("Attempting to disconnect view that has " + - "not been connected with the given animated node"); + throw new JSApplicationIllegalArgumentException( + "Attempting to disconnect view that has " + + "not been connected with the given animated node"); } mConnectedViewTag = -1; @@ -64,13 +65,11 @@ import javax.annotation.Nullable; public void restoreDefaultValues() { ReadableMapKeySetIterator it = mPropMap.keySetIterator(); - while(it.hasNextKey()) { + while (it.hasNextKey()) { mPropMap.putNull(it.nextKey()); } - mUIManager.synchronouslyUpdateViewOnUIThread( - mConnectedViewTag, - mPropMap); + mUIManager.synchronouslyUpdateViewOnUIThread(mConnectedViewTag, mPropMap); } public final void updateView() { @@ -86,18 +85,16 @@ import javax.annotation.Nullable; } else if (node instanceof ValueAnimatedNode) { Object animatedObject = ((ValueAnimatedNode) node).getAnimatedObject(); if (animatedObject instanceof String) { - mPropMap.putString(entry.getKey(), (String)animatedObject); + mPropMap.putString(entry.getKey(), (String) animatedObject); } else { mPropMap.putDouble(entry.getKey(), ((ValueAnimatedNode) node).getValue()); } } else { - throw new IllegalArgumentException("Unsupported type of node used in property node " + - node.getClass()); + throw new IllegalArgumentException( + "Unsupported type of node used in property node " + node.getClass()); } } - mUIManager.synchronouslyUpdateViewOnUIThread( - mConnectedViewTag, - mPropMap); + mUIManager.synchronouslyUpdateViewOnUIThread(mConnectedViewTag, mPropMap); } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/animated/SpringAnimation.java b/ReactAndroid/src/main/java/com/facebook/react/animated/SpringAnimation.java index 6b76ae32daa..0d0015af52f 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/animated/SpringAnimation.java +++ b/ReactAndroid/src/main/java/com/facebook/react/animated/SpringAnimation.java @@ -1,18 +1,17 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.animated; import com.facebook.react.bridge.ReadableMap; /** * Implementation of {@link AnimationDriver} providing support for spring animations. The - * implementation has been copied from android implementation of Rebound library (see - * http://facebook.github.io/rebound/) + * implementation has been copied from android implementation of Rebound library (see http://facebook.github.io/rebound/) */ /*package*/ class SpringAnimation extends AnimationDriver { @@ -101,6 +100,7 @@ import com.facebook.react.bridge.ReadableMap; /** * get the displacement from rest for a given physics state + * * @param state the state to measure from * @return the distance displaced by */ @@ -110,22 +110,24 @@ import com.facebook.react.bridge.ReadableMap; /** * check if the current state is at rest + * * @return is the spring at rest */ private boolean isAtRest() { - return Math.abs(mCurrentState.velocity) <= mRestSpeedThreshold && - (getDisplacementDistanceForState(mCurrentState) <= mDisplacementFromRestThreshold || - mSpringStiffness == 0); + return Math.abs(mCurrentState.velocity) <= mRestSpeedThreshold + && (getDisplacementDistanceForState(mCurrentState) <= mDisplacementFromRestThreshold + || mSpringStiffness == 0); } /** * Check if the spring is overshooting beyond its target. + * * @return true if the spring is overshooting its target */ private boolean isOvershooting() { - return mSpringStiffness > 0 && - ((mStartValue < mEndValue && mCurrentState.position > mEndValue) || - (mStartValue > mEndValue && mCurrentState.position < mEndValue)); + return mSpringStiffness > 0 + && ((mStartValue < mEndValue && mCurrentState.position > mEndValue) + || (mStartValue > mEndValue && mCurrentState.position < mEndValue)); } private void advance(double realDeltaTime) { @@ -147,7 +149,7 @@ import com.facebook.react.bridge.ReadableMap; double k = mSpringStiffness; double v0 = -mInitialVelocity; - double zeta = c / (2 * Math.sqrt(k * m )); + double zeta = c / (2 * Math.sqrt(k * m)); double omega0 = Math.sqrt(k / m); double omega1 = omega0 * Math.sqrt(1.0 - (zeta * zeta)); double x0 = mEndValue - mStartValue; @@ -159,27 +161,26 @@ import com.facebook.react.bridge.ReadableMap; // Under damped double envelope = Math.exp(-zeta * omega0 * t); position = - mEndValue - - envelope * - ((v0 + zeta * omega0 * x0) / omega1 * Math.sin(omega1 * t) + - x0 * Math.cos(omega1 * t)); + mEndValue + - envelope + * ((v0 + zeta * omega0 * x0) / omega1 * Math.sin(omega1 * t) + + x0 * Math.cos(omega1 * t)); // This looks crazy -- it's actually just the derivative of the // oscillation function velocity = - zeta * - omega0 * - envelope * - (Math.sin(omega1 * t) * (v0 + zeta * omega0 * x0) / omega1 + - x0 * Math.cos(omega1 * t)) - - envelope * - (Math.cos(omega1 * t) * (v0 + zeta * omega0 * x0) - - omega1 * x0 * Math.sin(omega1 * t)); + zeta + * omega0 + * envelope + * (Math.sin(omega1 * t) * (v0 + zeta * omega0 * x0) / omega1 + + x0 * Math.cos(omega1 * t)) + - envelope + * (Math.cos(omega1 * t) * (v0 + zeta * omega0 * x0) + - omega1 * x0 * Math.sin(omega1 * t)); } else { // Critically damped spring double envelope = Math.exp(-omega0 * t); position = mEndValue - envelope * (x0 + (v0 + omega0 * x0) * t); - velocity = - envelope * (v0 * (t * omega0 - 1) + t * x0 * (omega0 * omega0)); + velocity = envelope * (v0 * (t * omega0 - 1) + t * x0 * (omega0 * omega0)); } mCurrentState.position = position; diff --git a/ReactAndroid/src/main/java/com/facebook/react/animated/StyleAnimatedNode.java b/ReactAndroid/src/main/java/com/facebook/react/animated/StyleAnimatedNode.java index 0a46c31facd..94cff86c001 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/animated/StyleAnimatedNode.java +++ b/ReactAndroid/src/main/java/com/facebook/react/animated/StyleAnimatedNode.java @@ -1,19 +1,16 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.animated; import com.facebook.react.bridge.JavaOnlyMap; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.ReadableMapKeySetIterator; - import java.util.HashMap; import java.util.Map; - import javax.annotation.Nullable; /** @@ -46,8 +43,8 @@ import javax.annotation.Nullable; } else if (node instanceof ValueAnimatedNode) { propsMap.putDouble(entry.getKey(), ((ValueAnimatedNode) node).getValue()); } else { - throw new IllegalArgumentException("Unsupported type of node used in property node " + - node.getClass()); + throw new IllegalArgumentException( + "Unsupported type of node used in property node " + node.getClass()); } } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/animated/SubtractionAnimatedNode.java b/ReactAndroid/src/main/java/com/facebook/react/animated/SubtractionAnimatedNode.java index ac29638a2d3..c54fbe83b7b 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/animated/SubtractionAnimatedNode.java +++ b/ReactAndroid/src/main/java/com/facebook/react/animated/SubtractionAnimatedNode.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.animated; import com.facebook.react.bridge.JSApplicationCausedNativeException; @@ -21,8 +20,7 @@ import com.facebook.react.bridge.ReadableMap; private final int[] mInputNodes; public SubtractionAnimatedNode( - ReadableMap config, - NativeAnimatedNodesManager nativeAnimatedNodesManager) { + ReadableMap config, NativeAnimatedNodesManager nativeAnimatedNodesManager) { mNativeAnimatedNodesManager = nativeAnimatedNodesManager; ReadableArray inputNodes = config.getArray("input"); mInputNodes = new int[inputNodes.size()]; @@ -43,8 +41,8 @@ import com.facebook.react.bridge.ReadableMap; } mValue -= ((ValueAnimatedNode) animatedNode).getValue(); } else { - throw new JSApplicationCausedNativeException("Illegal node ID set as an input for " + - "Animated.subtract node"); + throw new JSApplicationCausedNativeException( + "Illegal node ID set as an input for " + "Animated.subtract node"); } } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/animated/TrackingAnimatedNode.java b/ReactAndroid/src/main/java/com/facebook/react/animated/TrackingAnimatedNode.java index 76108b548a3..ea1f6685a16 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/animated/TrackingAnimatedNode.java +++ b/ReactAndroid/src/main/java/com/facebook/react/animated/TrackingAnimatedNode.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.animated; import com.facebook.react.bridge.JavaOnlyMap; @@ -30,6 +29,7 @@ import com.facebook.react.bridge.ReadableMap; public void update() { AnimatedNode toValue = mNativeAnimatedNodesManager.getNodeById(mToValueNode); mAnimationConfig.putDouble("toValue", ((ValueAnimatedNode) toValue).getValue()); - mNativeAnimatedNodesManager.startAnimatingNode(mAnimationId, mValueNode, mAnimationConfig, null); + mNativeAnimatedNodesManager.startAnimatingNode( + mAnimationId, mValueNode, mAnimationConfig, null); } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/animated/TransformAnimatedNode.java b/ReactAndroid/src/main/java/com/facebook/react/animated/TransformAnimatedNode.java index 9288c25d6bf..466cf28ef56 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/animated/TransformAnimatedNode.java +++ b/ReactAndroid/src/main/java/com/facebook/react/animated/TransformAnimatedNode.java @@ -1,22 +1,21 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.animated; import com.facebook.react.bridge.JavaOnlyArray; import com.facebook.react.bridge.JavaOnlyMap; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableMap; - import java.util.ArrayList; import java.util.List; /** - * Native counterpart of transform animated node (see AnimatedTransform class in AnimatedImplementation.js) + * Native counterpart of transform animated node (see AnimatedTransform class in + * AnimatedImplementation.js) */ /* package */ class TransformAnimatedNode extends AnimatedNode { @@ -70,8 +69,8 @@ import java.util.List; } else if (node instanceof ValueAnimatedNode) { value = ((ValueAnimatedNode) node).getValue(); } else { - throw new IllegalArgumentException("Unsupported type of node used as a transform child " + - "node " + node.getClass()); + throw new IllegalArgumentException( + "Unsupported type of node used as a transform child " + "node " + node.getClass()); } } else { value = ((StaticTransformConfig) transformConfig).mValue; diff --git a/ReactAndroid/src/main/java/com/facebook/react/animated/ValueAnimatedNode.java b/ReactAndroid/src/main/java/com/facebook/react/animated/ValueAnimatedNode.java index 0c92f11f899..5ecec926f8b 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/animated/ValueAnimatedNode.java +++ b/ReactAndroid/src/main/java/com/facebook/react/animated/ValueAnimatedNode.java @@ -1,14 +1,12 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.animated; import com.facebook.react.bridge.ReadableMap; - import javax.annotation.Nullable; /** diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/ActivityEventListener.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/ActivityEventListener.java index f4b6f51f933..4cd950409f5 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/ActivityEventListener.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/ActivityEventListener.java @@ -14,13 +14,9 @@ import android.content.Intent; */ public interface ActivityEventListener { - /** - * Called when host (activity/service) receives an {@link Activity#onActivityResult} call. - */ + /** Called when host (activity/service) receives an {@link Activity#onActivityResult} call. */ void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data); - /** - * Called when a new intent is passed to the activity - */ + /** Called when a new intent is passed to the activity */ void onNewIntent(Intent intent); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/Arguments.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/Arguments.java index deffbe52655..2fee9d3b1c0 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/Arguments.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/Arguments.java @@ -1,30 +1,27 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ package com.facebook.react.bridge; +import android.os.Bundle; import java.lang.reflect.Array; - import java.util.AbstractList; import java.util.ArrayList; import java.util.List; import java.util.Map; - import javax.annotation.Nullable; -import android.os.Bundle; - public class Arguments { private static Object makeNativeObject(Object object) { if (object == null) { return null; - } else if (object instanceof Float || - object instanceof Long || - object instanceof Byte || - object instanceof Short) { + } else if (object instanceof Float + || object instanceof Long + || object instanceof Byte + || object instanceof Short) { return ((Number) object).doubleValue(); } else if (object.getClass().isArray()) { return makeNativeArray(object); @@ -41,12 +38,11 @@ public class Arguments { } /** - * This method converts a List into a NativeArray. The data types supported - * are boolean, int, float, double, and String. List, Map, and Bundle - * objects, as well as arrays, containing values of the above types and/or - * null, or any recursive arrangement of these, are also supported. The best - * way to think of this is a way to generate a Java representation of a json - * list, from Java types which have a natural representation in json. + * This method converts a List into a NativeArray. The data types supported are boolean, int, + * float, double, and String. List, Map, and Bundle objects, as well as arrays, containing values + * of the above types and/or null, or any recursive arrangement of these, are also supported. The + * best way to think of this is a way to generate a Java representation of a json list, from Java + * types which have a natural representation in json. */ public static WritableNativeArray makeNativeArray(List objects) { WritableNativeArray nativeArray = new WritableNativeArray(); @@ -77,8 +73,8 @@ public class Arguments { } /** - * This overload is like the above, but uses reflection to operate on any - * primitive or object type. + * This overload is like the above, but uses reflection to operate on any primitive or object + * type. */ public static WritableNativeArray makeNativeArray(final Object objects) { if (objects == null) { @@ -86,15 +82,16 @@ public class Arguments { } // No explicit check for objects's type here. If it's not an array, the // Array methods will throw IllegalArgumentException. - return makeNativeArray(new AbstractList() { - public int size() { - return Array.getLength(objects); - } + return makeNativeArray( + new AbstractList() { + public int size() { + return Array.getLength(objects); + } - public Object get(int index) { - return Array.get(objects, index); - } - }); + public Object get(int index) { + return Array.get(objects, index); + } + }); } private static void addEntry(WritableNativeMap nativeMap, String key, Object value) { @@ -119,10 +116,9 @@ public class Arguments { } /** - * This method converts a Map into a NativeMap. Value types are supported as - * with makeNativeArray. The best way to think of this is a way to generate - * a Java representation of a json object, from Java types which have a - * natural representation in json. + * This method converts a Map into a NativeMap. Value types are supported as with makeNativeArray. + * The best way to think of this is a way to generate a Java representation of a json object, from + * Java types which have a natural representation in json. */ public static WritableNativeMap makeNativeMap(Map objects) { WritableNativeMap nativeMap = new WritableNativeMap(); @@ -135,9 +131,7 @@ public class Arguments { return nativeMap; } - /** - * Like the above, but takes a Bundle instead of a Map. - */ + /** Like the above, but takes a Bundle instead of a Map. */ public static WritableNativeMap makeNativeMap(Bundle bundle) { WritableNativeMap nativeMap = new WritableNativeMap(); if (bundle == null) { @@ -149,16 +143,12 @@ public class Arguments { return nativeMap; } - /** - * This method should be used when you need to stub out creating NativeArrays in unit tests. - */ + /** This method should be used when you need to stub out creating NativeArrays in unit tests. */ public static WritableArray createArray() { return new WritableNativeArray(); } - /** - * This method should be used when you need to stub out creating NativeMaps in unit tests. - */ + /** This method should be used when you need to stub out creating NativeMaps in unit tests. */ public static WritableMap createMap() { return new WritableNativeMap(); } @@ -198,7 +188,7 @@ public class Arguments { * Convert an array to a {@link WritableArray}. * * @param array the array to convert. Supported types are: {@code String[]}, {@code Bundle[]}, - * {@code int[]}, {@code float[]}, {@code double[]}, {@code boolean[]}. + * {@code int[]}, {@code float[]}, {@code double[]}, {@code boolean[]}. * @return the converted {@link WritableArray} * @throws IllegalArgumentException if the passed object is none of the above types */ @@ -237,10 +227,12 @@ public class Arguments { /** * Convert a {@link List} to a {@link WritableArray}. * - * @param list the list to convert. Supported value types are: {@code null}, {@code String}, {@code Bundle}, - * {@code List}, {@code Number}, {@code Boolean}, and all array types supported in {@link #fromArray(Object)}. + * @param list the list to convert. Supported value types are: {@code null}, {@code String}, + * {@code Bundle}, {@code List}, {@code Number}, {@code Boolean}, and all array types + * supported in {@link #fromArray(Object)}. * @return the converted {@link WritableArray} - * @throws IllegalArgumentException if one of the values from the passed list is none of the above types + * @throws IllegalArgumentException if one of the values from the passed list is none of the above + * types */ public static WritableArray fromList(List list) { WritableArray catalystArray = createArray(); @@ -269,14 +261,15 @@ public class Arguments { } /** - * Convert a {@link Bundle} to a {@link WritableMap}. Supported key types in the bundle - * are: + * Convert a {@link Bundle} to a {@link WritableMap}. Supported key types in the bundle are: + * *

+ * *

* * @param bundle the {@link Bundle} to convert @@ -362,8 +355,8 @@ public class Arguments { } /** - * Convert a {@link WritableMap} to a {@link Bundle}. - * Note: Each array is converted to an {@link ArrayList}. + * Convert a {@link WritableMap} to a {@link Bundle}. Note: Each array is converted to an {@link + * ArrayList}. * * @param readableMap the {@link WritableMap} to convert. * @return the converted {@link Bundle}. diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/AssertionException.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/AssertionException.java index e225b718dd3..424bc716f60 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/AssertionException.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/AssertionException.java @@ -1,16 +1,15 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; /** - * Like {@link AssertionError} but extends RuntimeException so that it may be caught by a - * {@link NativeModuleCallExceptionHandler}. See that class for more details. Used in - * conjunction with {@link SoftAssertions}. + * Like {@link AssertionError} but extends RuntimeException so that it may be caught by a {@link + * NativeModuleCallExceptionHandler}. See that class for more details. Used in conjunction with + * {@link SoftAssertions}. */ public class AssertionException extends RuntimeException { diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/BaseActivityEventListener.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/BaseActivityEventListener.java index d7369ad1932..98d67b86b22 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/BaseActivityEventListener.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/BaseActivityEventListener.java @@ -8,20 +8,16 @@ package com.facebook.react.bridge; import android.app.Activity; import android.content.Intent; -/** - * An empty implementation of {@link ActivityEventListener} - */ +/** An empty implementation of {@link ActivityEventListener} */ public class BaseActivityEventListener implements ActivityEventListener { - /** - * @deprecated use {@link #onActivityResult(Activity, int, int, Intent)} instead. - */ + /** @deprecated use {@link #onActivityResult(Activity, int, int, Intent)} instead. */ @Deprecated - public void onActivityResult(int requestCode, int resultCode, Intent data) { } + public void onActivityResult(int requestCode, int resultCode, Intent data) {} @Override - public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) { } + public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {} @Override - public void onNewIntent(Intent intent) { } + public void onNewIntent(Intent intent) {} } diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/BaseJavaModule.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/BaseJavaModule.java index 086b939355f..51ac27100f0 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/BaseJavaModule.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/BaseJavaModule.java @@ -1,49 +1,44 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; -import javax.annotation.Nullable; - import java.util.Map; +import javax.annotation.Nullable; /** * Base class for Catalyst native modules whose implementations are written in Java. Default * implementations for {@link #initialize} and {@link #onCatalystInstanceDestroy} are provided for - * convenience. Subclasses which override these don't need to call {@code super} in case of + * convenience. Subclasses which override these don't need to call {@code super} in case of * overriding those methods as implementation of those methods is empty. * - * BaseJavaModules can be linked to Fragments' lifecycle events, {@link CatalystInstance} creation - * and destruction, by being called on the appropriate method when a life cycle event occurs. + *

BaseJavaModules can be linked to Fragments' lifecycle events, {@link CatalystInstance} + * creation and destruction, by being called on the appropriate method when a life cycle event + * occurs. * - * Native methods can be exposed to JS with {@link ReactMethod} annotation. Those methods may - * only use limited number of types for their arguments: - * 1/ primitives (boolean, int, float, double - * 2/ {@link String} mapped from JS string - * 3/ {@link ReadableArray} mapped from JS Array - * 4/ {@link ReadableMap} mapped from JS Object - * 5/ {@link Callback} mapped from js function and can be used only as a last parameter or in the - * case when it express success & error callback pair as two last arguments respectively. + *

Native methods can be exposed to JS with {@link ReactMethod} annotation. Those methods may + * only use limited number of types for their arguments: 1/ primitives (boolean, int, float, double + * 2/ {@link String} mapped from JS string 3/ {@link ReadableArray} mapped from JS Array 4/ {@link + * ReadableMap} mapped from JS Object 5/ {@link Callback} mapped from js function and can be used + * only as a last parameter or in the case when it express success & error callback pair as two last + * arguments respectively. * - * All methods exposed as native to JS with {@link ReactMethod} annotation must return - * {@code void}. + *

All methods exposed as native to JS with {@link ReactMethod} annotation must return {@code + * void}. * - * Please note that it is not allowed to have multiple methods annotated with {@link ReactMethod} + *

Please note that it is not allowed to have multiple methods annotated with {@link ReactMethod} * with the same name. */ public abstract class BaseJavaModule implements NativeModule { // taken from Libraries/Utilities/MessageQueue.js - static final public String METHOD_TYPE_ASYNC = "async"; - static final public String METHOD_TYPE_PROMISE= "promise"; - static final public String METHOD_TYPE_SYNC = "sync"; + public static final String METHOD_TYPE_ASYNC = "async"; + public static final String METHOD_TYPE_PROMISE = "promise"; + public static final String METHOD_TYPE_SYNC = "sync"; - /** - * @return a map of constants this module exports to JS. Supports JSON types. - */ + /** @return a map of constants this module exports to JS. Supports JSON types. */ public @Nullable Map getConstants() { return null; } diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/Callback.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/Callback.java index 26cb5b4c483..ed70293bece 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/Callback.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/Callback.java @@ -1,15 +1,14 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; /** - * Interface that represent javascript callback function which can be passed to the native module - * as a method parameter. + * Interface that represent javascript callback function which can be passed to the native module as + * a method parameter. */ public interface Callback { @@ -19,5 +18,4 @@ public interface Callback { * @param args arguments passed to javascript callback method via bridge */ public void invoke(Object... args); - } diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/CallbackImpl.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/CallbackImpl.java index 9bef1b06189..09de03d4e4b 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/CallbackImpl.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/CallbackImpl.java @@ -1,15 +1,12 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; -/** - * Implementation of javascript callback function that use Bridge to schedule method execution - */ +/** Implementation of javascript callback function that use Bridge to schedule method execution */ public final class CallbackImpl implements Callback { private final JSInstance mJSInstance; @@ -25,9 +22,10 @@ public final class CallbackImpl implements Callback { @Override public void invoke(Object... args) { if (mInvoked) { - throw new RuntimeException("Illegal callback invocation from native "+ - "module. This callback type only permits a single invocation from "+ - "native code."); + throw new RuntimeException( + "Illegal callback invocation from native " + + "module. This callback type only permits a single invocation from " + + "native code."); } mJSInstance.invokeCallback(mCallbackId, Arguments.fromJavaArgs(args)); mInvoked = true; diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/CatalystInstance.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/CatalystInstance.java index 97048de46d8..703386ff0a3 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/CatalystInstance.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/CatalystInstance.java @@ -1,25 +1,23 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; import com.facebook.proguard.annotations.DoNotStrip; import com.facebook.react.bridge.queue.ReactQueueConfiguration; import com.facebook.react.common.annotations.VisibleForTesting; import com.facebook.react.turbomodule.core.interfaces.JSCallInvokerHolder; -import com.facebook.react.turbomodule.core.interfaces.TurboModuleRegistry; import java.util.Collection; import java.util.List; import javax.annotation.Nullable; /** - * A higher level API on top of the asynchronous JSC bridge. This provides an - * environment allowing the invocation of JavaScript methods and lets a set of - * Java APIs be invokable from JavaScript as well. + * A higher level API on top of the asynchronous JSC bridge. This provides an environment allowing + * the invocation of JavaScript methods and lets a set of Java APIs be invokable from JavaScript as + * well. */ @DoNotStrip public interface CatalystInstance @@ -30,48 +28,50 @@ public interface CatalystInstance boolean hasRunJSBundle(); /** - * Return the source URL of the JS Bundle that was run, or {@code null} if no JS - * bundle has been run yet. + * Return the source URL of the JS Bundle that was run, or {@code null} if no JS bundle has been + * run yet. */ - @Nullable String getSourceURL(); + @Nullable + String getSourceURL(); // This is called from java code, so it won't be stripped anyway, but proguard will rename it, // which this prevents. - @Override @DoNotStrip - void invokeCallback( - int callbackID, - NativeArrayInterface arguments); + @Override @DoNotStrip - void callFunction( - String module, - String method, - NativeArray arguments); + void invokeCallback(int callbackID, NativeArrayInterface arguments); + + @DoNotStrip + void callFunction(String module, String method, NativeArray arguments); /** * Destroys this catalyst instance, waiting for any other threads in ReactQueueConfiguration * (besides the UI thread) to finish running. Must be called from the UI thread so that we can * fully shut down other threads. */ void destroy(); + boolean isDestroyed(); - /** - * Initialize all the native modules - */ + /** Initialize all the native modules */ @VisibleForTesting void initialize(); ReactQueueConfiguration getReactQueueConfiguration(); T getJSModule(Class jsInterface); + boolean hasNativeModule(Class nativeModuleInterface); + T getNativeModule(Class nativeModuleInterface); + NativeModule getNativeModule(String moduleName); + JSIModule getJSIModule(JSIModuleType moduleType); + Collection getNativeModules(); /** - * This method permits a CatalystInstance to extend the known - * Native modules. This provided registry contains only the new modules to load. + * This method permits a CatalystInstance to extend the known Native modules. This provided + * registry contains only the new modules to load. */ void extendNativeModules(NativeModuleRegistry modules); @@ -84,8 +84,8 @@ public interface CatalystInstance void addBridgeIdleDebugListener(NotThreadSafeBridgeIdleDebugListener listener); /** - * Removes a NotThreadSafeBridgeIdleDebugListener previously added with - * {@link #addBridgeIdleDebugListener} + * Removes a NotThreadSafeBridgeIdleDebugListener previously added with {@link + * #addBridgeIdleDebugListener} */ void removeBridgeIdleDebugListener(NotThreadSafeBridgeIdleDebugListener listener); @@ -107,16 +107,15 @@ public interface CatalystInstance void addJSIModules(List jsiModules); /** - * Returns a hybrid object that contains a pointer to JSCallInvoker. - * Required for TurboModuleManager initialization. + * Returns a hybrid object that contains a pointer to JSCallInvoker. Required for + * TurboModuleManager initialization. */ JSCallInvokerHolder getJSCallInvokerHolder(); /** - * For the time being, we want code relying on the old infra to also - * work with TurboModules. Hence, we must provide the TurboModuleRegistry - * to CatalystInstance so that getNativeModule, hasNativeModule, and - * getNativeModules can also return TurboModules. + * For the time being, we want code relying on the old infra to also work with TurboModules. + * Hence, we must provide the TurboModuleRegistry to CatalystInstance so that getNativeModule, + * hasNativeModule, and getNativeModules can also return TurboModules. */ void setTurboModuleManager(JSIModule getter); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/CatalystInstanceImpl.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/CatalystInstanceImpl.java index fc4d48dd162..d4867de3425 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/CatalystInstanceImpl.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/CatalystInstanceImpl.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; import static com.facebook.systrace.Systrace.TRACE_TAG_REACT_JAVA_BRIDGE; @@ -38,8 +37,8 @@ import java.util.concurrent.atomic.AtomicInteger; import javax.annotation.Nullable; /** - * This provides an implementation of the public CatalystInstance instance. It is public because - * it is built by XReactInstanceManager which is in a different package. + * This provides an implementation of the public CatalystInstance instance. It is public because it + * is built by XReactInstanceManager which is in a different package. */ @DoNotStrip public class CatalystInstanceImpl implements CatalystInstance { @@ -67,8 +66,12 @@ public class CatalystInstanceImpl implements CatalystInstance { } public String toString() { - return mModule + "." + mMethod + "(" - + (mArguments == null ? "" : mArguments.toString()) + ")"; + return mModule + + "." + + mMethod + + "(" + + (mArguments == null ? "" : mArguments.toString()) + + ")"; } } @@ -100,7 +103,9 @@ public class CatalystInstanceImpl implements CatalystInstance { // C++ parts private final HybridData mHybridData; - private native static HybridData initHybrid(); + + private static native HybridData initHybrid(); + public native JSCallInvokerHolderImpl getJSCallInvokerHolder(); private CatalystInstanceImpl( @@ -114,9 +119,9 @@ public class CatalystInstanceImpl implements CatalystInstance { mHybridData = initHybrid(); - mReactQueueConfiguration = ReactQueueConfigurationImpl.create( - reactQueueConfigurationSpec, - new NativeExceptionHandler()); + mReactQueueConfiguration = + ReactQueueConfigurationImpl.create( + reactQueueConfigurationSpec, new NativeExceptionHandler()); mBridgeIdleListeners = new CopyOnWriteArrayList<>(); mNativeModuleRegistry = nativeModuleRegistry; mJSModuleRegistry = new JavaScriptModuleRegistry(); @@ -129,12 +134,12 @@ public class CatalystInstanceImpl implements CatalystInstance { Log.d(ReactConstants.TAG, "Initializing React Xplat Bridge before initializeBridge"); Systrace.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "initializeCxxBridge"); initializeBridge( - new BridgeCallback(this), - jsExecutor, - mReactQueueConfiguration.getJSQueueThread(), - mNativeModulesQueueThread, - mNativeModuleRegistry.getJavaModules(this), - mNativeModuleRegistry.getCxxModules()); + new BridgeCallback(this), + jsExecutor, + mReactQueueConfiguration.getJSQueueThread(), + mNativeModulesQueueThread, + mNativeModuleRegistry.getJavaModules(this), + mNativeModuleRegistry.getCxxModules()); Log.d(ReactConstants.TAG, "Initializing React Xplat Bridge after initializeBridge"); Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE); @@ -177,24 +182,23 @@ public class CatalystInstanceImpl implements CatalystInstance { } /** - * This method and the native below permits a CatalystInstance to extend the known - * Native modules. This registry contains only the new modules to load. The - * registry {@code mNativeModuleRegistry} updates internally to contain all the new modules, and generates - * the new registry for extracting just the new collections. + * This method and the native below permits a CatalystInstance to extend the known Native modules. + * This registry contains only the new modules to load. The registry {@code mNativeModuleRegistry} + * updates internally to contain all the new modules, and generates the new registry for + * extracting just the new collections. */ @Override public void extendNativeModules(NativeModuleRegistry modules) { - //Extend the Java-visible registry of modules + // Extend the Java-visible registry of modules mNativeModuleRegistry.registerModules(modules); Collection javaModules = modules.getJavaModules(this); Collection cxxModules = modules.getCxxModules(); - //Extend the Cxx-visible registry of modules wrapped in appropriate interfaces + // Extend the Cxx-visible registry of modules wrapped in appropriate interfaces jniExtendNativeModules(javaModules, cxxModules); } private native void jniExtendNativeModules( - Collection javaModules, - Collection cxxModules); + Collection javaModules, Collection cxxModules); private native void initializeBridge( ReactCallback callback, @@ -216,7 +220,8 @@ public class CatalystInstanceImpl implements CatalystInstance { } @Override - public void loadScriptFromAssets(AssetManager assetManager, String assetURL, boolean loadSynchronously) { + public void loadScriptFromAssets( + AssetManager assetManager, String assetURL, boolean loadSynchronously) { mSourceURL = assetURL; jniLoadScriptFromAssets(assetManager, assetURL, loadSynchronously); } @@ -229,18 +234,23 @@ public class CatalystInstanceImpl implements CatalystInstance { @Override public void loadScriptFromDeltaBundle( - String sourceURL, - NativeDeltaClient deltaClient, - boolean loadSynchronously) { + String sourceURL, NativeDeltaClient deltaClient, boolean loadSynchronously) { mSourceURL = sourceURL; jniLoadScriptFromDeltaBundle(sourceURL, deltaClient, loadSynchronously); } private native void jniSetSourceURL(String sourceURL); + private native void jniRegisterSegment(int segmentId, String path); - private native void jniLoadScriptFromAssets(AssetManager assetManager, String assetURL, boolean loadSynchronously); - private native void jniLoadScriptFromFile(String fileName, String sourceURL, boolean loadSynchronously); - private native void jniLoadScriptFromDeltaBundle(String sourceURL, NativeDeltaClient deltaClient, boolean loadSynchronously); + + private native void jniLoadScriptFromAssets( + AssetManager assetManager, String assetURL, boolean loadSynchronously); + + private native void jniLoadScriptFromFile( + String fileName, String sourceURL, boolean loadSynchronously); + + private native void jniLoadScriptFromDeltaBundle( + String sourceURL, NativeDeltaClient deltaClient, boolean loadSynchronously); @Override public void runJSBundle() { @@ -279,16 +289,10 @@ public class CatalystInstanceImpl implements CatalystInstance { return mSourceURL; } - private native void jniCallJSFunction( - String module, - String method, - NativeArray arguments); + private native void jniCallJSFunction(String module, String method, NativeArray arguments); @Override - public void callFunction( - final String module, - final String method, - final NativeArray arguments) { + public void callFunction(final String module, final String method, final NativeArray arguments) { callFunction(new PendingJSCall(module, method, arguments)); } @@ -385,29 +389,25 @@ public class CatalystInstanceImpl implements CatalystInstance { return mDestroyed; } - /** - * Initialize all the native modules - */ + /** Initialize all the native modules */ @VisibleForTesting @Override public void initialize() { Log.d(ReactConstants.TAG, "CatalystInstanceImpl.initialize()"); Assertions.assertCondition( - !mInitialized, - "This catalyst instance has already been initialized"); + !mInitialized, "This catalyst instance has already been initialized"); // We assume that the instance manager blocks on running the JS bundle. If // that changes, then we need to set mAcceptCalls just after posting the // task that will run the js bundle. - Assertions.assertCondition( - mAcceptCalls, - "RunJSBundle hasn't completed."); + Assertions.assertCondition(mAcceptCalls, "RunJSBundle hasn't completed."); mInitialized = true; - mNativeModulesQueueThread.runOnQueue(new Runnable() { - @Override - public void run() { - mNativeModuleRegistry.notifyJSInstanceInitialized(); - } - }); + mNativeModulesQueueThread.runOnQueue( + new Runnable() { + @Override + public void run() { + mNativeModuleRegistry.notifyJSInstanceInitialized(); + } + }); } @Override @@ -423,7 +423,9 @@ public class CatalystInstanceImpl implements CatalystInstance { @Override public boolean hasNativeModule(Class nativeModuleInterface) { String moduleName = getNameFromAnnotation(nativeModuleInterface); - return mTurboModuleRegistry != null && mTurboModuleRegistry.hasModule(moduleName) ? true : mNativeModuleRegistry.hasModule(moduleName); + return mTurboModuleRegistry != null && mTurboModuleRegistry.hasModule(moduleName) + ? true + : mNativeModuleRegistry.hasModule(moduleName); } @Override @@ -437,17 +439,18 @@ public class CatalystInstanceImpl implements CatalystInstance { TurboModule turboModule = mTurboModuleRegistry.getModule(moduleName); if (turboModule != null) { - return (NativeModule)turboModule; + return (NativeModule) turboModule; } } return mNativeModuleRegistry.getModule(moduleName); } - private String getNameFromAnnotation(Class nativeModuleInterface){ + private String getNameFromAnnotation(Class nativeModuleInterface) { ReactModule annotation = nativeModuleInterface.getAnnotation(ReactModule.class); if (annotation == null) { - throw new IllegalArgumentException("Could not find @ReactModule annotation in " + nativeModuleInterface.getCanonicalName()); + throw new IllegalArgumentException( + "Could not find @ReactModule annotation in " + nativeModuleInterface.getCanonicalName()); } return annotation.name(); } @@ -489,8 +492,8 @@ public class CatalystInstanceImpl implements CatalystInstance { } /** - * Removes a NotThreadSafeBridgeIdleDebugListener previously added with - * {@link #addBridgeIdleDebugListener} + * Removes a NotThreadSafeBridgeIdleDebugListener previously added with {@link + * #addBridgeIdleDebugListener} */ @Override public void removeBridgeIdleDebugListener(NotThreadSafeBridgeIdleDebugListener listener) { @@ -521,56 +524,56 @@ public class CatalystInstanceImpl implements CatalystInstance { int oldPendingCalls = mPendingJSCalls.getAndIncrement(); boolean wasIdle = oldPendingCalls == 0; Systrace.traceCounter( - Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, - mJsPendingCallsTitleForTrace, - oldPendingCalls + 1); + Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, mJsPendingCallsTitleForTrace, oldPendingCalls + 1); if (wasIdle && !mBridgeIdleListeners.isEmpty()) { - mNativeModulesQueueThread.runOnQueue(new Runnable() { - @Override - public void run() { - for (NotThreadSafeBridgeIdleDebugListener listener : mBridgeIdleListeners) { - listener.onTransitionToBridgeBusy(); - } - } - }); + mNativeModulesQueueThread.runOnQueue( + new Runnable() { + @Override + public void run() { + for (NotThreadSafeBridgeIdleDebugListener listener : mBridgeIdleListeners) { + listener.onTransitionToBridgeBusy(); + } + } + }); } } public void setTurboModuleManager(JSIModule getter) { - mTurboModuleRegistry = (TurboModuleRegistry)getter; + mTurboModuleRegistry = (TurboModuleRegistry) getter; } private void decrementPendingJSCalls() { int newPendingCalls = mPendingJSCalls.decrementAndGet(); // TODO(9604406): handle case of web workers injecting messages to main thread - //Assertions.assertCondition(newPendingCalls >= 0); + // Assertions.assertCondition(newPendingCalls >= 0); boolean isNowIdle = newPendingCalls == 0; Systrace.traceCounter( - Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, - mJsPendingCallsTitleForTrace, - newPendingCalls); + Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, mJsPendingCallsTitleForTrace, newPendingCalls); if (isNowIdle && !mBridgeIdleListeners.isEmpty()) { - mNativeModulesQueueThread.runOnQueue(new Runnable() { - @Override - public void run() { - for (NotThreadSafeBridgeIdleDebugListener listener : mBridgeIdleListeners) { - listener.onTransitionToBridgeIdle(); - } - } - }); + mNativeModulesQueueThread.runOnQueue( + new Runnable() { + @Override + public void run() { + for (NotThreadSafeBridgeIdleDebugListener listener : mBridgeIdleListeners) { + listener.onTransitionToBridgeIdle(); + } + } + }); } } private void onNativeException(Exception e) { mNativeModuleCallExceptionHandler.handleException(e); - mReactQueueConfiguration.getUIQueueThread().runOnQueue( - new Runnable() { - @Override - public void run() { - destroy(); - } - }); + mReactQueueConfiguration + .getUIQueueThread() + .runOnQueue( + new Runnable() { + @Override + public void run() { + destroy(); + } + }); } private class NativeExceptionHandler implements QueueThreadExceptionHandler { @@ -619,7 +622,6 @@ public class CatalystInstanceImpl implements CatalystInstance { private @Nullable JavaScriptExecutor mJSExecutor; private @Nullable NativeModuleCallExceptionHandler mNativeModuleCallExceptionHandler; - public Builder setReactQueueConfigurationSpec( ReactQueueConfigurationSpec ReactQueueConfigurationSpec) { mReactQueueConfigurationSpec = ReactQueueConfigurationSpec; @@ -641,8 +643,7 @@ public class CatalystInstanceImpl implements CatalystInstance { return this; } - public Builder setNativeModuleCallExceptionHandler( - NativeModuleCallExceptionHandler handler) { + public Builder setNativeModuleCallExceptionHandler(NativeModuleCallExceptionHandler handler) { mNativeModuleCallExceptionHandler = handler; return this; } diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/ContextBaseJavaModule.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/ContextBaseJavaModule.java index fc68cb84bff..6ee6730b0d6 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/ContextBaseJavaModule.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/ContextBaseJavaModule.java @@ -1,17 +1,15 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; import android.content.Context; /** - * Base class for React native modules that require access to an Android - * {@link Context} instance. + * Base class for React native modules that require access to an Android {@link Context} instance. */ public abstract class ContextBaseJavaModule extends BaseJavaModule { @@ -21,9 +19,7 @@ public abstract class ContextBaseJavaModule extends BaseJavaModule { mContext = context; } - /** - * Subclasses can use this method to access Android context passed as a constructor - */ + /** Subclasses can use this method to access Android context passed as a constructor */ protected final Context getContext() { return mContext; } diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/CxxCallbackImpl.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/CxxCallbackImpl.java index 839da9a704b..ba20cd72014 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/CxxCallbackImpl.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/CxxCallbackImpl.java @@ -5,20 +5,15 @@ package com.facebook.react.bridge; -import com.facebook.jni.HybridData; -import com.facebook.proguard.annotations.DoNotStrip; -import com.facebook.react.bridge.Callback; -import com.facebook.react.bridge.NativeArray; - import static com.facebook.react.bridge.Arguments.*; -/** - * Callback impl that calls directly into the cxx bridge. Created from C++. - */ +import com.facebook.jni.HybridData; +import com.facebook.proguard.annotations.DoNotStrip; + +/** Callback impl that calls directly into the cxx bridge. Created from C++. */ @DoNotStrip public class CxxCallbackImpl implements Callback { - @DoNotStrip - private final HybridData mHybridData; + @DoNotStrip private final HybridData mHybridData; @DoNotStrip private CxxCallbackImpl(HybridData hybridData) { diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/CxxModuleWrapper.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/CxxModuleWrapper.java index a60704ecb42..cb9f15d41e3 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/CxxModuleWrapper.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/CxxModuleWrapper.java @@ -9,12 +9,9 @@ import com.facebook.jni.HybridData; import com.facebook.proguard.annotations.DoNotStrip; import com.facebook.soloader.SoLoader; -/** - * This does nothing interesting, except avoid breaking existing code. - */ +/** This does nothing interesting, except avoid breaking existing code. */ @DoNotStrip -public class CxxModuleWrapper extends CxxModuleWrapperBase -{ +public class CxxModuleWrapper extends CxxModuleWrapperBase { protected CxxModuleWrapper(HybridData hd) { super(hd); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/CxxModuleWrapperBase.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/CxxModuleWrapperBase.java index 1fa8e97019f..7c7284ffd49 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/CxxModuleWrapperBase.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/CxxModuleWrapperBase.java @@ -11,18 +11,16 @@ import com.facebook.proguard.annotations.DoNotStrip; /** * A Java Object which represents a cross-platform C++ module * - * This module implements the NativeModule interface but will never be invoked from Java, - * instead the underlying Cxx module will be extracted by the bridge and called directly. + *

This module implements the NativeModule interface but will never be invoked from Java, instead + * the underlying Cxx module will be extracted by the bridge and called directly. */ @DoNotStrip -public class CxxModuleWrapperBase implements NativeModule -{ +public class CxxModuleWrapperBase implements NativeModule { static { ReactBridge.staticInit(); } - @DoNotStrip - private HybridData mHybridData; + @DoNotStrip private HybridData mHybridData; @Override public native String getName(); diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/DefaultNativeModuleCallExceptionHandler.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/DefaultNativeModuleCallExceptionHandler.java index 0204a14e873..a8866d0b16e 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/DefaultNativeModuleCallExceptionHandler.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/DefaultNativeModuleCallExceptionHandler.java @@ -1,15 +1,12 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; -/** - * Crashy crashy exception handler. - */ +/** Crashy crashy exception handler. */ public class DefaultNativeModuleCallExceptionHandler implements NativeModuleCallExceptionHandler { @Override diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/Dynamic.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/Dynamic.java index 67f414ddff6..bddf4fddaed 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/Dynamic.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/Dynamic.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; /** @@ -13,12 +12,20 @@ package com.facebook.react.bridge; */ public interface Dynamic { boolean isNull(); + boolean asBoolean(); + double asDouble(); + int asInt(); + String asString(); + ReadableArray asArray(); + ReadableMap asMap(); + ReadableType getType(); + void recycle(); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/DynamicFromArray.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/DynamicFromArray.java index d05a80d295c..39e310d278c 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/DynamicFromArray.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/DynamicFromArray.java @@ -1,19 +1,15 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; +import androidx.core.util.Pools; import javax.annotation.Nullable; -import androidx.core.util.Pools; - -/** - * Implementation of Dynamic wrapping a ReadableArray. - */ +/** Implementation of Dynamic wrapping a ReadableArray. */ public class DynamicFromArray implements Dynamic { private static final Pools.SimplePool sPool = new Pools.SimplePool<>(10); diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/DynamicFromMap.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/DynamicFromMap.java index 2d0ef04cf4b..360b22934e7 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/DynamicFromMap.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/DynamicFromMap.java @@ -1,26 +1,23 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; +import androidx.core.util.Pools.SimplePool; import javax.annotation.Nullable; -import androidx.core.util.Pools.SimplePool; - -/** - * Implementation of Dynamic wrapping a ReadableMap. - */ +/** Implementation of Dynamic wrapping a ReadableMap. */ public class DynamicFromMap implements Dynamic { - private static final ThreadLocal> sPool = new ThreadLocal>() { - @Override - protected SimplePool initialValue() { - return new SimplePool<>(10); - } - }; + private static final ThreadLocal> sPool = + new ThreadLocal>() { + @Override + protected SimplePool initialValue() { + return new SimplePool<>(10); + } + }; private @Nullable ReadableMap mMap; private @Nullable String mName; diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/DynamicFromObject.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/DynamicFromObject.java index 3f7f24bf02b..e9104db1901 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/DynamicFromObject.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/DynamicFromObject.java @@ -1,19 +1,16 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; import com.facebook.common.logging.FLog; import com.facebook.react.common.ReactConstants; import javax.annotation.Nullable; -/** - * Implementation of Dynamic wrapping a ReadableArray. - */ +/** Implementation of Dynamic wrapping a ReadableArray. */ public class DynamicFromObject implements Dynamic { private @Nullable Object mObject; @@ -33,33 +30,33 @@ public class DynamicFromObject implements Dynamic { @Override public boolean asBoolean() { - return (boolean)mObject; + return (boolean) mObject; } @Override public double asDouble() { - return (double)mObject; + return (double) mObject; } @Override public int asInt() { // Numbers from JS are always Doubles - return ((Double)mObject).intValue(); + return ((Double) mObject).intValue(); } @Override public String asString() { - return (String)mObject; + return (String) mObject; } @Override public ReadableArray asArray() { - return (ReadableArray)mObject; + return (ReadableArray) mObject; } @Override public ReadableMap asMap() { - return (ReadableMap)mObject; + return (ReadableMap) mObject; } @Override diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/FallbackJSBundleLoader.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/FallbackJSBundleLoader.java index 50c47aa8a18..d66802a7707 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/FallbackJSBundleLoader.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/FallbackJSBundleLoader.java @@ -1,25 +1,23 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; +import com.facebook.common.logging.FLog; import java.util.ArrayList; import java.util.List; import java.util.ListIterator; import java.util.Stack; -import com.facebook.common.logging.FLog; - /** * FallbackJSBundleLoader * - * An implementation of {@link JSBundleLoader} that will try to load from - * multiple sources, falling back from one source to the next at load time - * when an exception is thrown for a recoverable error. + *

An implementation of {@link JSBundleLoader} that will try to load from multiple sources, + * falling back from one source to the next at load time when an exception is thrown for a + * recoverable error. */ public final class FallbackJSBundleLoader extends JSBundleLoader { @@ -32,10 +30,7 @@ public final class FallbackJSBundleLoader extends JSBundleLoader { // Reasons why we fell-back on previous loaders, in order of occurrence. private final ArrayList mRecoveredErrors = new ArrayList<>(); - /** - * @param loaders Loaders for the sources to try, in descending order of - * preference. - */ + /** @param loaders Loaders for the sources to try, in descending order of preference. */ public FallbackJSBundleLoader(List loaders) { mLoaders = new Stack(); ListIterator it = loaders.listIterator(loaders.size()); @@ -45,9 +40,9 @@ public final class FallbackJSBundleLoader extends JSBundleLoader { } /** - * This loader delegates to (and so behaves like) the currently preferred - * loader. If that loader fails in a recoverable way and we fall back from it, - * it is replaced by the next most preferred loader. + * This loader delegates to (and so behaves like) the currently preferred loader. If that loader + * fails in a recoverable way and we fall back from it, it is replaced by the next most preferred + * loader. */ @Override public String loadScript(JSBundleLoaderDelegate delegate) { @@ -71,8 +66,7 @@ public final class FallbackJSBundleLoader extends JSBundleLoader { return mLoaders.peek(); } - RuntimeException fallbackException = - new RuntimeException("No fallback options available"); + RuntimeException fallbackException = new RuntimeException("No fallback options available"); // Invariant: tail.getCause() == null Throwable tail = fallbackException; diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/GuardedAsyncTask.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/GuardedAsyncTask.java index 9b81961efee..eee4aeccd3b 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/GuardedAsyncTask.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/GuardedAsyncTask.java @@ -1,24 +1,22 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; import android.os.AsyncTask; /** - * Abstract base for a AsyncTask that should have any RuntimeExceptions it throws - * handled by the {@link com.facebook.react.bridge.NativeModuleCallExceptionHandler} registered if - * the app is in dev mode. + * Abstract base for a AsyncTask that should have any RuntimeExceptions it throws handled by the + * {@link com.facebook.react.bridge.NativeModuleCallExceptionHandler} registered if the app is in + * dev mode. * - * This class doesn't allow doInBackground to return a results. If you need this - * use GuardedResultAsyncTask instead. + *

This class doesn't allow doInBackground to return a results. If you need this use + * GuardedResultAsyncTask instead. */ -public abstract class GuardedAsyncTask - extends AsyncTask { +public abstract class GuardedAsyncTask extends AsyncTask { private final ReactContext mReactContext; diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/GuardedResultAsyncTask.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/GuardedResultAsyncTask.java index df0d857186b..5937167b629 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/GuardedResultAsyncTask.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/GuardedResultAsyncTask.java @@ -12,8 +12,7 @@ import android.os.AsyncTask; * throws handled by the {@link com.facebook.react.bridge.NativeModuleCallExceptionHandler} * registered if the app is in dev mode. */ -public abstract class GuardedResultAsyncTask - extends AsyncTask { +public abstract class GuardedResultAsyncTask extends AsyncTask { private final ReactContext mReactContext; @@ -41,6 +40,6 @@ public abstract class GuardedResultAsyncTask } protected abstract Result doInBackgroundGuarded(); - protected abstract void onPostExecuteGuarded(Result result); + protected abstract void onPostExecuteGuarded(Result result); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/GuardedRunnable.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/GuardedRunnable.java index b550cbaeade..78346ada610 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/GuardedRunnable.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/GuardedRunnable.java @@ -6,9 +6,9 @@ package com.facebook.react.bridge; /** - * Abstract base for a Runnable that should have any RuntimeExceptions it throws - * handled by the {@link com.facebook.react.bridge.NativeModuleCallExceptionHandler} registered if - * the app is in dev mode. + * Abstract base for a Runnable that should have any RuntimeExceptions it throws handled by the + * {@link com.facebook.react.bridge.NativeModuleCallExceptionHandler} registered if the app is in + * dev mode. */ public abstract class GuardedRunnable implements Runnable { diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/Inspector.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/Inspector.java index 44ef6b7b826..70586da45ac 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/Inspector.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/Inspector.java @@ -5,14 +5,13 @@ package com.facebook.react.bridge; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - import com.facebook.common.logging.FLog; import com.facebook.jni.HybridData; import com.facebook.proguard.annotations.DoNotStrip; import com.facebook.react.common.ReactConstants; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; @DoNotStrip public class Inspector { @@ -70,10 +69,7 @@ public class Inspector { @Override public String toString() { - return "Page{" + - "mId=" + mId + - ", mTitle='" + mTitle + '\'' + - '}'; + return "Page{" + "mId=" + mId + ", mTitle='" + mTitle + '\'' + '}'; } @DoNotStrip @@ -88,6 +84,7 @@ public class Inspector { public interface RemoteConnection { @DoNotStrip void onMessage(String message); + @DoNotStrip void onDisconnect(); } @@ -97,6 +94,7 @@ public class Inspector { private final HybridData mHybridData; public native void sendMessage(String message); + public native void disconnect(); private LocalConnection(HybridData hybridData) { diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/InvalidIteratorException.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/InvalidIteratorException.java index c13de24f45b..0eafddb293b 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/InvalidIteratorException.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/InvalidIteratorException.java @@ -1,17 +1,16 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; import com.facebook.proguard.annotations.DoNotStrip; /** - * Exception thrown by {@link ReadableMapKeySetIterator#nextKey()} when the iterator tries - * to iterate over elements after the end of the key set. + * Exception thrown by {@link ReadableMapKeySetIterator#nextKey()} when the iterator tries to + * iterate over elements after the end of the key set. */ @DoNotStrip public class InvalidIteratorException extends RuntimeException { diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/JSApplicationCausedNativeException.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/JSApplicationCausedNativeException.java index 078b042e7b6..6adb752a629 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/JSApplicationCausedNativeException.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/JSApplicationCausedNativeException.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; import javax.annotation.Nullable; @@ -13,19 +12,18 @@ import javax.annotation.Nullable; * A special RuntimeException that should be thrown by native code if it has reached an exceptional * state due to a, or a sequence of, bad commands. * - * A good rule of thumb for whether a native Exception should extend this interface is 1) Can a + *

A good rule of thumb for whether a native Exception should extend this interface is 1) Can a * developer make a change or correction in JS to keep this Exception from being thrown? 2) Is the * app outside of this catalyst instance still in a good state to allow reloading and restarting * this catalyst instance? * - * Examples where this class is appropriate to throw: - * - JS tries to update a view with a tag that hasn't been created yet - * - JS tries to show a static image that isn't in resources - * - JS tries to use an unsupported view class + *

Examples where this class is appropriate to throw: - JS tries to update a view with a tag that + * hasn't been created yet - JS tries to show a static image that isn't in resources - JS tries to + * use an unsupported view class * - * Examples where this class **isn't** appropriate to throw: - * - Failed to write to localStorage because disk is full - * - Assertions about internal state (e.g. that child.getParent().indexOf(child) != -1) + *

Examples where this class **isn't** appropriate to throw: - Failed to write to localStorage + * because disk is full - Assertions about internal state (e.g. that + * child.getParent().indexOf(child) != -1) */ public class JSApplicationCausedNativeException extends RuntimeException { @@ -34,8 +32,7 @@ public class JSApplicationCausedNativeException extends RuntimeException { } public JSApplicationCausedNativeException( - @Nullable String detailMessage, - @Nullable Throwable throwable) { + @Nullable String detailMessage, @Nullable Throwable throwable) { super(detailMessage, throwable); } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/JSApplicationIllegalArgumentException.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/JSApplicationIllegalArgumentException.java index 365ac08bd19..887480dcdc0 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/JSApplicationIllegalArgumentException.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/JSApplicationIllegalArgumentException.java @@ -1,15 +1,12 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; -/** - * An illegal argument Exception caused by an argument passed from JS. - */ +/** An illegal argument Exception caused by an argument passed from JS. */ public class JSApplicationIllegalArgumentException extends JSApplicationCausedNativeException { public JSApplicationIllegalArgumentException(String detailMessage) { diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/JSBundleLoader.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/JSBundleLoader.java index 9a67632c5c3..12b35eb17a8 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/JSBundleLoader.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/JSBundleLoader.java @@ -1,18 +1,17 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; import android.content.Context; import com.facebook.react.common.DebugServerException; /** - * A class that stores JS bundle information and allows a {@link JSBundleLoaderDelegate} - * (e.g. {@link CatalystInstance}) to load a correct bundle through {@link ReactBridge}. + * A class that stores JS bundle information and allows a {@link JSBundleLoaderDelegate} (e.g. + * {@link CatalystInstance}) to load a correct bundle through {@link ReactBridge}. */ public abstract class JSBundleLoader { @@ -22,9 +21,7 @@ public abstract class JSBundleLoader { * strings from java to native memory. */ public static JSBundleLoader createAssetLoader( - final Context context, - final String assetUrl, - final boolean loadSynchronously) { + final Context context, final String assetUrl, final boolean loadSynchronously) { return new JSBundleLoader() { @Override public String loadScript(JSBundleLoaderDelegate delegate) { @@ -43,9 +40,7 @@ public abstract class JSBundleLoader { } public static JSBundleLoader createFileLoader( - final String fileName, - final String assetUrl, - final boolean loadSynchronously) { + final String fileName, final String assetUrl, final boolean loadSynchronously) { return new JSBundleLoader() { @Override public String loadScript(JSBundleLoaderDelegate delegate) { @@ -63,8 +58,7 @@ public abstract class JSBundleLoader { * work correctly and allows for source maps to correctly symbolize those. */ public static JSBundleLoader createCachedBundleFromNetworkLoader( - final String sourceURL, - final String cachedFileLocation) { + final String sourceURL, final String cachedFileLocation) { return new JSBundleLoader() { @Override public String loadScript(JSBundleLoaderDelegate delegate) { @@ -82,11 +76,11 @@ public abstract class JSBundleLoader { * This loader is used to load delta bundles from the dev server. We pass each delta message to * the loader and process it in C++. Passing it as a string leads to inefficiencies due to memory * copies, which will have to be addressed in a follow-up. + * * @param nativeDeltaClient */ public static JSBundleLoader createDeltaFromNetworkLoader( - final String sourceURL, - final NativeDeltaClient nativeDeltaClient) { + final String sourceURL, final NativeDeltaClient nativeDeltaClient) { return new JSBundleLoader() { @Override public String loadScript(JSBundleLoaderDelegate delegate) { @@ -105,8 +99,7 @@ public abstract class JSBundleLoader { * the bundle from device as remote executor will have to do it anyway. */ public static JSBundleLoader createRemoteDebuggerBundleLoader( - final String proxySourceURL, - final String realSourceURL) { + final String proxySourceURL, final String realSourceURL) { return new JSBundleLoader() { @Override public String loadScript(JSBundleLoaderDelegate delegate) { diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/JSBundleLoaderDelegate.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/JSBundleLoaderDelegate.java index 29c3af69d59..b21c5b6887d 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/JSBundleLoaderDelegate.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/JSBundleLoaderDelegate.java @@ -1,22 +1,21 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; import android.content.Context; import android.content.res.AssetManager; -/** - * An interface for classes that initialize JavaScript using {@link JSBundleLoader} - */ +/** An interface for classes that initialize JavaScript using {@link JSBundleLoader} */ public interface JSBundleLoaderDelegate { /** - * Load a JS bundle from Android assets. See {@link JSBundleLoader#createAssetLoader(Context, String, boolean)} + * Load a JS bundle from Android assets. See {@link JSBundleLoader#createAssetLoader(Context, + * String, boolean)} + * * @param assetManager * @param assetURL * @param loadSynchronously @@ -24,8 +23,9 @@ public interface JSBundleLoaderDelegate { void loadScriptFromAssets(AssetManager assetManager, String assetURL, boolean loadSynchronously); /** - * Load a JS bundle from the filesystem. - * See {@link JSBundleLoader#createFileLoader(String)} and {@link JSBundleLoader#createCachedBundleFromNetworkLoader(String, String)} + * Load a JS bundle from the filesystem. See {@link JSBundleLoader#createFileLoader(String)} and + * {@link JSBundleLoader#createCachedBundleFromNetworkLoader(String, String)} + * * @param fileName * @param sourceURL * @param loadSynchronously @@ -33,26 +33,23 @@ public interface JSBundleLoaderDelegate { void loadScriptFromFile(String fileName, String sourceURL, boolean loadSynchronously); /** - * Load a delta bundle from Metro. - * See {@link JSBundleLoader#createDeltaFromNetworkLoader(String, NativeDeltaClient)} + * Load a delta bundle from Metro. See {@link JSBundleLoader#createDeltaFromNetworkLoader(String, + * NativeDeltaClient)} + * * @param sourceURL * @param deltaClient * @param loadSynchronously */ void loadScriptFromDeltaBundle( - String sourceURL, - NativeDeltaClient deltaClient, - boolean loadSynchronously); + String sourceURL, NativeDeltaClient deltaClient, boolean loadSynchronously); /** - * This API is used in situations where the JS bundle is being executed not on - * the device, but on a host machine. In that case, we must provide two source - * URLs for the JS bundle: One to be used on the device, and one to be used on - * the remote debugging machine. + * This API is used in situations where the JS bundle is being executed not on the device, but on + * a host machine. In that case, we must provide two source URLs for the JS bundle: One to be used + * on the device, and one to be used on the remote debugging machine. * * @param deviceURL A source URL that is accessible from this device. - * @param remoteURL A source URL that is accessible from the remote machine - * executing the JS. + * @param remoteURL A source URL that is accessible from the remote machine executing the JS. */ void setSourceURLs(String deviceURL, String remoteURL); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/JSCJavaScriptExecutor.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/JSCJavaScriptExecutor.java index 08e6ca3ad44..b7090caaf0a 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/JSCJavaScriptExecutor.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/JSCJavaScriptExecutor.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; import com.facebook.jni.HybridData; @@ -25,6 +24,5 @@ import com.facebook.proguard.annotations.DoNotStrip; return "JSCJavaScriptExecutor"; } - - private native static HybridData initHybrid(ReadableNativeMap jscConfig); + private static native HybridData initHybrid(ReadableNativeMap jscConfig); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/JSCJavaScriptExecutorFactory.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/JSCJavaScriptExecutorFactory.java index 7fe2f16403c..ed60de01710 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/JSCJavaScriptExecutorFactory.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/JSCJavaScriptExecutorFactory.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; public class JSCJavaScriptExecutorFactory implements JavaScriptExecutorFactory { diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/JSIModule.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/JSIModule.java index 43b1d3349b5..54c232ac490 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/JSIModule.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/JSIModule.java @@ -1,26 +1,21 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; -/** - * Marker interface used to represent a JSI Module. - */ +/** Marker interface used to represent a JSI Module. */ public interface JSIModule { /** - * This is called at the end of {@link CatalystApplicationFragment#createCatalystInstance()} - * after the CatalystInstance has been created, in order to initialize NativeModules that require - * the CatalystInstance or JS modules. + * This is called at the end of {@link CatalystApplicationFragment#createCatalystInstance()} after + * the CatalystInstance has been created, in order to initialize NativeModules that require the + * CatalystInstance or JS modules. */ void initialize(); - /** - * Called before {CatalystInstance#onHostDestroy} - */ + /** Called before {CatalystInstance#onHostDestroy} */ void onCatalystInstanceDestroy(); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/JSIModuleHolder.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/JSIModuleHolder.java index 7e7f4b0914c..c8ec6687dac 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/JSIModuleHolder.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/JSIModuleHolder.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; public class JSIModuleHolder { diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/JSIModulePackage.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/JSIModulePackage.java index e5c28700b83..430cd9b61ed 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/JSIModulePackage.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/JSIModulePackage.java @@ -1,22 +1,17 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; import java.util.List; -/** - * Interface used to initialize JSI Modules into the JSI Bridge. - */ +/** Interface used to initialize JSI Modules into the JSI Bridge. */ public interface JSIModulePackage { - /** - * @return a {@link List< JSIModuleSpec >} that contain the list of JSI Modules. - */ - List getJSIModules(ReactApplicationContext reactApplicationContext, JavaScriptContextHolder jsContext); - + /** @return a {@link List< JSIModuleSpec >} that contain the list of JSI Modules. */ + List getJSIModules( + ReactApplicationContext reactApplicationContext, JavaScriptContextHolder jsContext); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/JSIModuleProvider.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/JSIModuleProvider.java index d8c3765878c..fc3987a9d8a 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/JSIModuleProvider.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/JSIModuleProvider.java @@ -1,14 +1,12 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; public interface JSIModuleProvider { T get(); - } diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/JSIModuleRegistry.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/JSIModuleRegistry.java index 46c7868f727..7c4ded025f8 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/JSIModuleRegistry.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/JSIModuleRegistry.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; import com.facebook.infer.annotation.Assertions; @@ -16,7 +15,7 @@ public class JSIModuleRegistry { private final Map mModules = new HashMap<>(); - public JSIModuleRegistry() { } + public JSIModuleRegistry() {} public JSIModule getModule(JSIModuleType moduleType) { JSIModuleHolder jsiModuleHolder = mModules.get(moduleType); diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/JSIModuleSpec.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/JSIModuleSpec.java index 2e8379f7fcd..73ccbe3aa16 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/JSIModuleSpec.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/JSIModuleSpec.java @@ -1,19 +1,15 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; -/** - * Holder class used to register {@link JSIModule} into JSI Bridge. - */ +/** Holder class used to register {@link JSIModule} into JSI Bridge. */ public interface JSIModuleSpec { JSIModuleType getJSIModuleType(); JSIModuleProvider getJSIModuleProvider(); - } diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/JSIModuleType.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/JSIModuleType.java index 99fb9b3e8c5..b64240682e3 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/JSIModuleType.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/JSIModuleType.java @@ -1,15 +1,14 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; /** - * A list of support JSIModules. These are usually core infra pieces, so there - * should be an explicit list. + * A list of support JSIModules. These are usually core infra pieces, so there should be an explicit + * list. */ public enum JSIModuleType { TurboModuleManager, diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/JSInstance.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/JSInstance.java index a20ee7089b2..75d101335a9 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/JSInstance.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/JSInstance.java @@ -1,21 +1,17 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; /** - * This interface includes the methods needed to use a running JS - * instance, without specifying any of the bridge-specific - * initialization or lifecycle management. + * This interface includes the methods needed to use a running JS instance, without specifying any + * of the bridge-specific initialization or lifecycle management. */ public interface JSInstance { - void invokeCallback( - int callbackID, - NativeArrayInterface arguments); + void invokeCallback(int callbackID, NativeArrayInterface arguments); // TODO if this interface survives refactoring, think about adding // callFunction. } diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/JavaJSExecutor.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/JavaJSExecutor.java index 4f6c057631e..577b7098a09 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/JavaJSExecutor.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/JavaJSExecutor.java @@ -1,18 +1,17 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; import com.facebook.proguard.annotations.DoNotStrip; /** - * This is class represents java version of native js executor interface. When set through - * {@link ProxyJavaScriptExecutor} as a {@link CatalystInstance} executor, native code will - * delegate js calls to the given implementation of this interface. + * This is class represents java version of native js executor interface. When set through {@link + * ProxyJavaScriptExecutor} as a {@link CatalystInstance} executor, native code will delegate js + * calls to the given implementation of this interface. */ @DoNotStrip public interface JavaJSExecutor { @@ -27,13 +26,14 @@ public interface JavaJSExecutor { } /** - * Close this executor and cleanup any resources that it was using. No further calls are - * expected after this. + * Close this executor and cleanup any resources that it was using. No further calls are expected + * after this. */ void close(); /** * Load javascript into the js context + * * @param sourceURL url or file location from which script content was loaded */ @DoNotStrip @@ -41,13 +41,13 @@ public interface JavaJSExecutor { /** * Execute javascript method within js context + * * @param methodName name of the method to be executed * @param jsonArgsArray json encoded array of arguments provided for the method call * @return json encoded value returned from the method call */ @DoNotStrip - String executeJSCall(String methodName, String jsonArgsArray) - throws ProxyExecutorException; + String executeJSCall(String methodName, String jsonArgsArray) throws ProxyExecutorException; @DoNotStrip void setGlobalVariable(String propertyName, String jsonEncodedValue); diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/JavaMethodWrapper.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/JavaMethodWrapper.java index 3a8bfcda2ee..edf5cfbf96d 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/JavaMethodWrapper.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/JavaMethodWrapper.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; import static com.facebook.infer.annotation.Assertions.assertNotNull; @@ -20,118 +19,118 @@ import javax.annotation.Nullable; public class JavaMethodWrapper implements NativeModule.NativeMethod { - private static abstract class ArgumentExtractor { + private abstract static class ArgumentExtractor { public int getJSArgumentsNeeded() { return 1; } public abstract @Nullable T extractArgument( - JSInstance jsInstance, ReadableArray jsArguments, int atIndex); + JSInstance jsInstance, ReadableArray jsArguments, int atIndex); } - static final private ArgumentExtractor ARGUMENT_EXTRACTOR_BOOLEAN = - new ArgumentExtractor() { - @Override - public Boolean extractArgument( - JSInstance jsInstance, ReadableArray jsArguments, int atIndex) { - return jsArguments.getBoolean(atIndex); - } - }; - - static final private ArgumentExtractor ARGUMENT_EXTRACTOR_DOUBLE = - new ArgumentExtractor() { - @Override - public Double extractArgument( - JSInstance jsInstance, ReadableArray jsArguments, int atIndex) { - return jsArguments.getDouble(atIndex); - } - }; - - static final private ArgumentExtractor ARGUMENT_EXTRACTOR_FLOAT = - new ArgumentExtractor() { - @Override - public Float extractArgument( - JSInstance jsInstance, ReadableArray jsArguments, int atIndex) { - return (float) jsArguments.getDouble(atIndex); - } - }; - - static final private ArgumentExtractor ARGUMENT_EXTRACTOR_INTEGER = - new ArgumentExtractor() { - @Override - public Integer extractArgument( - JSInstance jsInstance, ReadableArray jsArguments, int atIndex) { - return (int) jsArguments.getDouble(atIndex); - } - }; - - static final private ArgumentExtractor ARGUMENT_EXTRACTOR_STRING = - new ArgumentExtractor() { - @Override - public String extractArgument( - JSInstance jsInstance, ReadableArray jsArguments, int atIndex) { - return jsArguments.getString(atIndex); - } - }; - - static final private ArgumentExtractor ARGUMENT_EXTRACTOR_ARRAY = - new ArgumentExtractor() { - @Override - public ReadableArray extractArgument( - JSInstance jsInstance, ReadableArray jsArguments, int atIndex) { - return jsArguments.getArray(atIndex); - } - }; - - static final private ArgumentExtractor ARGUMENT_EXTRACTOR_DYNAMIC = - new ArgumentExtractor() { - @Override - public Dynamic extractArgument( - JSInstance jsInstance, ReadableArray jsArguments, int atIndex) { - return DynamicFromArray.create(jsArguments, atIndex); - } - }; - - static final private ArgumentExtractor ARGUMENT_EXTRACTOR_MAP = - new ArgumentExtractor() { - @Override - public ReadableMap extractArgument( - JSInstance jsInstance, ReadableArray jsArguments, int atIndex) { - return jsArguments.getMap(atIndex); - } - }; - - static final private ArgumentExtractor ARGUMENT_EXTRACTOR_CALLBACK = - new ArgumentExtractor() { - @Override - public @Nullable Callback extractArgument( - JSInstance jsInstance, ReadableArray jsArguments, int atIndex) { - if (jsArguments.isNull(atIndex)) { - return null; - } else { - int id = (int) jsArguments.getDouble(atIndex); - return new com.facebook.react.bridge.CallbackImpl(jsInstance, id); + private static final ArgumentExtractor ARGUMENT_EXTRACTOR_BOOLEAN = + new ArgumentExtractor() { + @Override + public Boolean extractArgument( + JSInstance jsInstance, ReadableArray jsArguments, int atIndex) { + return jsArguments.getBoolean(atIndex); } - } - }; + }; - static final private ArgumentExtractor ARGUMENT_EXTRACTOR_PROMISE = - new ArgumentExtractor() { - @Override - public int getJSArgumentsNeeded() { - return 2; - } + private static final ArgumentExtractor ARGUMENT_EXTRACTOR_DOUBLE = + new ArgumentExtractor() { + @Override + public Double extractArgument( + JSInstance jsInstance, ReadableArray jsArguments, int atIndex) { + return jsArguments.getDouble(atIndex); + } + }; - @Override - public Promise extractArgument( - JSInstance jsInstance, ReadableArray jsArguments, int atIndex) { - Callback resolve = ARGUMENT_EXTRACTOR_CALLBACK - .extractArgument(jsInstance, jsArguments, atIndex); - Callback reject = ARGUMENT_EXTRACTOR_CALLBACK - .extractArgument(jsInstance, jsArguments, atIndex + 1); - return new PromiseImpl(resolve, reject); - } - }; + private static final ArgumentExtractor ARGUMENT_EXTRACTOR_FLOAT = + new ArgumentExtractor() { + @Override + public Float extractArgument( + JSInstance jsInstance, ReadableArray jsArguments, int atIndex) { + return (float) jsArguments.getDouble(atIndex); + } + }; + + private static final ArgumentExtractor ARGUMENT_EXTRACTOR_INTEGER = + new ArgumentExtractor() { + @Override + public Integer extractArgument( + JSInstance jsInstance, ReadableArray jsArguments, int atIndex) { + return (int) jsArguments.getDouble(atIndex); + } + }; + + private static final ArgumentExtractor ARGUMENT_EXTRACTOR_STRING = + new ArgumentExtractor() { + @Override + public String extractArgument( + JSInstance jsInstance, ReadableArray jsArguments, int atIndex) { + return jsArguments.getString(atIndex); + } + }; + + private static final ArgumentExtractor ARGUMENT_EXTRACTOR_ARRAY = + new ArgumentExtractor() { + @Override + public ReadableArray extractArgument( + JSInstance jsInstance, ReadableArray jsArguments, int atIndex) { + return jsArguments.getArray(atIndex); + } + }; + + private static final ArgumentExtractor ARGUMENT_EXTRACTOR_DYNAMIC = + new ArgumentExtractor() { + @Override + public Dynamic extractArgument( + JSInstance jsInstance, ReadableArray jsArguments, int atIndex) { + return DynamicFromArray.create(jsArguments, atIndex); + } + }; + + private static final ArgumentExtractor ARGUMENT_EXTRACTOR_MAP = + new ArgumentExtractor() { + @Override + public ReadableMap extractArgument( + JSInstance jsInstance, ReadableArray jsArguments, int atIndex) { + return jsArguments.getMap(atIndex); + } + }; + + private static final ArgumentExtractor ARGUMENT_EXTRACTOR_CALLBACK = + new ArgumentExtractor() { + @Override + public @Nullable Callback extractArgument( + JSInstance jsInstance, ReadableArray jsArguments, int atIndex) { + if (jsArguments.isNull(atIndex)) { + return null; + } else { + int id = (int) jsArguments.getDouble(atIndex); + return new com.facebook.react.bridge.CallbackImpl(jsInstance, id); + } + } + }; + + private static final ArgumentExtractor ARGUMENT_EXTRACTOR_PROMISE = + new ArgumentExtractor() { + @Override + public int getJSArgumentsNeeded() { + return 2; + } + + @Override + public Promise extractArgument( + JSInstance jsInstance, ReadableArray jsArguments, int atIndex) { + Callback resolve = + ARGUMENT_EXTRACTOR_CALLBACK.extractArgument(jsInstance, jsArguments, atIndex); + Callback reject = + ARGUMENT_EXTRACTOR_CALLBACK.extractArgument(jsInstance, jsArguments, atIndex + 1); + return new PromiseImpl(resolve, reject); + } + }; private static final boolean DEBUG = PrinterHolder.getPrinter().shouldDisplayLogMessage(ReactDebugOverlayTags.BRIDGE_CALLS); @@ -152,8 +151,7 @@ public class JavaMethodWrapper implements NativeModule.NativeMethod { } else if (paramClass == Dynamic.class) { return 'Y'; } else { - throw new RuntimeException( - "Got unknown param class: " + paramClass.getSimpleName()); + throw new RuntimeException("Got unknown param class: " + paramClass.getSimpleName()); } } @@ -170,8 +168,7 @@ public class JavaMethodWrapper implements NativeModule.NativeMethod { } else if (returnClass == WritableArray.class) { return 'A'; } else { - throw new RuntimeException( - "Got unknown return class: " + returnClass.getSimpleName()); + throw new RuntimeException("Got unknown return class: " + returnClass.getSimpleName()); } } @@ -229,15 +226,13 @@ public class JavaMethodWrapper implements NativeModule.NativeMethod { return; } SystraceMessage.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "processArguments") - .arg("method", mModuleWrapper.getName() + "." + mMethod.getName()) - .flush(); + .arg("method", mModuleWrapper.getName() + "." + mMethod.getName()) + .flush(); try { mArgumentsProcessed = true; mArgumentExtractors = buildArgumentExtractors(mParameterTypes); - mSignature = buildSignature( - mMethod, - mParameterTypes, - (mType.equals(BaseJavaModule.METHOD_TYPE_SYNC))); + mSignature = + buildSignature(mMethod, mParameterTypes, (mType.equals(BaseJavaModule.METHOD_TYPE_SYNC))); // Since native methods are invoked from a message queue executed on a single thread, it is // safe to allocate only one arguments object per method that can be reused across calls mArguments = new Object[mParameterTypes.length]; @@ -272,7 +267,7 @@ public class JavaMethodWrapper implements NativeModule.NativeMethod { Class paramClass = paramTypes[i]; if (paramClass == Promise.class) { Assertions.assertCondition( - i == paramTypes.length - 1, "Promise must be used as last parameter only"); + i == paramTypes.length - 1, "Promise must be used as last parameter only"); } builder.append(paramTypeToChar(paramClass)); } @@ -299,7 +294,7 @@ public class JavaMethodWrapper implements NativeModule.NativeMethod { } else if (argumentClass == Promise.class) { argumentExtractors[i] = ARGUMENT_EXTRACTOR_PROMISE; Assertions.assertCondition( - i == paramTypes.length - 1, "Promise must be used as last parameter only"); + i == paramTypes.length - 1, "Promise must be used as last parameter only"); } else if (argumentClass == ReadableMap.class) { argumentExtractors[i] = ARGUMENT_EXTRACTOR_MAP; } else if (argumentClass == ReadableArray.class) { @@ -307,8 +302,7 @@ public class JavaMethodWrapper implements NativeModule.NativeMethod { } else if (argumentClass == Dynamic.class) { argumentExtractors[i] = ARGUMENT_EXTRACTOR_DYNAMIC; } else { - throw new RuntimeException( - "Got unknown argument class: " + argumentClass.getSimpleName()); + throw new RuntimeException("Got unknown argument class: " + argumentClass.getSimpleName()); } } return argumentExtractors; @@ -323,16 +317,17 @@ public class JavaMethodWrapper implements NativeModule.NativeMethod { } private String getAffectedRange(int startIndex, int jsArgumentsNeeded) { - return jsArgumentsNeeded > 1 ? - "" + startIndex + "-" + (startIndex + jsArgumentsNeeded - 1) : "" + startIndex; + return jsArgumentsNeeded > 1 + ? "" + startIndex + "-" + (startIndex + jsArgumentsNeeded - 1) + : "" + startIndex; } @Override public void invoke(JSInstance jsInstance, ReadableArray parameters) { String traceName = mModuleWrapper.getName() + "." + mMethod.getName(); SystraceMessage.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "callJavaModuleMethod") - .arg("method", traceName) - .flush(); + .arg("method", traceName) + .flush(); if (DEBUG) { PrinterHolder.getPrinter() .logMessage( @@ -350,22 +345,26 @@ public class JavaMethodWrapper implements NativeModule.NativeMethod { } if (mJSArgumentsNeeded != parameters.size()) { throw new NativeArgumentsParseException( - traceName + " got " + parameters.size() + " arguments, expected " + mJSArgumentsNeeded); + traceName + " got " + parameters.size() + " arguments, expected " + mJSArgumentsNeeded); } int i = 0, jsArgumentsConsumed = 0; try { for (; i < mArgumentExtractors.length; i++) { - mArguments[i] = mArgumentExtractors[i].extractArgument( - jsInstance, parameters, jsArgumentsConsumed); + mArguments[i] = + mArgumentExtractors[i].extractArgument(jsInstance, parameters, jsArgumentsConsumed); jsArgumentsConsumed += mArgumentExtractors[i].getJSArgumentsNeeded(); } } catch (UnexpectedNativeTypeException e) { throw new NativeArgumentsParseException( - e.getMessage() + " (constructing arguments for " + traceName + " at argument index " + - getAffectedRange(jsArgumentsConsumed, mArgumentExtractors[i].getJSArgumentsNeeded()) + - ")", - e); + e.getMessage() + + " (constructing arguments for " + + traceName + + " at argument index " + + getAffectedRange( + jsArgumentsConsumed, mArgumentExtractors[i].getJSArgumentsNeeded()) + + ")", + e); } try { @@ -388,10 +387,9 @@ public class JavaMethodWrapper implements NativeModule.NativeMethod { } /** - * Determines how the method is exported in JavaScript: - * METHOD_TYPE_ASYNC for regular methods - * METHOD_TYPE_PROMISE for methods that return a promise object to the caller. - * METHOD_TYPE_SYNC for sync methods + * Determines how the method is exported in JavaScript: METHOD_TYPE_ASYNC for regular methods + * METHOD_TYPE_PROMISE for methods that return a promise object to the caller. METHOD_TYPE_SYNC + * for sync methods */ @Override public String getType() { diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/JavaModuleWrapper.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/JavaModuleWrapper.java index af8b0fbeebf..77105a5d5ca 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/JavaModuleWrapper.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/JavaModuleWrapper.java @@ -1,50 +1,41 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; -import javax.annotation.Nullable; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.facebook.proguard.annotations.DoNotStrip; -import com.facebook.systrace.Systrace; -import com.facebook.systrace.SystraceMessage; - import static com.facebook.react.bridge.ReactMarkerConstants.CONVERT_CONSTANTS_END; import static com.facebook.react.bridge.ReactMarkerConstants.CONVERT_CONSTANTS_START; import static com.facebook.react.bridge.ReactMarkerConstants.GET_CONSTANTS_END; import static com.facebook.react.bridge.ReactMarkerConstants.GET_CONSTANTS_START; import static com.facebook.systrace.Systrace.TRACE_TAG_REACT_JAVA_BRIDGE; -/** - * This is part of the glue which wraps a java BaseJavaModule in a C++ - * NativeModule. This could all be in C++, but it's android-specific - * initialization code, and writing it this way is easier to read and means - * fewer JNI calls. - */ +import com.facebook.proguard.annotations.DoNotStrip; +import com.facebook.systrace.Systrace; +import com.facebook.systrace.SystraceMessage; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import javax.annotation.Nullable; +/** + * This is part of the glue which wraps a java BaseJavaModule in a C++ NativeModule. This could all + * be in C++, but it's android-specific initialization code, and writing it this way is easier to + * read and means fewer JNI calls. + */ @DoNotStrip public class JavaModuleWrapper { @DoNotStrip public class MethodDescriptor { - @DoNotStrip - Method method; - @DoNotStrip - String signature; - @DoNotStrip - String name; - @DoNotStrip - String type; + @DoNotStrip Method method; + @DoNotStrip String signature; + @DoNotStrip String name; + @DoNotStrip String type; } private final JSInstance mJSInstance; @@ -93,10 +84,11 @@ public class JavaModuleWrapper { // We do not support method overloading since js sees a function as an object regardless // of number of params. throw new IllegalArgumentException( - "Java Module " + getName() + " method name already registered: " + methodName); + "Java Module " + getName() + " method name already registered: " + methodName); } MethodDescriptor md = new MethodDescriptor(); - JavaMethodWrapper method = new JavaMethodWrapper(this, targetMethod, annotation.isBlockingSynchronousMethod()); + JavaMethodWrapper method = + new JavaMethodWrapper(this, targetMethod, annotation.isBlockingSynchronousMethod()); md.name = methodName; md.type = method.getType(); if (md.type == BaseJavaModule.METHOD_TYPE_SYNC) { @@ -126,8 +118,8 @@ public class JavaModuleWrapper { final String moduleName = getName(); SystraceMessage.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "JavaModuleWrapper.getConstants") - .arg("moduleName", moduleName) - .flush(); + .arg("moduleName", moduleName) + .flush(); ReactMarker.logMarker(GET_CONSTANTS_START, moduleName); BaseJavaModule baseJavaModule = getModule(); diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/JavaOnlyArray.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/JavaOnlyArray.java index 1b3774d7f87..fcc022220e4 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/JavaOnlyArray.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/JavaOnlyArray.java @@ -1,29 +1,27 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; import java.util.ArrayList; import java.util.Arrays; import java.util.List; - import javax.annotation.Nonnull; import javax.annotation.Nullable; /** * Java {@link ArrayList} backed implementation of {@link ReadableArray} and {@link WritableArray} * Instances of this class SHOULD NOT be used for communication between java and JS, use instances - * of {@link WritableNativeArray} created via {@link Arguments#createArray} or just - * {@link ReadableArray} interface if you want your "native" module method to take an array from JS - * as an argument. + * of {@link WritableNativeArray} created via {@link Arguments#createArray} or just {@link + * ReadableArray} interface if you want your "native" module method to take an array from JS as an + * argument. * - * Main purpose for this class is to be used in java-only unit tests, but could also be used outside - * of tests in the code that operates only in java and needs to communicate with RN modules via - * their JS-exposed API. + *

Main purpose for this class is to be used in java-only unit tests, but could also be used + * outside of tests in the code that operates only in java and needs to communicate with RN modules + * via their JS-exposed API. */ public class JavaOnlyArray implements ReadableArray, WritableArray { @@ -130,9 +128,7 @@ public class JavaOnlyArray implements ReadableArray, WritableArray { return ReadableType.Null; } else if (object instanceof Boolean) { return ReadableType.Boolean; - } else if (object instanceof Double || - object instanceof Float || - object instanceof Integer) { + } else if (object instanceof Double || object instanceof Float || object instanceof Integer) { return ReadableType.Number; } else if (object instanceof String) { return ReadableType.String; diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/JavaOnlyMap.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/JavaOnlyMap.java index ddf450f814c..6ce959b9a3b 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/JavaOnlyMap.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/JavaOnlyMap.java @@ -9,7 +9,6 @@ package com.facebook.react.bridge; import java.util.HashMap; import java.util.Iterator; import java.util.Map; - import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -71,7 +70,7 @@ public class JavaOnlyMap implements ReadableMap, WritableMap { Object val = keysAndValues[i + 1]; if (val instanceof Number) { // all values from JS are doubles, so emulate that here for tests. - val = ((Number)val).doubleValue(); + val = ((Number) val).doubleValue(); } mBackingMap.put(keysAndValues[i], val); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/JavaScriptContextHolder.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/JavaScriptContextHolder.java index 13c767afc6c..20e0a907a1e 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/JavaScriptContextHolder.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/JavaScriptContextHolder.java @@ -9,8 +9,8 @@ import javax.annotation.concurrent.GuardedBy; /** * Wrapper for JavaScriptContext native pointer. CatalystInstanceImpl creates this on demand, and - * will call clear() before destroying the VM. People who need the raw JavaScriptContext pointer - * can synchronize on this wrapper object to guarantee that it will not be destroyed. + * will call clear() before destroying the VM. People who need the raw JavaScriptContext pointer can + * synchronize on this wrapper object to guarantee that it will not be destroyed. */ public class JavaScriptContextHolder { @GuardedBy("this") @@ -28,5 +28,4 @@ public class JavaScriptContextHolder { public synchronized void clear() { mContext = 0; } - } diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/JavaScriptExecutor.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/JavaScriptExecutor.java index 4333cfbbda7..70e4e7e75fd 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/JavaScriptExecutor.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/JavaScriptExecutor.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; import com.facebook.jni.HybridData; @@ -19,16 +18,13 @@ public abstract class JavaScriptExecutor { } /** - * Close this executor and cleanup any resources that it was using. No further calls are - * expected after this. - * TODO mhorowitz: This may no longer be used; check and delete if possible. + * Close this executor and cleanup any resources that it was using. No further calls are expected + * after this. TODO mhorowitz: This may no longer be used; check and delete if possible. */ public void close() { mHybridData.resetNative(); } - /** - * Returns the name of the executor, identifying the underlying runtime. - */ - abstract public String getName(); + /** Returns the name of the executor, identifying the underlying runtime. */ + public abstract String getName(); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/JavaScriptExecutorFactory.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/JavaScriptExecutorFactory.java index 1530755ca58..6aee7949a71 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/JavaScriptExecutorFactory.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/JavaScriptExecutorFactory.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; public interface JavaScriptExecutorFactory { diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/JavaScriptModule.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/JavaScriptModule.java index e3b5f568135..895f8de45f9 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/JavaScriptModule.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/JavaScriptModule.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; import com.facebook.proguard.annotations.DoNotStrip; @@ -13,15 +12,13 @@ import com.facebook.proguard.annotations.DoNotStrip; * Interface denoting that a class is the interface to a module with the same name in JS. Calling * functions on this interface will result in corresponding methods in JS being called. * - * When extending JavaScriptModule and registering it with a CatalystInstance, all public methods - * are assumed to be implemented on a JS module with the same name as this class. Calling methods - * on the object returned from {@link ReactContext#getJSModule} or - * {@link CatalystInstance#getJSModule} will result in the methods with those names exported by - * that module being called in JS. + *

When extending JavaScriptModule and registering it with a CatalystInstance, all public methods + * are assumed to be implemented on a JS module with the same name as this class. Calling methods on + * the object returned from {@link ReactContext#getJSModule} or {@link CatalystInstance#getJSModule} + * will result in the methods with those names exported by that module being called in JS. * - * NB: JavaScriptModule does not allow method name overloading because JS does not allow method name - * overloading. + *

NB: JavaScriptModule does not allow method name overloading because JS does not allow method + * name overloading. */ @DoNotStrip -public interface JavaScriptModule { -} +public interface JavaScriptModule {} diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/JavaScriptModuleRegistry.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/JavaScriptModuleRegistry.java index 5bb25881ca4..4d03060cf51 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/JavaScriptModuleRegistry.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/JavaScriptModuleRegistry.java @@ -1,27 +1,24 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; -import javax.annotation.Nullable; - +import com.facebook.react.common.build.ReactBuildConfig; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.HashMap; import java.util.HashSet; import java.util.Set; - -import com.facebook.react.common.build.ReactBuildConfig; +import javax.annotation.Nullable; /** - * Class responsible for holding all the {@link JavaScriptModule}s. Uses Java proxy objects - * to dispatch method calls on JavaScriptModules to the bridge using the corresponding - * module and method ids so the proper function is executed in JavaScript. + * Class responsible for holding all the {@link JavaScriptModule}s. Uses Java proxy objects to + * dispatch method calls on JavaScriptModules to the bridge using the corresponding module and + * method ids so the proper function is executed in JavaScript. */ public final class JavaScriptModuleRegistry { private final HashMap, JavaScriptModule> mModuleInstances; @@ -31,17 +28,18 @@ public final class JavaScriptModuleRegistry { } public synchronized T getJavaScriptModule( - CatalystInstance instance, - Class moduleInterface) { + CatalystInstance instance, Class moduleInterface) { JavaScriptModule module = mModuleInstances.get(moduleInterface); if (module != null) { return (T) module; } - JavaScriptModule interfaceProxy = (JavaScriptModule) Proxy.newProxyInstance( - moduleInterface.getClassLoader(), - new Class[]{moduleInterface}, - new JavaScriptModuleInvocationHandler(instance, moduleInterface)); + JavaScriptModule interfaceProxy = + (JavaScriptModule) + Proxy.newProxyInstance( + moduleInterface.getClassLoader(), + new Class[] {moduleInterface}, + new JavaScriptModuleInvocationHandler(instance, moduleInterface)); mModuleInstances.put(moduleInterface, interfaceProxy); return (T) interfaceProxy; } @@ -52,8 +50,7 @@ public final class JavaScriptModuleRegistry { private @Nullable String mName; public JavaScriptModuleInvocationHandler( - CatalystInstance catalystInstance, - Class moduleInterface) { + CatalystInstance catalystInstance, Class moduleInterface) { mCatalystInstance = catalystInstance; mModuleInterface = moduleInterface; @@ -62,8 +59,10 @@ public final class JavaScriptModuleRegistry { for (Method method : mModuleInterface.getDeclaredMethods()) { if (!methodNames.add(method.getName())) { throw new AssertionError( - "Method overloading is unsupported: " + mModuleInterface.getName() + - "#" + method.getName()); + "Method overloading is unsupported: " + + mModuleInterface.getName() + + "#" + + method.getName()); } } } @@ -87,10 +86,9 @@ public final class JavaScriptModuleRegistry { } @Override - public @Nullable Object invoke(Object proxy, Method method, @Nullable Object[] args) throws Throwable { - NativeArray jsArgs = args != null - ? Arguments.fromJavaArgs(args) - : new WritableNativeArray(); + public @Nullable Object invoke(Object proxy, Method method, @Nullable Object[] args) + throws Throwable { + NativeArray jsArgs = args != null ? Arguments.fromJavaArgs(args) : new WritableNativeArray(); mCatalystInstance.callFunction(getJSModuleName(), method.getName(), jsArgs); return null; } diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/JsonWriter.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/JsonWriter.java index 924b7915629..e379b568c68 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/JsonWriter.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/JsonWriter.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; import java.io.Closeable; @@ -13,9 +12,7 @@ import java.io.Writer; import java.util.ArrayDeque; import java.util.Deque; -/** - * Simple Json generator that does no validation. - */ +/** Simple Json generator that does no validation. */ public class JsonWriter implements Closeable { private final Writer mWriter; private final Deque mScopes; @@ -197,7 +194,6 @@ public class JsonWriter implements Closeable { } break; } - } mWriter.write('"'); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/JsonWriterHelper.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/JsonWriterHelper.java index 712197ae088..ab46dc7f72d 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/JsonWriterHelper.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/JsonWriterHelper.java @@ -1,19 +1,16 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; import java.io.IOException; import java.util.List; import java.util.Map; -/** - * Helper for generating JSON for lists and maps. - */ +/** Helper for generating JSON for lists and maps. */ class JsonWriterHelper { public static void value(JsonWriter writer, Object value) throws IOException { if (value instanceof Map) { diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/LifecycleEventListener.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/LifecycleEventListener.java index 908e13db416..32c4b015546 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/LifecycleEventListener.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/LifecycleEventListener.java @@ -1,28 +1,25 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; /** * Listener for receiving activity lifecycle events. * - * When multiple activities share a react instance, only the most recent one's lifecycle events get - * forwarded to listeners. Consider the following scenarios: + *

When multiple activities share a react instance, only the most recent one's lifecycle events + * get forwarded to listeners. Consider the following scenarios: * - * 1. Navigating from Activity A to B will trigger two events: A#onHostPause and B#onHostResume. Any - * subsequent lifecycle events coming from Activity A, such as onHostDestroy, will be ignored. + *

1. Navigating from Activity A to B will trigger two events: A#onHostPause and B#onHostResume. + * Any subsequent lifecycle events coming from Activity A, such as onHostDestroy, will be ignored. * 2. Navigating back from Activity B to Activity A will trigger the same events: B#onHostPause and - * A#onHostResume. Any subsequent events coming from Activity B, such as onHostDestroy, are - * ignored. + * A#onHostResume. Any subsequent events coming from Activity B, such as onHostDestroy, are ignored. * 3. Navigating back from Activity A to a non-React Activity or to the home screen will trigger two - * events: onHostPause and onHostDestroy. - * 4. Navigating from Activity A to a non-React Activity B will trigger one event: onHostPause. - * Later, if Activity A is destroyed (e.g. because of resource contention), onHostDestroy is - * triggered. + * events: onHostPause and onHostDestroy. 4. Navigating from Activity A to a non-React Activity B + * will trigger one event: onHostPause. Later, if Activity A is destroyed (e.g. because of resource + * contention), onHostDestroy is triggered. */ public interface LifecycleEventListener { diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/MemoryPressureListener.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/MemoryPressureListener.java index 972f17aa397..ac7ea034dcc 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/MemoryPressureListener.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/MemoryPressureListener.java @@ -5,14 +5,9 @@ package com.facebook.react.bridge; -/** - * Listener interface for memory pressure events. - */ +/** Listener interface for memory pressure events. */ public interface MemoryPressureListener { - /** - * Called when the system generates a memory warning. - */ + /** Called when the system generates a memory warning. */ void handleMemoryPressure(int level); - } diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/ModuleHolder.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/ModuleHolder.java index e1299d525ae..f36bf258fe0 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/ModuleHolder.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/ModuleHolder.java @@ -70,8 +70,7 @@ public class ModuleHolder { true, true, CxxModuleWrapper.class.isAssignableFrom(nativeModule.getClass()), - TurboModule.class.isAssignableFrom(nativeModule.getClass()) - ); + TurboModule.class.isAssignableFrom(nativeModule.getClass())); mModule = nativeModule; PrinterHolder.getPrinter() @@ -199,7 +198,7 @@ public class ModuleHolder { doInitialize(module); } } finally { - ReactMarker.logMarker(CREATE_MODULE_END, mName ,mInstanceKey); + ReactMarker.logMarker(CREATE_MODULE_END, mName, mInstanceKey); SystraceMessage.endSection(TRACE_TAG_REACT_JAVA_BRIDGE).flush(); } return module; diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/NativeArgumentsParseException.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/NativeArgumentsParseException.java index 3dd3617293e..b292b669de6 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/NativeArgumentsParseException.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/NativeArgumentsParseException.java @@ -1,17 +1,14 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; import javax.annotation.Nullable; -/** - * Exception thrown when a native module method call receives unexpected arguments from JS. - */ +/** Exception thrown when a native module method call receives unexpected arguments from JS. */ public class NativeArgumentsParseException extends JSApplicationCausedNativeException { public NativeArgumentsParseException(String detailMessage) { diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/NativeArray.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/NativeArray.java index 9ae9251f23e..101c6b99fa3 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/NativeArray.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/NativeArray.java @@ -1,20 +1,17 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; import com.facebook.jni.HybridData; import com.facebook.proguard.annotations.DoNotStrip; -/** - * Base class for an array whose members are stored in native code (C++). - */ +/** Base class for an array whose members are stored in native code (C++). */ @DoNotStrip -public abstract class NativeArray implements NativeArrayInterface{ +public abstract class NativeArray implements NativeArrayInterface { static { ReactBridge.staticInit(); } @@ -26,6 +23,5 @@ public abstract class NativeArray implements NativeArrayInterface{ @Override public native String toString(); - @DoNotStrip - private HybridData mHybridData; + @DoNotStrip private HybridData mHybridData; } diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/NativeArrayInterface.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/NativeArrayInterface.java index 989208814f2..c31bde01d8a 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/NativeArrayInterface.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/NativeArrayInterface.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; public interface NativeArrayInterface { diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/NativeDeltaClient.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/NativeDeltaClient.java index 97eb4337284..39ebf53b636 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/NativeDeltaClient.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/NativeDeltaClient.java @@ -1,15 +1,13 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; -import java.nio.channels.ReadableByteChannel; - import com.facebook.jni.HybridData; +import java.nio.channels.ReadableByteChannel; public class NativeDeltaClient { static { @@ -18,8 +16,10 @@ public class NativeDeltaClient { // C++ parts private final HybridData mHybridData = initHybrid(); - private native static HybridData initHybrid(); + + private static native HybridData initHybrid(); public native void reset(); + public native void processDelta(ReadableByteChannel deltaMessage); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/NativeMap.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/NativeMap.java index d1dbf145ef1..731638105ec 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/NativeMap.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/NativeMap.java @@ -1,18 +1,15 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; import com.facebook.jni.HybridData; import com.facebook.proguard.annotations.DoNotStrip; -/** - * Base class for a Map whose keys and values are stored in native code (C++). - */ +/** Base class for a Map whose keys and values are stored in native code (C++). */ @DoNotStrip public abstract class NativeMap { static { @@ -26,6 +23,5 @@ public abstract class NativeMap { @Override public native String toString(); - @DoNotStrip - private HybridData mHybridData; + @DoNotStrip private HybridData mHybridData; } diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/NativeModule.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/NativeModule.java index 14224ca10a2..8d0b6251a0d 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/NativeModule.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/NativeModule.java @@ -1,41 +1,40 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; import com.facebook.proguard.annotations.DoNotStrip; - import javax.annotation.Nonnull; - /** - * A native module whose API can be provided to JS catalyst instances. {@link NativeModule}s whose + * A native module whose API can be provided to JS catalyst instances. {@link NativeModule}s whose * implementation is written in Java should extend {@link BaseJavaModule} or {@link - * ReactContextBaseJavaModule}. {@link NativeModule}s whose implementation is written in C++ - * must not provide any Java code (so they can be reused on other platforms), and instead should - * register themselves using {@link CxxModuleWrapper}. + * ReactContextBaseJavaModule}. {@link NativeModule}s whose implementation is written in C++ must + * not provide any Java code (so they can be reused on other platforms), and instead should register + * themselves using {@link CxxModuleWrapper}. */ @DoNotStrip public interface NativeModule { interface NativeMethod { void invoke(JSInstance jsInstance, ReadableArray parameters); + String getType(); } /** * @return the name of this module. This will be the name used to {@code require()} this module - * from javascript. + * from javascript. */ - @Nonnull String getName(); + @Nonnull + String getName(); /** - * This is called at the end of {@link CatalystApplicationFragment#createCatalystInstance()} - * after the CatalystInstance has been created, in order to initialize NativeModules that require - * the CatalystInstance or JS modules. + * This is called at the end of {@link CatalystApplicationFragment#createCatalystInstance()} after + * the CatalystInstance has been created, in order to initialize NativeModules that require the + * CatalystInstance or JS modules. */ void initialize(); @@ -47,8 +46,6 @@ public interface NativeModule { */ boolean canOverrideExistingModule(); - /** - * Called before {CatalystInstance#onHostDestroy} - */ + /** Called before {CatalystInstance#onHostDestroy} */ void onCatalystInstanceDestroy(); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/NativeModuleCallExceptionHandler.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/NativeModuleCallExceptionHandler.java index ada610f1f06..d9b31a59673 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/NativeModuleCallExceptionHandler.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/NativeModuleCallExceptionHandler.java @@ -1,26 +1,22 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; /** * Interface for a class that knows how to handle an Exception thrown by a native module invoked - * from JS. Since these Exceptions are triggered by JS calls (and can be fixed in JS), a - * common way to handle one is to show a error dialog and allow the developer to change and reload - * JS. + * from JS. Since these Exceptions are triggered by JS calls (and can be fixed in JS), a common way + * to handle one is to show a error dialog and allow the developer to change and reload JS. * - * We should also note that we have a unique stance on what 'caused' means: even if there's a bug in - * the framework/native code, it was triggered by JS and theoretically since we were able to set up - * the bridge, JS could change its logic, reload, and not trigger that crash. + *

We should also note that we have a unique stance on what 'caused' means: even if there's a bug + * in the framework/native code, it was triggered by JS and theoretically since we were able to set + * up the bridge, JS could change its logic, reload, and not trigger that crash. */ public interface NativeModuleCallExceptionHandler { - /** - * Do something to display or log the exception. - */ + /** Do something to display or log the exception. */ void handleException(Exception e); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/NativeModuleRegistry.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/NativeModuleRegistry.java index 126e7fb7576..8c82e88e615 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/NativeModuleRegistry.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/NativeModuleRegistry.java @@ -144,8 +144,8 @@ public class NativeModuleRegistry { } public NativeModule getModule(String name) { - return Assertions.assertNotNull( - mModules.get(name), "Could not find module with name " + name).getModule(); + return Assertions.assertNotNull(mModules.get(name), "Could not find module with name " + name) + .getModule(); } public List getAllModules() { diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/NoSuchKeyException.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/NoSuchKeyException.java index 56488cc11c5..32843d35339 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/NoSuchKeyException.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/NoSuchKeyException.java @@ -1,17 +1,14 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; import com.facebook.proguard.annotations.DoNotStrip; -/** - * Exception thrown by {@link ReadableNativeMap} when a key that does not exist is requested. - */ +/** Exception thrown by {@link ReadableNativeMap} when a key that does not exist is requested. */ @DoNotStrip public class NoSuchKeyException extends RuntimeException { diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/NotThreadSafeBridgeIdleDebugListener.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/NotThreadSafeBridgeIdleDebugListener.java index 680702561a5..da854c76092 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/NotThreadSafeBridgeIdleDebugListener.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/NotThreadSafeBridgeIdleDebugListener.java @@ -1,36 +1,32 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; /** * Interface for receiving notification for bridge idle/busy events. Should not affect application - * logic and should only be used for debug/monitoring/testing purposes. Call - * {@link CatalystInstance#addBridgeIdleDebugListener} to start monitoring. + * logic and should only be used for debug/monitoring/testing purposes. Call {@link + * CatalystInstance#addBridgeIdleDebugListener} to start monitoring. * - * NB: onTransitionToBridgeIdle and onTransitionToBridgeBusy may be called from different threads, - * and those threads may not be the same thread on which the listener was originally registered. + *

NB: onTransitionToBridgeIdle and onTransitionToBridgeBusy may be called from different + * threads, and those threads may not be the same thread on which the listener was originally + * registered. */ public interface NotThreadSafeBridgeIdleDebugListener { /** * Called once all pending JS calls have resolved via an onBatchComplete call in the bridge and - * the requested native module calls have also run. The bridge will not become busy again until - * a timer, touch event, etc. causes a Java->JS call to be enqueued again. + * the requested native module calls have also run. The bridge will not become busy again until a + * timer, touch event, etc. causes a Java->JS call to be enqueued again. */ void onTransitionToBridgeIdle(); - /** - * Called when the bridge was in an idle state and executes a JS call or callback. - */ + /** Called when the bridge was in an idle state and executes a JS call or callback. */ void onTransitionToBridgeBusy(); - /** - * Called when the bridge is destroyed - */ + /** Called when the bridge is destroyed */ void onBridgeDestroyed(); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/ObjectAlreadyConsumedException.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/ObjectAlreadyConsumedException.java index 720cc2ac9fe..d83f579c6d5 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/ObjectAlreadyConsumedException.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/ObjectAlreadyConsumedException.java @@ -1,18 +1,17 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; import com.facebook.proguard.annotations.DoNotStrip; /** - * Exception thrown when a caller attempts to modify or use a {@link WritableNativeArray} or - * {@link WritableNativeMap} after it has already been added to a parent array or map. This is - * unsafe since we reuse the native memory so the underlying array/map is no longer valid. + * Exception thrown when a caller attempts to modify or use a {@link WritableNativeArray} or {@link + * WritableNativeMap} after it has already been added to a parent array or map. This is unsafe since + * we reuse the native memory so the underlying array/map is no longer valid. */ @DoNotStrip public class ObjectAlreadyConsumedException extends RuntimeException { diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/OnBatchCompleteListener.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/OnBatchCompleteListener.java index e785ab843e0..52e726bb5fc 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/OnBatchCompleteListener.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/OnBatchCompleteListener.java @@ -1,15 +1,12 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; -/** - * Interface for a module that will be notified when a batch of JS->Java calls has finished. - */ +/** Interface for a module that will be notified when a batch of JS->Java calls has finished. */ public interface OnBatchCompleteListener { void onBatchComplete(); diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/PerformanceCounter.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/PerformanceCounter.java index 645851c9316..e34889635d8 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/PerformanceCounter.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/PerformanceCounter.java @@ -1,8 +1,8 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ package com.facebook.react.bridge; @@ -13,5 +13,4 @@ public interface PerformanceCounter { void profileNextBatch(); Map getPerformanceCounters(); - } diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/Promise.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/Promise.java index 27d4d697cf8..4678c788480 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/Promise.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/Promise.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; import javax.annotation.Nonnull; @@ -29,7 +28,7 @@ public interface Promise { /** * Report an error without an exception using a custom code and error message. * - * @param code String + * @param code String * @param message String */ void reject(String code, String message); @@ -37,7 +36,7 @@ public interface Promise { /** * Report an exception with a custom code. * - * @param code String + * @param code String * @param throwable Throwable */ void reject(String code, Throwable throwable); @@ -45,16 +44,15 @@ public interface Promise { /** * Report an exception with a custom code and error message. * - * @param code String - * @param message String + * @param code String + * @param message String * @param throwable Throwable */ void reject(String code, String message, Throwable throwable); - /** - * Report an exception, with default error code. - * Useful in catch-all scenarios where it's unclear why the error occurred. + * Report an exception, with default error code. Useful in catch-all scenarios where it's unclear + * why the error occurred. * * @param throwable Throwable */ @@ -65,18 +63,18 @@ public interface Promise { * --------------------------- */ /** - * Report an exception, with default error code, with userInfo. - * Useful in catch-all scenarios where it's unclear why the error occurred. + * Report an exception, with default error code, with userInfo. Useful in catch-all scenarios + * where it's unclear why the error occurred. * * @param throwable Throwable - * @param userInfo WritableMap + * @param userInfo WritableMap */ void reject(Throwable throwable, WritableMap userInfo); /** * Reject with a code and userInfo WritableMap. * - * @param code String + * @param code String * @param userInfo WritableMap */ void reject(String code, @Nonnull WritableMap userInfo); @@ -84,18 +82,18 @@ public interface Promise { /** * Report an exception with a custom code and userInfo. * - * @param code String + * @param code String * @param throwable Throwable - * @param userInfo WritableMap + * @param userInfo WritableMap */ void reject(String code, Throwable throwable, WritableMap userInfo); /** - * Report an error with a custom code, error message and userInfo, - * an error not caused by an exception. + * Report an error with a custom code, error message and userInfo, an error not caused by an + * exception. * - * @param code String - * @param message String + * @param code String + * @param message String * @param userInfo WritableMap */ void reject(String code, String message, @Nonnull WritableMap userInfo); @@ -103,10 +101,10 @@ public interface Promise { /** * Report an exception with a custom code, error message and userInfo. * - * @param code String - * @param message String + * @param code String + * @param message String * @param throwable Throwable - * @param userInfo WritableMap + * @param userInfo WritableMap */ void reject(String code, String message, Throwable throwable, WritableMap userInfo); @@ -117,8 +115,8 @@ public interface Promise { /** * Report an error which wasn't caused by an exception. * - * @deprecated Prefer passing a module-specific error code to JS. - * Using this method will pass the error code "EUNSPECIFIED". + * @deprecated Prefer passing a module-specific error code to JS. Using this method will pass the + * error code "EUNSPECIFIED". */ @Deprecated void reject(String message); diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/PromiseImpl.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/PromiseImpl.java index fb3cceaa644..ccc1204bc27 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/PromiseImpl.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/PromiseImpl.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; import javax.annotation.Nonnull; @@ -37,10 +36,8 @@ public class PromiseImpl implements Promise { private static final String STACK_FRAME_KEY_LINE_NUMBER = "lineNumber"; private static final String STACK_FRAME_KEY_METHOD_NAME = "methodName"; - private @Nullable - Callback mResolve; - private @Nullable - Callback mReject; + private @Nullable Callback mResolve; + private @Nullable Callback mReject; public PromiseImpl(@Nullable Callback resolve, @Nullable Callback reject) { mResolve = resolve; @@ -64,46 +61,46 @@ public class PromiseImpl implements Promise { /** * Report an error without an exception using a custom code and error message. * - * @param code String + * @param code String * @param message String */ @Override public void reject(String code, String message) { - reject(code, message, /*Throwable*/null, /*WritableMap*/null); + reject(code, message, /*Throwable*/ null, /*WritableMap*/ null); } /** * Report an exception with a custom code. * - * @param code String + * @param code String * @param throwable Throwable */ @Override public void reject(String code, Throwable throwable) { - reject(code, /*Message*/null, throwable, /*WritableMap*/null); + reject(code, /*Message*/ null, throwable, /*WritableMap*/ null); } /** * Report an exception with a custom code and error message. * - * @param code String - * @param message String + * @param code String + * @param message String * @param throwable Throwable */ @Override public void reject(String code, String message, Throwable throwable) { - reject(code, message, throwable, /*WritableMap*/null); + reject(code, message, throwable, /*WritableMap*/ null); } /** - * Report an exception, with default error code. - * Useful in catch-all scenarios where it's unclear why the error occurred. + * Report an exception, with default error code. Useful in catch-all scenarios where it's unclear + * why the error occurred. * * @param throwable Throwable */ @Override public void reject(Throwable throwable) { - reject(/*Code*/null, /*Message*/null, throwable, /*WritableMap*/null); + reject(/*Code*/ null, /*Message*/ null, throwable, /*WritableMap*/ null); } /* --------------------------- @@ -111,68 +108,67 @@ public class PromiseImpl implements Promise { * --------------------------- */ /** - * Report an exception, with default error code, with userInfo. - * Useful in catch-all scenarios where it's unclear why the error occurred. + * Report an exception, with default error code, with userInfo. Useful in catch-all scenarios + * where it's unclear why the error occurred. * * @param throwable Throwable - * @param userInfo WritableMap + * @param userInfo WritableMap */ @Override public void reject(Throwable throwable, WritableMap userInfo) { - reject(/*Code*/null, /*Message*/null, throwable, userInfo); + reject(/*Code*/ null, /*Message*/ null, throwable, userInfo); } /** * Reject with a code and userInfo WritableMap. * - * @param code String + * @param code String * @param userInfo WritableMap */ @Override public void reject(String code, @Nonnull WritableMap userInfo) { - reject(code, /*Message*/null, /*Throwable*/null, userInfo); + reject(code, /*Message*/ null, /*Throwable*/ null, userInfo); } /** * Report an exception with a custom code and userInfo. * - * @param code String + * @param code String * @param throwable Throwable - * @param userInfo WritableMap + * @param userInfo WritableMap */ @Override public void reject(String code, Throwable throwable, WritableMap userInfo) { - reject(code, /*Message*/null, throwable, userInfo); + reject(code, /*Message*/ null, throwable, userInfo); } /** - * Report an error with a custom code, error message and userInfo, - * an error not caused by an exception. + * Report an error with a custom code, error message and userInfo, an error not caused by an + * exception. * - * @param code String - * @param message String + * @param code String + * @param message String * @param userInfo WritableMap */ @Override public void reject(String code, String message, @Nonnull WritableMap userInfo) { - reject(code, message, /*Throwable*/null, userInfo); + reject(code, message, /*Throwable*/ null, userInfo); } /** * Report an exception with a custom code, error message and userInfo. * - * @param code String - * @param message String + * @param code String + * @param message String * @param throwable Throwable - * @param userInfo WritableMap + * @param userInfo WritableMap */ @Override public void reject( @Nullable String code, @Nullable String message, @Nullable Throwable throwable, - @Nullable WritableMap userInfo - ) { + @Nullable WritableMap userInfo) { if (mReject == null) { mResolve = null; return; @@ -243,6 +239,6 @@ public class PromiseImpl implements Promise { @Override @Deprecated public void reject(String message) { - reject(/*Code*/null, message, /*Throwable*/null, /*WritableMap*/null); + reject(/*Code*/ null, message, /*Throwable*/ null, /*WritableMap*/ null); } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/ProxyJavaScriptExecutor.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/ProxyJavaScriptExecutor.java index ea5d126f799..7a556096937 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/ProxyJavaScriptExecutor.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/ProxyJavaScriptExecutor.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; import com.facebook.jni.HybridData; @@ -12,12 +11,12 @@ import com.facebook.proguard.annotations.DoNotStrip; import javax.annotation.Nullable; /** - * JavaScript executor that delegates JS calls processed by native code back to a java version - * of the native executor interface. + * JavaScript executor that delegates JS calls processed by native code back to a java version of + * the native executor interface. * - * When set as a executor with {@link CatalystInstance.Builder}, catalyst native code will delegate - * low level javascript calls to the implementation of {@link JavaJSExecutor} interface provided - * with the constructor of this class. + *

When set as a executor with {@link CatalystInstance.Builder}, catalyst native code will + * delegate low level javascript calls to the implementation of {@link JavaJSExecutor} interface + * provided with the constructor of this class. */ @DoNotStrip public class ProxyJavaScriptExecutor extends JavaScriptExecutor { @@ -42,8 +41,9 @@ public class ProxyJavaScriptExecutor extends JavaScriptExecutor { /** * Create {@link ProxyJavaScriptExecutor} instance + * * @param executor implementation of {@link JavaJSExecutor} which will be responsible for handling - * javascript calls + * javascript calls */ public ProxyJavaScriptExecutor(JavaJSExecutor executor) { super(initHybrid(executor)); @@ -63,5 +63,5 @@ public class ProxyJavaScriptExecutor extends JavaScriptExecutor { return "ProxyJavaScriptExecutor"; } - private native static HybridData initHybrid(JavaJSExecutor executor); + private static native HybridData initHybrid(JavaJSExecutor executor); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/ReactApplicationContext.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/ReactApplicationContext.java index f94c2382751..245f8c21b9d 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/ReactApplicationContext.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/ReactApplicationContext.java @@ -1,17 +1,16 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; import android.content.Context; /** - * A context wrapper that always wraps Android Application {@link Context} and - * {@link CatalystInstance} by extending {@link ReactContext} + * A context wrapper that always wraps Android Application {@link Context} and {@link + * CatalystInstance} by extending {@link ReactContext} */ public class ReactApplicationContext extends ReactContext { // We want to wrap ApplicationContext, since there is no easy way to verify that application diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/ReactBridge.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/ReactBridge.java index db7edacb75a..36acb022167 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/ReactBridge.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/ReactBridge.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; import static com.facebook.systrace.Systrace.TRACE_TAG_REACT_JAVA_BRIDGE; @@ -19,14 +18,15 @@ public class ReactBridge { private static boolean sDidInit = false; - public synchronized static void staticInit() { + public static synchronized void staticInit() { if (sDidInit) { return; } sDidInit = true; sLoadStartTime = SystemClock.uptimeMillis(); - Systrace.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "ReactBridge.staticInit::load:reactnativejni"); + Systrace.beginSection( + TRACE_TAG_REACT_JAVA_BRIDGE, "ReactBridge.staticInit::load:reactnativejni"); ReactMarker.logMarker(ReactMarkerConstants.LOAD_REACT_NATIVE_SO_FILE_START); SoLoader.loadLibrary("reactnativejni"); ReactMarker.logMarker(ReactMarkerConstants.LOAD_REACT_NATIVE_SO_FILE_END); diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/ReactCallback.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/ReactCallback.java index bc690b52a7e..8ddc0a95be2 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/ReactCallback.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/ReactCallback.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; import com.facebook.proguard.annotations.DoNotStrip; diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/ReactContext.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/ReactContext.java index c2e74c0b897..eaed58cdb3c 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/ReactContext.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/ReactContext.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; import android.app.Activity; @@ -22,22 +21,22 @@ import java.util.concurrent.CopyOnWriteArraySet; import javax.annotation.Nullable; /** - * Abstract ContextWrapper for Android application or activity {@link Context} and - * {@link CatalystInstance} + * Abstract ContextWrapper for Android application or activity {@link Context} and {@link + * CatalystInstance} */ public class ReactContext extends ContextWrapper { private static final String EARLY_JS_ACCESS_EXCEPTION_MESSAGE = - "Tried to access a JS module before the React instance was fully set up. Calls to " + - "ReactContext#getJSModule should only happen once initialize() has been called on your " + - "native module."; + "Tried to access a JS module before the React instance was fully set up. Calls to " + + "ReactContext#getJSModule should only happen once initialize() has been called on your " + + "native module."; private final CopyOnWriteArraySet mLifecycleEventListeners = new CopyOnWriteArraySet<>(); private final CopyOnWriteArraySet mActivityEventListeners = new CopyOnWriteArraySet<>(); private final CopyOnWriteArraySet mWindowFocusEventListeners = - new CopyOnWriteArraySet<>(); + new CopyOnWriteArraySet<>(); private LifecycleState mLifecycleState = LifecycleState.BEFORE_CREATE; @@ -53,9 +52,7 @@ public class ReactContext extends ContextWrapper { super(base); } - /** - * Set and initialize CatalystInstance for this Context. This should be called exactly once. - */ + /** Set and initialize CatalystInstance for this Context. This should be called exactly once. */ public void initializeWithInstance(CatalystInstance catalystInstance) { if (catalystInstance == null) { throw new IllegalArgumentException("CatalystInstance cannot be null."); @@ -71,11 +68,13 @@ public class ReactContext extends ContextWrapper { } /** - * Initialize message queue threads using a ReactQueueConfiguration. - * TODO (janzer) T43898341 Make this package instead of public + * Initialize message queue threads using a ReactQueueConfiguration. TODO (janzer) T43898341 Make + * this package instead of public */ public void initializeMessageQueueThreads(ReactQueueConfiguration queueConfig) { - if (mUiMessageQueueThread != null || mNativeModulesMessageQueueThread != null || mJSMessageQueueThread != null) { + if (mUiMessageQueueThread != null + || mNativeModulesMessageQueueThread != null + || mJSMessageQueueThread != null) { throw new IllegalStateException("Message queue threads already initialized"); } mUiMessageQueueThread = queueConfig.getUIQueueThread(); @@ -125,18 +124,16 @@ public class ReactContext extends ContextWrapper { public boolean hasNativeModule(Class nativeModuleInterface) { if (mCatalystInstance == null) { throw new RuntimeException( - "Trying to call native module before CatalystInstance has been set!"); + "Trying to call native module before CatalystInstance has been set!"); } return mCatalystInstance.hasNativeModule(nativeModuleInterface); } - /** - * @return the instance of the specified module interface associated with this ReactContext. - */ + /** @return the instance of the specified module interface associated with this ReactContext. */ public T getNativeModule(Class nativeModuleInterface) { if (mCatalystInstance == null) { throw new RuntimeException( - "Trying to call native module before CatalystInstance has been set!"); + "Trying to call native module before CatalystInstance has been set!"); } return mCatalystInstance.getNativeModule(nativeModuleInterface); } @@ -206,9 +203,7 @@ public class ReactContext extends ContextWrapper { mWindowFocusEventListeners.remove(listener); } - /** - * Should be called by the hosting Fragment in {@link Fragment#onResume} - */ + /** Should be called by the hosting Fragment in {@link Fragment#onResume} */ public void onHostResume(@Nullable Activity activity) { mLifecycleState = LifecycleState.RESUMED; mCurrentActivity = new WeakReference(activity); @@ -235,9 +230,7 @@ public class ReactContext extends ContextWrapper { } } - /** - * Should be called by the hosting Fragment in {@link Fragment#onPause} - */ + /** Should be called by the hosting Fragment in {@link Fragment#onPause} */ public void onHostPause() { mLifecycleState = LifecycleState.BEFORE_RESUME; ReactMarker.logMarker(ReactMarkerConstants.ON_HOST_PAUSE_START); @@ -251,9 +244,7 @@ public class ReactContext extends ContextWrapper { ReactMarker.logMarker(ReactMarkerConstants.ON_HOST_PAUSE_END); } - /** - * Should be called by the hosting Fragment in {@link Fragment#onDestroy} - */ + /** Should be called by the hosting Fragment in {@link Fragment#onDestroy} */ public void onHostDestroy() { UiThreadUtil.assertOnUiThread(); mLifecycleState = LifecycleState.BEFORE_CREATE; @@ -267,9 +258,7 @@ public class ReactContext extends ContextWrapper { mCurrentActivity = null; } - /** - * Destroy this instance, making it unusable. - */ + /** Destroy this instance, making it unusable. */ public void destroy() { UiThreadUtil.assertOnUiThread(); @@ -278,9 +267,7 @@ public class ReactContext extends ContextWrapper { } } - /** - * Should be called by the hosting Fragment in {@link Fragment#onActivityResult} - */ + /** Should be called by the hosting Fragment in {@link Fragment#onActivityResult} */ public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) { for (ActivityEventListener listener : mActivityEventListeners) { try { @@ -343,14 +330,14 @@ public class ReactContext extends ContextWrapper { } /** - * Passes the given exception to the current - * {@link com.facebook.react.bridge.NativeModuleCallExceptionHandler} if one exists, rethrowing + * Passes the given exception to the current {@link + * com.facebook.react.bridge.NativeModuleCallExceptionHandler} if one exists, rethrowing * otherwise. */ public void handleException(Exception e) { - if (mCatalystInstance != null && - !mCatalystInstance.isDestroyed() && - mNativeModuleCallExceptionHandler != null) { + if (mCatalystInstance != null + && !mCatalystInstance.isDestroyed() + && mNativeModuleCallExceptionHandler != null) { mNativeModuleCallExceptionHandler.handleException(e); } else { throw new RuntimeException(e); @@ -363,8 +350,8 @@ public class ReactContext extends ContextWrapper { /** * Same as {@link Activity#startActivityForResult(Intent, int)}, this just redirects the call to - * the current activity. Returns whether the activity was started, as this might fail if this - * was called before the context is in the right state. + * the current activity. Returns whether the activity was started, as this might fail if this was + * called before the context is in the right state. */ public boolean startActivityForResult(Intent intent, int code, Bundle bundle) { Activity activity = getCurrentActivity(); @@ -394,5 +381,4 @@ public class ReactContext extends ContextWrapper { public JavaScriptContextHolder getJavaScriptContextHolder() { return mCatalystInstance.getJavaScriptContextHolder(); } - } diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/ReactContextBaseJavaModule.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/ReactContextBaseJavaModule.java index 0fe9ac13a59..b9ef6122991 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/ReactContextBaseJavaModule.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/ReactContextBaseJavaModule.java @@ -1,20 +1,17 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; +import android.app.Activity; import javax.annotation.Nonnull; import javax.annotation.Nullable; -import android.app.Activity; - /** - * Base class for Catalyst native modules that require access to the {@link ReactContext} - * instance. + * Base class for Catalyst native modules that require access to the {@link ReactContext} instance. */ public abstract class ReactContextBaseJavaModule extends BaseJavaModule { @@ -24,9 +21,7 @@ public abstract class ReactContextBaseJavaModule extends BaseJavaModule { mReactApplicationContext = reactContext; } - /** - * Subclasses can use this method to access catalyst context passed as a constructor - */ + /** Subclasses can use this method to access catalyst context passed as a constructor */ protected final ReactApplicationContext getReactApplicationContext() { return mReactApplicationContext; } @@ -34,11 +29,12 @@ public abstract class ReactContextBaseJavaModule extends BaseJavaModule { /** * Get the activity to which this context is currently attached, or {@code null} if not attached. * - * DO NOT HOLD LONG-LIVED REFERENCES TO THE OBJECT RETURNED BY THIS METHOD, AS THIS WILL CAUSE + *

DO NOT HOLD LONG-LIVED REFERENCES TO THE OBJECT RETURNED BY THIS METHOD, AS THIS WILL CAUSE * MEMORY LEAKS. * - * For example, never store the value returned by this method in a member variable. Instead, call - * this method whenever you actually need the Activity and make sure to check for {@code null}. + *

For example, never store the value returned by this method in a member variable. Instead, + * call this method whenever you actually need the Activity and make sure to check for {@code + * null}. */ protected @Nullable final Activity getCurrentActivity() { return mReactApplicationContext.getCurrentActivity(); diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/ReactMarker.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/ReactMarker.java index d3f3e9f2250..9e444140e75 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/ReactMarker.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/ReactMarker.java @@ -5,16 +5,14 @@ package com.facebook.react.bridge; -import java.util.List; +import com.facebook.proguard.annotations.DoNotStrip; import java.util.ArrayList; - +import java.util.List; import javax.annotation.Nullable; -import com.facebook.proguard.annotations.DoNotStrip; - /** - * Static class that allows markers to be placed in React code and responded to in a - * configurable way + * Static class that allows markers to be placed in React code and responded to in a configurable + * way */ @DoNotStrip public class ReactMarker { @@ -30,7 +28,7 @@ public class ReactMarker { @DoNotStrip public static void addListener(MarkerListener listener) { - synchronized(sListeners) { + synchronized (sListeners) { if (!sListeners.contains(listener)) { sListeners.add(listener); } @@ -39,14 +37,14 @@ public class ReactMarker { @DoNotStrip public static void removeListener(MarkerListener listener) { - synchronized(sListeners) { + synchronized (sListeners) { sListeners.remove(listener); } } @DoNotStrip public static void clearMarkerListeners() { - synchronized(sListeners) { + synchronized (sListeners) { sListeners.clear(); } } @@ -89,7 +87,7 @@ public class ReactMarker { @DoNotStrip public static void logMarker(ReactMarkerConstants name, @Nullable String tag, int instanceKey) { - synchronized(sListeners) { + synchronized (sListeners) { for (MarkerListener listener : sListeners) { listener.logMarker(name, tag, instanceKey); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/ReactMarkerConstants.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/ReactMarkerConstants.java index b8292828803..89193a392e3 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/ReactMarkerConstants.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/ReactMarkerConstants.java @@ -5,9 +5,7 @@ package com.facebook.react.bridge; -/** - * Constants used by ReactMarker. - */ +/** Constants used by ReactMarker. */ public enum ReactMarkerConstants { CREATE_REACT_CONTEXT_START, CREATE_REACT_CONTEXT_END, diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/ReactMethod.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/ReactMethod.java index 2f52f534db9..b51a5196caa 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/ReactMethod.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/ReactMethod.java @@ -1,39 +1,37 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; -import java.lang.annotation.Retention; - import static java.lang.annotation.RetentionPolicy.RUNTIME; +import java.lang.annotation.Retention; + /** * Annotation which is used to mark methods that are exposed to React Native. * - * This applies to derived classes of {@link BaseJavaModule}, which will generate a list - * of exported methods by searching for those which are annotated with this annotation - * and adding a JS callback for each. + *

This applies to derived classes of {@link BaseJavaModule}, which will generate a list of + * exported methods by searching for those which are annotated with this annotation and adding a JS + * callback for each. */ @Retention(RUNTIME) public @interface ReactMethod { /** - * Whether the method can be called from JS synchronously **on the JS thread**, - * possibly returning a result. + * Whether the method can be called from JS synchronously **on the JS thread**, possibly returning + * a result. * - * WARNING: in the vast majority of cases, you should leave this to false which allows - * your native module methods to be called asynchronously: calling methods - * synchronously can have strong performance penalties and introduce threading-related - * bugs to your native modules. + *

WARNING: in the vast majority of cases, you should leave this to false which allows your + * native module methods to be called asynchronously: calling methods synchronously can have + * strong performance penalties and introduce threading-related bugs to your native modules. * - * In order to support remote debugging, both the method args and return type must be - * serializable to JSON: this means that we only support the same args as - * {@link ReactMethod}, and the hook can only be void or return JSON values (e.g. bool, - * number, String, {@link WritableMap}, or {@link WritableArray}). Calling these - * methods when running under the websocket executor is currently not supported. + *

In order to support remote debugging, both the method args and return type must be + * serializable to JSON: this means that we only support the same args as {@link ReactMethod}, and + * the hook can only be void or return JSON values (e.g. bool, number, String, {@link + * WritableMap}, or {@link WritableArray}). Calling these methods when running under the websocket + * executor is currently not supported. */ boolean isBlockingSynchronousMethod() default false; } diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/ReactModuleWithSpec.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/ReactModuleWithSpec.java index 716b2a3f6f5..44ea8301d9c 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/ReactModuleWithSpec.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/ReactModuleWithSpec.java @@ -1,19 +1,16 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; import com.facebook.proguard.annotations.DoNotStrip; /** - * An interface to be implemented by react modules that extends from the - * generated spec class. - * This is experimental. + * An interface to be implemented by react modules that extends from the generated spec class. This + * is experimental. */ @DoNotStrip -public interface ReactModuleWithSpec { -} +public interface ReactModuleWithSpec {} diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/ReadableArray.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/ReadableArray.java index 79b3bb63985..042121349b3 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/ReadableArray.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/ReadableArray.java @@ -1,14 +1,12 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; import java.util.ArrayList; - import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -19,15 +17,30 @@ import javax.annotation.Nullable; public interface ReadableArray { int size(); - boolean isNull(int index); - boolean getBoolean(int index); - double getDouble(int index); - int getInt(int index); - @Nullable String getString(int index); - @Nullable ReadableArray getArray(int index); - @Nullable ReadableMap getMap(int index); - @Nonnull Dynamic getDynamic(int index); - @Nonnull ReadableType getType(int index); - @Nonnull ArrayList toArrayList(); + boolean isNull(int index); + + boolean getBoolean(int index); + + double getDouble(int index); + + int getInt(int index); + + @Nullable + String getString(int index); + + @Nullable + ReadableArray getArray(int index); + + @Nullable + ReadableMap getMap(int index); + + @Nonnull + Dynamic getDynamic(int index); + + @Nonnull + ReadableType getType(int index); + + @Nonnull + ArrayList toArrayList(); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/ReadableMap.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/ReadableMap.java index a51e7c89d39..291b9e8f718 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/ReadableMap.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/ReadableMap.java @@ -9,7 +9,6 @@ package com.facebook.react.bridge; import java.util.HashMap; import java.util.Iterator; import java.util.Map; - import javax.annotation.Nonnull; import javax.annotation.Nullable; diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/ReadableMapKeySetIterator.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/ReadableMapKeySetIterator.java index c4cfbe019e4..15239b48883 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/ReadableMapKeySetIterator.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/ReadableMapKeySetIterator.java @@ -1,20 +1,18 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; import com.facebook.proguard.annotations.DoNotStrip; -/** - * Interface of a iterator for a {@link NativeMap}'s key set. - */ +/** Interface of a iterator for a {@link NativeMap}'s key set. */ @DoNotStrip public interface ReadableMapKeySetIterator { boolean hasNextKey(); + String nextKey(); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/ReadableNativeArray.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/ReadableNativeArray.java index a4c66cf8c83..d251e9b2a1b 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/ReadableNativeArray.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/ReadableNativeArray.java @@ -1,19 +1,16 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; import com.facebook.infer.annotation.Assertions; import com.facebook.jni.HybridData; import com.facebook.proguard.annotations.DoNotStrip; -import com.facebook.react.config.ReactFeatureFlags; import java.util.ArrayList; import java.util.Arrays; - import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -31,11 +28,12 @@ public class ReadableNativeArray extends NativeArray implements ReadableArray { super(hybridData); } - //WriteOnce but not in the constructor fields + // WriteOnce but not in the constructor fields private @Nullable Object[] mLocalArray; private @Nullable ReadableType[] mLocalTypeArray; private static int jniPassCounter = 0; + public static int getJNIPassCounter() { return jniPassCounter; } @@ -53,6 +51,7 @@ public class ReadableNativeArray extends NativeArray implements ReadableArray { } return mLocalArray; } + private native Object[] importArray(); private ReadableType[] getLocalTypeArray() { @@ -69,6 +68,7 @@ public class ReadableNativeArray extends NativeArray implements ReadableArray { } return mLocalTypeArray; } + private native Object[] importTypeArray(); @Override diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/ReadableNativeMap.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/ReadableNativeMap.java index 98a697978fb..be4691f08e1 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/ReadableNativeMap.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/ReadableNativeMap.java @@ -9,11 +9,9 @@ package com.facebook.react.bridge; import com.facebook.infer.annotation.Assertions; import com.facebook.jni.HybridData; import com.facebook.proguard.annotations.DoNotStrip; -import com.facebook.react.config.ReactFeatureFlags; import java.util.HashMap; import java.util.Iterator; import java.util.Map; - import javax.annotation.Nonnull; import javax.annotation.Nullable; diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/ReadableType.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/ReadableType.java index 9845f33f588..ff3a2a09564 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/ReadableType.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/ReadableType.java @@ -1,18 +1,14 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; import com.facebook.proguard.annotations.DoNotStrip; -/** - * Defines the type of an object stored in a {@link ReadableArray} or - * {@link ReadableMap}. - */ +/** Defines the type of an object stored in a {@link ReadableArray} or {@link ReadableMap}. */ @DoNotStrip public enum ReadableType { Null, diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/SoftAssertions.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/SoftAssertions.java index 168b67d62bc..4df3d3fa2cc 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/SoftAssertions.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/SoftAssertions.java @@ -1,26 +1,25 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; import javax.annotation.Nullable; /** * Utility class to make assertions that should not hard-crash the app but instead be handled by the - * Catalyst app {@link NativeModuleCallExceptionHandler}. See the javadoc on that class for - * more information about our opinion on when these assertions should be used as opposed to - * assertions that might throw AssertionError Throwables that will cause the app to hard crash. + * Catalyst app {@link NativeModuleCallExceptionHandler}. See the javadoc on that class for more + * information about our opinion on when these assertions should be used as opposed to assertions + * that might throw AssertionError Throwables that will cause the app to hard crash. */ public class SoftAssertions { /** - * Throw {@link AssertionException} with a given message. Use this method surrounded with - * {@code if} block with assert condition in case you plan to do string concatenation to produce - * the message. + * Throw {@link AssertionException} with a given message. Use this method surrounded with {@code + * if} block with assert condition in case you plan to do string concatenation to produce the + * message. */ public static void assertUnreachable(String message) { throw new AssertionException(message); @@ -36,9 +35,7 @@ public class SoftAssertions { } } - /** - * Asserts that the given Object isn't null, throwing an {@link AssertionException} if it was. - */ + /** Asserts that the given Object isn't null, throwing an {@link AssertionException} if it was. */ public static T assertNotNull(@Nullable T instance) { if (instance == null) { throw new AssertionException("Expected object to not be null!"); diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/Systrace.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/Systrace.java index 8f0520844ae..040b9cfe43d 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/Systrace.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/Systrace.java @@ -7,11 +7,9 @@ package com.facebook.react.bridge; import com.facebook.proguard.annotations.DoNotStrip; -/** - * Interface to the JavaScript Systrace Module - */ +/** Interface to the JavaScript Systrace Module */ @DoNotStrip -public interface Systrace extends JavaScriptModule{ +public interface Systrace extends JavaScriptModule { @DoNotStrip void setEnabled(boolean enabled); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/UIManager.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/UIManager.java index 883c039dc9b..d7e42ae69fc 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/UIManager.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/UIManager.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; import android.view.View; @@ -12,14 +11,11 @@ import javax.annotation.Nullable; public interface UIManager extends JSIModule, PerformanceCounter { - /** - * Registers a new root view. - */ - int addRootView(final T rootView, WritableMap initialProps, @Nullable String initialUITemplate); + /** Registers a new root view. */ + int addRootView( + final T rootView, WritableMap initialProps, @Nullable String initialUITemplate); - /** - * Unregisters a new root view. - */ + /** Unregisters a new root view. */ void removeRootView(int reactRootTag); /** @@ -29,10 +25,10 @@ public interface UIManager extends JSIModule, PerformanceCounter { void updateRootLayoutSpecs(int rootTag, int widthMeasureSpec, int heightMeasureSpec); /** - * Dispatches the commandId received by parameter to the view associated with the reactTag. - * The command will be processed in the UIThread. + * Dispatches the commandId received by parameter to the view associated with the reactTag. The + * command will be processed in the UIThread. * - * Receiving commands as ints is deprecated and will be removed in a future release. + *

Receiving commands as ints is deprecated and will be removed in a future release. * * @param reactTag {@link int} that identifies the view that will receive this command * @param commandId {@link int} command id @@ -41,8 +37,8 @@ public interface UIManager extends JSIModule, PerformanceCounter { void dispatchCommand(int reactTag, int commandId, @Nullable ReadableArray commandArgs); /** - * Dispatches the commandId received by parameter to the view associated with the reactTag. - * The command will be processed in the UIThread. + * Dispatches the commandId received by parameter to the view associated with the reactTag. The + * command will be processed in the UIThread. * * @param reactTag {@link int} that identifies the view that will receive this command * @param commandId {@link String} command id @@ -57,8 +53,8 @@ public interface UIManager extends JSIModule, PerformanceCounter { /** * Used by native animated module to bypass the process of updating the values through the shadow * view hierarchy. This method will directly update native views, which means that updates for - * layout-related propertied won't be handled properly. - * Make sure you know what you're doing before calling this method :) + * layout-related propertied won't be handled properly. Make sure you know what you're doing + * before calling this method :) * * @param tag {@link int} that identifies the view that will be updated * @param props {@link ReadableMap} props that should be immediately updated in view diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/UiThreadUtil.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/UiThreadUtil.java index 9b320097d69..38bf74fb2fc 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/UiThreadUtil.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/UiThreadUtil.java @@ -1,55 +1,41 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; -import javax.annotation.Nullable; - import android.os.Handler; import android.os.Looper; +import javax.annotation.Nullable; -/** - * Utility for interacting with the UI thread. - */ +/** Utility for interacting with the UI thread. */ public class UiThreadUtil { @Nullable private static Handler sMainHandler; - /** - * @return {@code true} if the current thread is the UI thread. - */ + /** @return {@code true} if the current thread is the UI thread. */ public static boolean isOnUiThread() { return Looper.getMainLooper().getThread() == Thread.currentThread(); } - /** - * Throws an {@link AssertionException} if the current thread is not the UI thread. - */ + /** Throws an {@link AssertionException} if the current thread is not the UI thread. */ public static void assertOnUiThread() { SoftAssertions.assertCondition(isOnUiThread(), "Expected to run on UI thread!"); } - /** - * Throws an {@link AssertionException} if the current thread is the UI thread. - */ + /** Throws an {@link AssertionException} if the current thread is the UI thread. */ public static void assertNotOnUiThread() { SoftAssertions.assertCondition(!isOnUiThread(), "Expected not to run on UI thread!"); } - /** - * Runs the given {@code Runnable} on the UI thread. - */ + /** Runs the given {@code Runnable} on the UI thread. */ public static void runOnUiThread(Runnable runnable) { runOnUiThread(runnable, 0); } - /** - * Runs the given {@code Runnable} on the UI thread with the specified delay. - */ + /** Runs the given {@code Runnable} on the UI thread with the specified delay. */ public static void runOnUiThread(Runnable runnable, long delayInMs) { synchronized (UiThreadUtil.class) { if (sMainHandler == null) { diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/UnexpectedNativeTypeException.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/UnexpectedNativeTypeException.java index c5400ddbae0..aeac0d205f3 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/UnexpectedNativeTypeException.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/UnexpectedNativeTypeException.java @@ -1,17 +1,16 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; import com.facebook.proguard.annotations.DoNotStrip; /** - * Exception thrown from native code when a type retrieved from a map or array (e.g. via - * {@link NativeArrayParameter#getString(int)}) does not match the expected type. + * Exception thrown from native code when a type retrieved from a map or array (e.g. via {@link + * NativeArrayParameter#getString(int)}) does not match the expected type. */ @DoNotStrip public class UnexpectedNativeTypeException extends RuntimeException { diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/WindowFocusChangeListener.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/WindowFocusChangeListener.java index d74b1089f9a..5e6e1480bc7 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/WindowFocusChangeListener.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/WindowFocusChangeListener.java @@ -3,10 +3,8 @@ // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. - package com.facebook.react.bridge; - /* * Listener for receiving window focus events. */ diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/WritableArray.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/WritableArray.java index 62d52d15805..dcbeb660aaa 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/WritableArray.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/WritableArray.java @@ -1,25 +1,27 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; -import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * Interface for a mutable array. Used to pass arguments from Java to JS. - */ +/** Interface for a mutable array. Used to pass arguments from Java to JS. */ public interface WritableArray extends ReadableArray { void pushNull(); + void pushBoolean(boolean value); + void pushDouble(double value); + void pushInt(int value); + void pushString(@Nullable String value); + void pushArray(@Nullable WritableArray array); + void pushMap(@Nullable WritableMap map); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/WritableMap.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/WritableMap.java index 9338c19ae96..b823a782e7b 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/WritableMap.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/WritableMap.java @@ -1,28 +1,32 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * Interface for a mutable map. Used to pass arguments from Java to JS. - */ +/** Interface for a mutable map. Used to pass arguments from Java to JS. */ public interface WritableMap extends ReadableMap { void putNull(@Nonnull String key); + void putBoolean(@Nonnull String key, boolean value); + void putDouble(@Nonnull String key, double value); + void putInt(@Nonnull String key, int value); + void putString(@Nonnull String key, @Nullable String value); + void putArray(@Nonnull String key, @Nullable WritableArray value); + void putMap(@Nonnull String key, @Nullable WritableMap value); void merge(@Nonnull ReadableMap source); + WritableMap copy(); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/WritableNativeArray.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/WritableNativeArray.java index 004477eb22f..3e1adba95c8 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/WritableNativeArray.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/WritableNativeArray.java @@ -1,23 +1,19 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; import com.facebook.infer.annotation.Assertions; import com.facebook.jni.HybridData; import com.facebook.proguard.annotations.DoNotStrip; - -import javax.annotation.Nonnull; import javax.annotation.Nullable; /** - * Implementation of a write-only array stored in native memory. Use - * {@link Arguments#createArray()} if you need to stub out creating this class in a test. - * TODO(5815532): Check if consumed on read + * Implementation of a write-only array stored in native memory. Use {@link Arguments#createArray()} + * if you need to stub out creating this class in a test. TODO(5815532): Check if consumed on read */ @DoNotStrip public class WritableNativeArray extends ReadableNativeArray implements WritableArray { @@ -31,12 +27,16 @@ public class WritableNativeArray extends ReadableNativeArray implements Writable @Override public native void pushNull(); + @Override public native void pushBoolean(boolean value); + @Override public native void pushDouble(double value); + @Override public native void pushInt(int value); + @Override public native void pushString(@Nullable String value); @@ -57,6 +57,8 @@ public class WritableNativeArray extends ReadableNativeArray implements Writable } private static native HybridData initHybrid(); + private native void pushNativeArray(WritableNativeArray array); + private native void pushNativeMap(WritableNativeMap map); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/WritableNativeMap.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/WritableNativeMap.java index 997f4058783..ac3d95dc826 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/WritableNativeMap.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/WritableNativeMap.java @@ -1,25 +1,21 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; import androidx.annotation.NonNull; - -import com.facebook.jni.HybridData; import com.facebook.infer.annotation.Assertions; +import com.facebook.jni.HybridData; import com.facebook.proguard.annotations.DoNotStrip; - import javax.annotation.Nonnull; import javax.annotation.Nullable; /** - * Implementation of a write-only map stored in native memory. Use - * {@link Arguments#createMap()} if you need to stub out creating this class in a test. - * TODO(5815532): Check if consumed on read + * Implementation of a write-only map stored in native memory. Use {@link Arguments#createMap()} if + * you need to stub out creating this class in a test. TODO(5815532): Check if consumed on read */ @DoNotStrip public class WritableNativeMap extends ReadableNativeMap implements WritableMap { @@ -29,12 +25,16 @@ public class WritableNativeMap extends ReadableNativeMap implements WritableMap @Override public native void putBoolean(@Nonnull String key, boolean value); + @Override public native void putDouble(@Nonnull String key, double value); + @Override public native void putInt(@Nonnull String key, int value); + @Override public native void putString(@Nonnull String key, @Nullable String value); + @Override public native void putNull(@NonNull String key); @@ -75,6 +75,8 @@ public class WritableNativeMap extends ReadableNativeMap implements WritableMap private static native HybridData initHybrid(); private native void putNativeMap(String key, WritableNativeMap value); + private native void putNativeArray(String key, WritableNativeArray value); + private native void mergeNativeMap(ReadableNativeMap source); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/MessageQueueThread.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/MessageQueueThread.java index ca3fda84c7e..a79f4c59ce5 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/MessageQueueThread.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/MessageQueueThread.java @@ -1,20 +1,16 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge.queue; +import com.facebook.proguard.annotations.DoNotStrip; import java.util.concurrent.Callable; import java.util.concurrent.Future; -import com.facebook.proguard.annotations.DoNotStrip; - -/** - * Encapsulates a Thread that can accept Runnables. - */ +/** Encapsulates a Thread that can accept Runnables. */ @DoNotStrip public interface MessageQueueThread { /** @@ -38,15 +34,15 @@ public interface MessageQueueThread { boolean isOnThread(); /** - * Asserts {@link #isOnThread()}, throwing a {@link AssertionException} (NOT an - * {@link AssertionError}) if the assertion fails. + * Asserts {@link #isOnThread()}, throwing a {@link AssertionException} (NOT an {@link + * AssertionError}) if the assertion fails. */ @DoNotStrip void assertIsOnThread(); /** - * Asserts {@link #isOnThread()}, throwing a {@link AssertionException} (NOT an - * {@link AssertionError}) if the assertion fails. The given message is appended to the error. + * Asserts {@link #isOnThread()}, throwing a {@link AssertionException} (NOT an {@link + * AssertionError}) if the assertion fails. The given message is appended to the error. */ @DoNotStrip void assertIsOnThread(String message); @@ -60,15 +56,15 @@ public interface MessageQueueThread { void quitSynchronous(); /** - * Returns the perf counters taken when the framework was started. This - * method is intended to be used for instrumentation purposes. + * Returns the perf counters taken when the framework was started. This method is intended to be + * used for instrumentation purposes. */ @DoNotStrip MessageQueueThreadPerfStats getPerfStats(); /** - * Resets the perf counters. This is useful if the RN threads are being re-used. - * This method is intended to be used for instrumentation purposes. + * Resets the perf counters. This is useful if the RN threads are being re-used. This method is + * intended to be used for instrumentation purposes. */ @DoNotStrip void resetPerfStats(); diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/MessageQueueThreadHandler.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/MessageQueueThreadHandler.java index d62247b845b..5238aad52ce 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/MessageQueueThreadHandler.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/MessageQueueThreadHandler.java @@ -1,19 +1,16 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge.queue; import android.os.Handler; import android.os.Looper; import android.os.Message; -/** - * Handler that can catch and dispatch Exceptions to an Exception handler. - */ +/** Handler that can catch and dispatch Exceptions to an Exception handler. */ public class MessageQueueThreadHandler extends Handler { private final QueueThreadExceptionHandler mExceptionHandler; diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/MessageQueueThreadImpl.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/MessageQueueThreadImpl.java index 76ce66b70c2..efac82e48b2 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/MessageQueueThreadImpl.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/MessageQueueThreadImpl.java @@ -1,18 +1,14 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge.queue; -import java.util.concurrent.Callable; -import java.util.concurrent.Future; - -import android.os.SystemClock; import android.os.Looper; import android.os.Process; +import android.os.SystemClock; import android.util.Pair; import com.facebook.common.logging.FLog; import com.facebook.proguard.annotations.DoNotStrip; @@ -21,10 +17,10 @@ import com.facebook.react.bridge.SoftAssertions; import com.facebook.react.bridge.UiThreadUtil; import com.facebook.react.common.ReactConstants; import com.facebook.react.common.futures.SimpleSettableFuture; +import java.util.concurrent.Callable; +import java.util.concurrent.Future; -/** - * Encapsulates a Thread that has a {@link Looper} running on it that can accept Runnables. - */ +/** Encapsulates a Thread that has a {@link Looper} running on it that can accept Runnables. */ @DoNotStrip public class MessageQueueThreadImpl implements MessageQueueThread { @@ -36,10 +32,8 @@ public class MessageQueueThreadImpl implements MessageQueueThread { private volatile boolean mIsFinished = false; private MessageQueueThreadImpl( - String name, - Looper looper, - QueueThreadExceptionHandler exceptionHandler) { - this(name, looper, exceptionHandler, null); + String name, Looper looper, QueueThreadExceptionHandler exceptionHandler) { + this(name, looper, exceptionHandler, null); } private MessageQueueThreadImpl( @@ -64,8 +58,9 @@ public class MessageQueueThreadImpl implements MessageQueueThread { if (mIsFinished) { FLog.w( ReactConstants.TAG, - "Tried to enqueue runnable on already finished thread: '" + getName() + - "... dropping Runnable."); + "Tried to enqueue runnable on already finished thread: '" + + getName() + + "... dropping Runnable."); } mHandler.post(runnable); } @@ -98,8 +93,8 @@ public class MessageQueueThreadImpl implements MessageQueueThread { } /** - * Asserts {@link #isOnThread()}, throwing a {@link AssertionException} (NOT an - * {@link AssertionError}) if the assertion fails. + * Asserts {@link #isOnThread()}, throwing a {@link AssertionException} (NOT an {@link + * AssertionError}) if the assertion fails. */ @DoNotStrip @Override @@ -108,15 +103,15 @@ public class MessageQueueThreadImpl implements MessageQueueThread { } /** - * Asserts {@link #isOnThread()}, throwing a {@link AssertionException} (NOT an - * {@link AssertionError}) if the assertion fails. + * Asserts {@link #isOnThread()}, throwing a {@link AssertionException} (NOT an {@link + * AssertionError}) if the assertion fails. */ @DoNotStrip @Override public void assertIsOnThread(String message) { SoftAssertions.assertCondition( - isOnThread(), - new StringBuilder().append(mAssertionErrorMessage).append(" ").append(message).toString()); + isOnThread(), + new StringBuilder().append(mAssertionErrorMessage).append(" ").append(message).toString()); } /** @@ -147,14 +142,15 @@ public class MessageQueueThreadImpl implements MessageQueueThread { @Override public void resetPerfStats() { assignToPerfStats(mPerfStats, -1, -1); - runOnQueue(new Runnable() { - @Override - public void run() { - long wallTime = SystemClock.uptimeMillis(); - long cpuTime = SystemClock.currentThreadTimeMillis(); - assignToPerfStats(mPerfStats, wallTime, cpuTime); - } - }); + runOnQueue( + new Runnable() { + @Override + public void run() { + long wallTime = SystemClock.uptimeMillis(); + long cpuTime = SystemClock.currentThreadTimeMillis(); + assignToPerfStats(mPerfStats, wallTime, cpuTime); + } + }); } private static void assignToPerfStats(MessageQueueThreadPerfStats stats, long wall, long cpu) { @@ -171,8 +167,7 @@ public class MessageQueueThreadImpl implements MessageQueueThread { } public static MessageQueueThreadImpl create( - MessageQueueThreadSpec spec, - QueueThreadExceptionHandler exceptionHandler) { + MessageQueueThreadSpec spec, QueueThreadExceptionHandler exceptionHandler) { switch (spec.getThreadType()) { case MAIN_UI: return createForMainThread(spec.getName(), exceptionHandler); @@ -183,12 +178,9 @@ public class MessageQueueThreadImpl implements MessageQueueThread { } } - /** - * @return a MessageQueueThreadImpl corresponding to Android's main UI thread. - */ + /** @return a MessageQueueThreadImpl corresponding to Android's main UI thread. */ private static MessageQueueThreadImpl createForMainThread( - String name, - QueueThreadExceptionHandler exceptionHandler) { + String name, QueueThreadExceptionHandler exceptionHandler) { Looper mainLooper = Looper.getMainLooper(); final MessageQueueThreadImpl mqt = new MessageQueueThreadImpl(name, mainLooper, exceptionHandler); @@ -209,29 +201,32 @@ public class MessageQueueThreadImpl implements MessageQueueThread { /** * Creates and starts a new MessageQueueThreadImpl encapsulating a new Thread with a new Looper - * running on it. Give it a name for easier debugging and optionally a suggested stack size. - * When this method exits, the new MessageQueueThreadImpl is ready to receive events. + * running on it. Give it a name for easier debugging and optionally a suggested stack size. When + * this method exits, the new MessageQueueThreadImpl is ready to receive events. */ private static MessageQueueThreadImpl startNewBackgroundThread( - final String name, - long stackSize, - QueueThreadExceptionHandler exceptionHandler) { - final SimpleSettableFuture> dataFuture = new SimpleSettableFuture<>(); + final String name, long stackSize, QueueThreadExceptionHandler exceptionHandler) { + final SimpleSettableFuture> dataFuture = + new SimpleSettableFuture<>(); long startTimeMillis; - Thread bgThread = new Thread(null, - new Runnable() { - @Override - public void run() { - Process.setThreadPriority(Process.THREAD_PRIORITY_DISPLAY); - Looper.prepare(); - MessageQueueThreadPerfStats stats = new MessageQueueThreadPerfStats(); - long wallTime = SystemClock.uptimeMillis(); - long cpuTime = SystemClock.currentThreadTimeMillis(); - assignToPerfStats(stats, wallTime, cpuTime); - dataFuture.set(new Pair<>(Looper.myLooper(), stats)); - Looper.loop(); - } - }, "mqt_" + name, stackSize); + Thread bgThread = + new Thread( + null, + new Runnable() { + @Override + public void run() { + Process.setThreadPriority(Process.THREAD_PRIORITY_DISPLAY); + Looper.prepare(); + MessageQueueThreadPerfStats stats = new MessageQueueThreadPerfStats(); + long wallTime = SystemClock.uptimeMillis(); + long cpuTime = SystemClock.currentThreadTimeMillis(); + assignToPerfStats(stats, wallTime, cpuTime); + dataFuture.set(new Pair<>(Looper.myLooper(), stats)); + Looper.loop(); + } + }, + "mqt_" + name, + stackSize); bgThread.start(); Pair pair = dataFuture.getOrThrow(); diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/MessageQueueThreadPerfStats.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/MessageQueueThreadPerfStats.java index 7b7866645c1..639a96bdd8e 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/MessageQueueThreadPerfStats.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/MessageQueueThreadPerfStats.java @@ -1,15 +1,12 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge.queue; -/** - * This class holds perf counters' values at the beginning of an RN startup. - */ +/** This class holds perf counters' values at the beginning of an RN startup. */ public class MessageQueueThreadPerfStats { public long wallTime; public long cpuTime; diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/MessageQueueThreadSpec.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/MessageQueueThreadSpec.java index bc48673a1b6..7e7c240b1e7 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/MessageQueueThreadSpec.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/MessageQueueThreadSpec.java @@ -1,15 +1,12 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge.queue; -/** - * Spec for creating a MessageQueueThread. - */ +/** Spec for creating a MessageQueueThread. */ public class MessageQueueThreadSpec { private static final MessageQueueThreadSpec MAIN_UI_SPEC = diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/NativeRunnable.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/NativeRunnable.java index c5b0e2e0405..240ab4edc82 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/NativeRunnable.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/NativeRunnable.java @@ -1,18 +1,15 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge.queue; import com.facebook.jni.HybridData; import com.facebook.proguard.annotations.DoNotStrip; -/** - * A Runnable that has a native run implementation. - */ +/** A Runnable that has a native run implementation. */ @DoNotStrip public class NativeRunnable implements Runnable { diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/NativeRunnableDeprecated.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/NativeRunnableDeprecated.java index 2f8a2e5e914..b4b9622144e 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/NativeRunnableDeprecated.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/NativeRunnableDeprecated.java @@ -1,25 +1,20 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge.queue; import com.facebook.jni.Countable; -import com.facebook.jni.HybridData; import com.facebook.proguard.annotations.DoNotStrip; -/** - * A Runnable that has a native run implementation. - */ +/** A Runnable that has a native run implementation. */ @DoNotStrip public class NativeRunnableDeprecated extends Countable implements Runnable { @DoNotStrip - private NativeRunnableDeprecated() { - } + private NativeRunnableDeprecated() {} public native void run(); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/QueueThreadExceptionHandler.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/QueueThreadExceptionHandler.java index f0f08a3cccd..9ed429db4e1 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/QueueThreadExceptionHandler.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/QueueThreadExceptionHandler.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge.queue; /** diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/ReactQueueConfiguration.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/ReactQueueConfiguration.java index 5a666785553..4c240b2714b 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/ReactQueueConfiguration.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/ReactQueueConfiguration.java @@ -1,25 +1,26 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge.queue; - /** - * Specifies which {@link MessageQueueThread}s must be used to run the various contexts of - * execution within catalyst (Main UI thread, native modules, and JS). Some of these queues *may* be - * the same but should be coded against as if they are different. + * Specifies which {@link MessageQueueThread}s must be used to run the various contexts of execution + * within catalyst (Main UI thread, native modules, and JS). Some of these queues *may* be the same + * but should be coded against as if they are different. * - * UI Queue Thread: The standard Android main UI thread and Looper. Not configurable. - * Native Modules Queue Thread: The thread and Looper that native modules are invoked on. - * JS Queue Thread: The thread and Looper that JS is executed on. + *

UI Queue Thread: The standard Android main UI thread and Looper. Not configurable. Native + * Modules Queue Thread: The thread and Looper that native modules are invoked on. JS Queue Thread: + * The thread and Looper that JS is executed on. */ public interface ReactQueueConfiguration { MessageQueueThread getUIQueueThread(); + MessageQueueThread getNativeModulesQueueThread(); + MessageQueueThread getJSQueueThread(); + void destroy(); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/ReactQueueConfigurationImpl.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/ReactQueueConfigurationImpl.java index 4388949362c..4b8dc010ac3 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/ReactQueueConfigurationImpl.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/ReactQueueConfigurationImpl.java @@ -1,17 +1,14 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge.queue; -import java.util.Map; - import android.os.Looper; - import com.facebook.react.common.MapBuilder; +import java.util.Map; public class ReactQueueConfigurationImpl implements ReactQueueConfiguration { @@ -44,8 +41,8 @@ public class ReactQueueConfigurationImpl implements ReactQueueConfiguration { } /** - * Should be called when the corresponding {@link com.facebook.react.bridge.CatalystInstance} - * is destroyed so that we shut down the proper queue threads. + * Should be called when the corresponding {@link com.facebook.react.bridge.CatalystInstance} is + * destroyed so that we shut down the proper queue threads. */ public void destroy() { if (mNativeModulesQueueThread.getLooper() != Looper.getMainLooper()) { @@ -57,13 +54,11 @@ public class ReactQueueConfigurationImpl implements ReactQueueConfiguration { } public static ReactQueueConfigurationImpl create( - ReactQueueConfigurationSpec spec, - QueueThreadExceptionHandler exceptionHandler) { + ReactQueueConfigurationSpec spec, QueueThreadExceptionHandler exceptionHandler) { Map specsToThreads = MapBuilder.newHashMap(); MessageQueueThreadSpec uiThreadSpec = MessageQueueThreadSpec.mainThreadSpec(); - MessageQueueThreadImpl uiThread = - MessageQueueThreadImpl.create(uiThreadSpec, exceptionHandler); + MessageQueueThreadImpl uiThread = MessageQueueThreadImpl.create(uiThreadSpec, exceptionHandler); specsToThreads.put(uiThreadSpec, uiThread); MessageQueueThreadImpl jsThread = specsToThreads.get(spec.getJSQueueThreadSpec()); @@ -78,9 +73,6 @@ public class ReactQueueConfigurationImpl implements ReactQueueConfiguration { MessageQueueThreadImpl.create(spec.getNativeModulesQueueThreadSpec(), exceptionHandler); } - return new ReactQueueConfigurationImpl( - uiThread, - nativeModulesThread, - jsThread); + return new ReactQueueConfigurationImpl(uiThread, nativeModulesThread, jsThread); } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/ReactQueueConfigurationSpec.java b/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/ReactQueueConfigurationSpec.java index f81deff7c75..e00b217db96 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/ReactQueueConfigurationSpec.java +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/queue/ReactQueueConfigurationSpec.java @@ -1,21 +1,18 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge.queue; import android.os.Build; - +import com.facebook.infer.annotation.Assertions; import javax.annotation.Nullable; -import com.facebook.infer.annotation.Assertions; - /** - * Spec for creating a ReactQueueConfiguration. This exists so that CatalystInstance is able to - * set Exception handlers on the MessageQueueThreads it uses and it would not be super clean if the + * Spec for creating a ReactQueueConfiguration. This exists so that CatalystInstance is able to set + * Exception handlers on the MessageQueueThreads it uses and it would not be super clean if the * threads were configured, then passed to CatalystInstance where they are configured more. These * specs allows the Threads to be created fully configured. */ @@ -27,8 +24,8 @@ public class ReactQueueConfigurationSpec { private final MessageQueueThreadSpec mJSQueueThreadSpec; private ReactQueueConfigurationSpec( - MessageQueueThreadSpec nativeModulesQueueThreadSpec, - MessageQueueThreadSpec jsQueueThreadSpec) { + MessageQueueThreadSpec nativeModulesQueueThreadSpec, + MessageQueueThreadSpec jsQueueThreadSpec) { mNativeModulesQueueThreadSpec = nativeModulesQueueThreadSpec; mJSQueueThreadSpec = jsQueueThreadSpec; } @@ -46,9 +43,11 @@ public class ReactQueueConfigurationSpec { } public static ReactQueueConfigurationSpec createDefault() { - MessageQueueThreadSpec spec = Build.VERSION.SDK_INT < 21 ? - MessageQueueThreadSpec.newBackgroundThreadSpec("native_modules", LEGACY_STACK_SIZE_BYTES) : - MessageQueueThreadSpec.newBackgroundThreadSpec("native_modules"); + MessageQueueThreadSpec spec = + Build.VERSION.SDK_INT < 21 + ? MessageQueueThreadSpec.newBackgroundThreadSpec( + "native_modules", LEGACY_STACK_SIZE_BYTES) + : MessageQueueThreadSpec.newBackgroundThreadSpec("native_modules"); return builder() .setJSQueueThreadSpec(MessageQueueThreadSpec.newBackgroundThreadSpec("js")) .setNativeModulesQueueThreadSpec(spec) @@ -62,8 +61,7 @@ public class ReactQueueConfigurationSpec { public Builder setNativeModulesQueueThreadSpec(MessageQueueThreadSpec spec) { Assertions.assertCondition( - mNativeModulesQueueSpec == null, - "Setting native modules queue spec multiple times!"); + mNativeModulesQueueSpec == null, "Setting native modules queue spec multiple times!"); mNativeModulesQueueSpec = spec; return this; } @@ -76,8 +74,8 @@ public class ReactQueueConfigurationSpec { public ReactQueueConfigurationSpec build() { return new ReactQueueConfigurationSpec( - Assertions.assertNotNull(mNativeModulesQueueSpec), - Assertions.assertNotNull(mJSQueueSpec)); + Assertions.assertNotNull(mNativeModulesQueueSpec), + Assertions.assertNotNull(mJSQueueSpec)); } } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/common/ArrayUtils.java b/ReactAndroid/src/main/java/com/facebook/react/common/ArrayUtils.java index b689d8b0ad9..06c575745db 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/common/ArrayUtils.java +++ b/ReactAndroid/src/main/java/com/facebook/react/common/ArrayUtils.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.common; import java.util.Arrays; diff --git a/ReactAndroid/src/main/java/com/facebook/react/common/ClearableSynchronizedPool.java b/ReactAndroid/src/main/java/com/facebook/react/common/ClearableSynchronizedPool.java index 51c26e3c23b..872a4457d81 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/common/ClearableSynchronizedPool.java +++ b/ReactAndroid/src/main/java/com/facebook/react/common/ClearableSynchronizedPool.java @@ -8,8 +8,8 @@ package com.facebook.react.common; import androidx.core.util.Pools; /** - * Like {@link androidx.core.util.Pools.SynchronizedPool} with the option to clear the pool - * (e.g. on memory pressure). + * Like {@link androidx.core.util.Pools.SynchronizedPool} with the option to clear the pool (e.g. on + * memory pressure). */ public class ClearableSynchronizedPool implements Pools.Pool { diff --git a/ReactAndroid/src/main/java/com/facebook/react/common/DebugServerException.java b/ReactAndroid/src/main/java/com/facebook/react/common/DebugServerException.java index dd82b0b451b..9e19c9042fc 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/common/DebugServerException.java +++ b/ReactAndroid/src/main/java/com/facebook/react/common/DebugServerException.java @@ -1,42 +1,37 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.common; -import javax.annotation.Nullable; - -import java.io.IOException; - import android.net.Uri; import android.text.TextUtils; - import com.facebook.common.logging.FLog; - +import javax.annotation.Nullable; import org.json.JSONException; import org.json.JSONObject; /** - * Tracks errors connecting to or received from the debug server. - * The debug server returns errors as json objects. This exception represents that error. + * Tracks errors connecting to or received from the debug server. The debug server returns errors as + * json objects. This exception represents that error. */ public class DebugServerException extends RuntimeException { private static final String GENERIC_ERROR_MESSAGE = - "\n\nTry the following to fix the issue:\n" + - "\u2022 Ensure that the packager server is running\n" + - "\u2022 Ensure that your device/emulator is connected to your machine and has USB debugging enabled - run 'adb devices' to see a list of connected devices\n" + - "\u2022 Ensure Airplane Mode is disabled\n" + - "\u2022 If you're on a physical device connected to the same machine, run 'adb reverse tcp: tcp:' to forward requests from your device\n" + - "\u2022 If your device is on the same Wi-Fi network, set 'Debug server host & port for device' in 'Dev settings' to your machine's IP address and the port of the local dev server - e.g. 10.0.1.1:\n\n"; + "\n\nTry the following to fix the issue:\n" + + "\u2022 Ensure that the packager server is running\n" + + "\u2022 Ensure that your device/emulator is connected to your machine and has USB debugging enabled - run 'adb devices' to see a list of connected devices\n" + + "\u2022 Ensure Airplane Mode is disabled\n" + + "\u2022 If you're on a physical device connected to the same machine, run 'adb reverse tcp: tcp:' to forward requests from your device\n" + + "\u2022 If your device is on the same Wi-Fi network, set 'Debug server host & port for device' in 'Dev settings' to your machine's IP address and the port of the local dev server - e.g. 10.0.1.1:\n\n"; public static DebugServerException makeGeneric(String url, String reason, Throwable t) { return makeGeneric(url, reason, "", t); } - public static DebugServerException makeGeneric(String url, String reason, String extra, Throwable t) { + public static DebugServerException makeGeneric( + String url, String reason, String extra, Throwable t) { Uri uri = Uri.parse(url); String message = GENERIC_ERROR_MESSAGE.replace("", String.valueOf(uri.getPort())); @@ -58,10 +53,12 @@ public class DebugServerException extends RuntimeException { /** * Parse a DebugServerException from the server json string. + * * @param str json string returned by the debug server * @return A DebugServerException or null if the string is not of proper form. */ - @Nullable public static DebugServerException parse(String url, String str) { + @Nullable + public static DebugServerException parse(String url, String str) { if (TextUtils.isEmpty(str)) { return null; } diff --git a/ReactAndroid/src/main/java/com/facebook/react/common/JavascriptException.java b/ReactAndroid/src/main/java/com/facebook/react/common/JavascriptException.java index 52a56e93b68..4c421db5a6b 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/common/JavascriptException.java +++ b/ReactAndroid/src/main/java/com/facebook/react/common/JavascriptException.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.common; /** diff --git a/ReactAndroid/src/main/java/com/facebook/react/common/LifecycleState.java b/ReactAndroid/src/main/java/com/facebook/react/common/LifecycleState.java index 656d77d9678..0b2e61e0ab3 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/common/LifecycleState.java +++ b/ReactAndroid/src/main/java/com/facebook/react/common/LifecycleState.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.common; /** @@ -12,11 +11,7 @@ package com.facebook.react.common; * basically the same so this enum is in terms of the forward lifecycle progression (onResume, etc). * Eventually, if necessary, it could contain something like: * - * BEFORE_CREATE, - * CREATED, - * VIEW_CREATED, - * STARTED, - * RESUMED + *

BEFORE_CREATE, CREATED, VIEW_CREATED, STARTED, RESUMED */ public enum LifecycleState { BEFORE_CREATE, diff --git a/ReactAndroid/src/main/java/com/facebook/react/common/LongArray.java b/ReactAndroid/src/main/java/com/facebook/react/common/LongArray.java index 9b6191182fd..0b8d2d3fc4b 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/common/LongArray.java +++ b/ReactAndroid/src/main/java/com/facebook/react/common/LongArray.java @@ -1,15 +1,12 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.common; -/** - * Object wrapping an auto-expanding long[]. Like an ArrayList but without the autoboxing. - */ +/** Object wrapping an auto-expanding long[]. Like an ArrayList but without the autoboxing. */ public class LongArray { private static final double INNER_ARRAY_GROWTH_FACTOR = 1.8; @@ -53,9 +50,7 @@ public class LongArray { return mLength == 0; } - /** - * Removes the *last* n items of the array all at once. - */ + /** Removes the *last* n items of the array all at once. */ public void dropTail(int n) { if (n > mLength) { throw new IndexOutOfBoundsException( @@ -67,7 +62,7 @@ public class LongArray { private void growArrayIfNeeded() { if (mLength == mArray.length) { // If the initial capacity was 1 we need to ensure it at least grows by 1. - int newSize = Math.max(mLength + 1, (int)(mLength * INNER_ARRAY_GROWTH_FACTOR)); + int newSize = Math.max(mLength + 1, (int) (mLength * INNER_ARRAY_GROWTH_FACTOR)); long[] newArray = new long[newSize]; System.arraycopy(mArray, 0, newArray, 0, mLength); mArray = newArray; diff --git a/ReactAndroid/src/main/java/com/facebook/react/common/MapBuilder.java b/ReactAndroid/src/main/java/com/facebook/react/common/MapBuilder.java index 5c668ad14cd..7346926a077 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/common/MapBuilder.java +++ b/ReactAndroid/src/main/java/com/facebook/react/common/MapBuilder.java @@ -1,46 +1,35 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.common; import java.util.HashMap; import java.util.Map; -/** - * Utility class for creating maps - */ +/** Utility class for creating maps */ public class MapBuilder { - /** - * Creates an instance of {@code HashMap} - */ + /** Creates an instance of {@code HashMap} */ public static HashMap newHashMap() { return new HashMap(); } - /** - * Returns the empty map. - */ + /** Returns the empty map. */ public static Map of() { return newHashMap(); } - /** - * Returns map containing a single entry. - */ + /** Returns map containing a single entry. */ public static Map of(K k1, V v1) { Map map = of(); map.put(k1, v1); return map; } - /** - * Returns map containing the given entries. - */ + /** Returns map containing the given entries. */ public static Map of(K k1, V v1, K k2, V v2) { Map map = of(); map.put(k1, v1); @@ -48,9 +37,7 @@ public class MapBuilder { return map; } - /** - * Returns map containing the given entries. - */ + /** Returns map containing the given entries. */ public static Map of(K k1, V v1, K k2, V v2, K k3, V v3) { Map map = of(); map.put(k1, v1); @@ -59,9 +46,7 @@ public class MapBuilder { return map; } - /** - * Returns map containing the given entries. - */ + /** Returns map containing the given entries. */ public static Map of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) { Map map = of(); map.put(k1, v1); @@ -71,9 +56,7 @@ public class MapBuilder { return map; } - /** - * Returns map containing the given entries. - */ + /** Returns map containing the given entries. */ public static Map of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) { Map map = of(); map.put(k1, v1); @@ -84,9 +67,7 @@ public class MapBuilder { return map; } - /** - * Returns map containing the given entries. - */ + /** Returns map containing the given entries. */ public static Map of( K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6) { Map map = of(); @@ -99,9 +80,7 @@ public class MapBuilder { return map; } - /** - * Returns map containing the given entries. - */ + /** Returns map containing the given entries. */ public static Map of( K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7) { Map map = of(); @@ -115,9 +94,7 @@ public class MapBuilder { return map; } - /** - * Returns map containing the given entries. - */ + /** Returns map containing the given entries. */ public static Builder builder() { return new Builder(); } @@ -132,15 +109,15 @@ public class MapBuilder { mUnderConstruction = true; } - public Builder put(K k, V v) { + public Builder put(K k, V v) { if (!mUnderConstruction) { throw new IllegalStateException("Underlying map has already been built"); } - mMap.put(k,v); + mMap.put(k, v); return this; } - public Map build() { + public Map build() { if (!mUnderConstruction) { throw new IllegalStateException("Underlying map has already been built"); } @@ -148,5 +125,4 @@ public class MapBuilder { return mMap; } } - } diff --git a/ReactAndroid/src/main/java/com/facebook/react/common/ReactConstants.java b/ReactAndroid/src/main/java/com/facebook/react/common/ReactConstants.java index 83ca41a2a99..cdf1db635eb 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/common/ReactConstants.java +++ b/ReactAndroid/src/main/java/com/facebook/react/common/ReactConstants.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.common; public class ReactConstants { diff --git a/ReactAndroid/src/main/java/com/facebook/react/common/ShakeDetector.java b/ReactAndroid/src/main/java/com/facebook/react/common/ShakeDetector.java index 01a0da121d6..cbb32cbbab0 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/common/ShakeDetector.java +++ b/ReactAndroid/src/main/java/com/facebook/react/common/ShakeDetector.java @@ -1,33 +1,26 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.common; -import javax.annotation.Nullable; - -import java.util.concurrent.TimeUnit; - import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; - import com.facebook.infer.annotation.Assertions; +import java.util.concurrent.TimeUnit; +import javax.annotation.Nullable; -/** - * Listens for the user shaking their phone. Allocation-less once it starts listening. - */ +/** Listens for the user shaking their phone. Allocation-less once it starts listening. */ public class ShakeDetector implements SensorEventListener { // Collect sensor data in this interval (nanoseconds) private static final long MIN_TIME_BETWEEN_SAMPLES_NS = - TimeUnit.NANOSECONDS.convert(20, TimeUnit.MILLISECONDS); + TimeUnit.NANOSECONDS.convert(20, TimeUnit.MILLISECONDS); // Number of nanoseconds to listen for and count shakes (nanoseconds) - private static final float SHAKING_WINDOW_NS = - TimeUnit.NANOSECONDS.convert(3, TimeUnit.SECONDS); + private static final float SHAKING_WINDOW_NS = TimeUnit.NANOSECONDS.convert(3, TimeUnit.SECONDS); // Required force to constitute a rage shake. Need to multiply gravity by 1.33 because a rage // shake in one direction should have more force than just the magnitude of free fall. private static final float REQUIRED_FORCE = SensorManager.GRAVITY_EARTH * 1.33f; @@ -44,7 +37,7 @@ public class ShakeDetector implements SensorEventListener { private long mLastTimestamp; private int mNumShakes; private long mLastShakeTimestamp; - //number of shakes required to trigger onShake() + // number of shakes required to trigger onShake() private int mMinNumShakes; public ShakeDetector(ShakeListener listener) { @@ -56,9 +49,7 @@ public class ShakeDetector implements SensorEventListener { mMinNumShakes = minNumShakes; } - /** - * Start listening for shakes. - */ + /** Start listening for shakes. */ public void start(SensorManager manager) { Assertions.assertNotNull(manager); Sensor accelerometer = manager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); @@ -71,9 +62,7 @@ public class ShakeDetector implements SensorEventListener { } } - /** - * Stop listening for shakes. - */ + /** Stop listening for shakes. */ public void stop() { if (mSensorManager != null) { mSensorManager.unregisterListener(this); @@ -81,9 +70,7 @@ public class ShakeDetector implements SensorEventListener { } } - /** - * Reset all variables used to keep track of number of shakes recorded. - */ + /** Reset all variables used to keep track of number of shakes recorded. */ private void reset() { mNumShakes = 0; mAccelerationX = 0; @@ -95,8 +82,8 @@ public class ShakeDetector implements SensorEventListener { * Determine if acceleration applied to sensor is large enough to count as a rage shake. * * @param a acceleration in x, y, or z applied to the sensor - * @return true if the magnitude of the force exceeds the minimum required amount of force. - * false otherwise. + * @return true if the magnitude of the force exceeds the minimum required amount of force. false + * otherwise. */ private boolean atLeastRequiredForce(float a) { return Math.abs(a) > REQUIRED_FORCE; @@ -104,6 +91,7 @@ public class ShakeDetector implements SensorEventListener { /** * Save data about last shake + * * @param timestamp (ns) of last sensor event */ private void recordShake(long timestamp) { @@ -138,8 +126,7 @@ public class ShakeDetector implements SensorEventListener { } @Override - public void onAccuracyChanged(Sensor sensor, int i) { - } + public void onAccuracyChanged(Sensor sensor, int i) {} private void maybeDispatchShake(long currentTimestamp) { if (mNumShakes >= 8 * mMinNumShakes) { diff --git a/ReactAndroid/src/main/java/com/facebook/react/common/SingleThreadAsserter.java b/ReactAndroid/src/main/java/com/facebook/react/common/SingleThreadAsserter.java index 63a1ea63875..16e96ae9c51 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/common/SingleThreadAsserter.java +++ b/ReactAndroid/src/main/java/com/facebook/react/common/SingleThreadAsserter.java @@ -1,19 +1,15 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.common; +import com.facebook.infer.annotation.Assertions; import javax.annotation.Nullable; -import com.facebook.infer.annotation.Assertions; - -/** - * Simple class for asserting that operations only run on a single thread. - */ +/** Simple class for asserting that operations only run on a single thread. */ public class SingleThreadAsserter { private @Nullable Thread mThread = null; diff --git a/ReactAndroid/src/main/java/com/facebook/react/common/StandardCharsets.java b/ReactAndroid/src/main/java/com/facebook/react/common/StandardCharsets.java index 8246db9dc95..d433f45c335 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/common/StandardCharsets.java +++ b/ReactAndroid/src/main/java/com/facebook/react/common/StandardCharsets.java @@ -1,36 +1,27 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ package com.facebook.react.common; import java.nio.charset.Charset; /** - * Not all versions of Android SDK have this class in nio package. - * This is the reason to have it around. + * Not all versions of Android SDK have this class in nio package. This is the reason to have it + * around. */ public class StandardCharsets { - /** - * Eight-bit UCS Transformation Format - */ + /** Eight-bit UCS Transformation Format */ public static final Charset UTF_8 = Charset.forName("UTF-8"); - /** - * Sixteen-bit UCS Transformation Format, byte order identified by an - * optional byte-order mark - */ + /** Sixteen-bit UCS Transformation Format, byte order identified by an optional byte-order mark */ public static final Charset UTF_16 = Charset.forName("UTF-16"); - /** - * Sixteen-bit UCS Transformation Format, big-endian byte order - */ + /** Sixteen-bit UCS Transformation Format, big-endian byte order */ public static final Charset UTF_16BE = Charset.forName("UTF-16BE"); - /** - * Sixteen-bit UCS Transformation Format, little-endian byte order - */ + /** Sixteen-bit UCS Transformation Format, little-endian byte order */ public static final Charset UTF_16LE = Charset.forName("UTF-16LE"); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/common/SystemClock.java b/ReactAndroid/src/main/java/com/facebook/react/common/SystemClock.java index ce7cc73baf6..c57803fe617 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/common/SystemClock.java +++ b/ReactAndroid/src/main/java/com/facebook/react/common/SystemClock.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.common; /** @@ -24,5 +23,4 @@ public class SystemClock { public static long uptimeMillis() { return android.os.SystemClock.uptimeMillis(); } - } diff --git a/ReactAndroid/src/main/java/com/facebook/react/common/annotations/VisibleForTesting.java b/ReactAndroid/src/main/java/com/facebook/react/common/annotations/VisibleForTesting.java index 5a8cb0e98fd..44d598d0830 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/common/annotations/VisibleForTesting.java +++ b/ReactAndroid/src/main/java/com/facebook/react/common/annotations/VisibleForTesting.java @@ -1,15 +1,13 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.common.annotations; /** * Annotates a method that should have restricted visibility but it's required to be public for use * in test code only. */ -public @interface VisibleForTesting { -} +public @interface VisibleForTesting {} diff --git a/ReactAndroid/src/main/java/com/facebook/react/common/build/ReactBuildConfig.java b/ReactAndroid/src/main/java/com/facebook/react/common/build/ReactBuildConfig.java index f2ea5a6a4b0..d5c02cfffa0 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/common/build/ReactBuildConfig.java +++ b/ReactAndroid/src/main/java/com/facebook/react/common/build/ReactBuildConfig.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.common.build; import com.facebook.react.BuildConfig; diff --git a/ReactAndroid/src/main/java/com/facebook/react/common/futures/SimpleSettableFuture.java b/ReactAndroid/src/main/java/com/facebook/react/common/futures/SimpleSettableFuture.java index d220e2efe41..2e86489fc58 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/common/futures/SimpleSettableFuture.java +++ b/ReactAndroid/src/main/java/com/facebook/react/common/futures/SimpleSettableFuture.java @@ -1,19 +1,17 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.common.futures; -import javax.annotation.Nullable; - import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; +import javax.annotation.Nullable; /** * A super simple Future-like class that can safely notify another Thread when a value is ready. @@ -73,12 +71,12 @@ public class SimpleSettableFuture implements Future { * Wait up to the timeout time for another Thread to set a value on this future. If a value has * already been set, this method will return immediately. * - * NB: For simplicity, we catch and wrap InterruptedException. Do NOT use this class if you - * are in the 1% of cases where you actually want to handle that. + *

NB: For simplicity, we catch and wrap InterruptedException. Do NOT use this class if you are + * in the 1% of cases where you actually want to handle that. */ @Override - public @Nullable T get(long timeout, TimeUnit unit) throws - InterruptedException, ExecutionException, TimeoutException { + public @Nullable T get(long timeout, TimeUnit unit) + throws InterruptedException, ExecutionException, TimeoutException { if (!mReadyLatch.await(timeout, unit)) { throw new TimeoutException("Timed out waiting for result"); } @@ -90,8 +88,7 @@ public class SimpleSettableFuture implements Future { } /** - * Convenience wrapper for {@link #get()} that re-throws get()'s Exceptions as - * RuntimeExceptions. + * Convenience wrapper for {@link #get()} that re-throws get()'s Exceptions as RuntimeExceptions. */ public @Nullable T getOrThrow() { try { diff --git a/ReactAndroid/src/main/java/com/facebook/react/common/network/OkHttpCallUtil.java b/ReactAndroid/src/main/java/com/facebook/react/common/network/OkHttpCallUtil.java index 82d24461ad1..9b2a3b51e30 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/common/network/OkHttpCallUtil.java +++ b/ReactAndroid/src/main/java/com/facebook/react/common/network/OkHttpCallUtil.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.common.network; import okhttp3.Call; @@ -15,8 +14,7 @@ import okhttp3.OkHttpClient; */ public class OkHttpCallUtil { - private OkHttpCallUtil() { - } + private OkHttpCallUtil() {} public static void cancelTag(OkHttpClient client, Object tag) { for (Call call : client.dispatcher().queuedCalls()) { diff --git a/ReactAndroid/src/main/java/com/facebook/react/config/ReactFeatureFlags.java b/ReactAndroid/src/main/java/com/facebook/react/config/ReactFeatureFlags.java index 5c95fbb4d7d..4fd59de5c28 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/config/ReactFeatureFlags.java +++ b/ReactAndroid/src/main/java/com/facebook/react/config/ReactFeatureFlags.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.config; /** @@ -12,35 +11,29 @@ package com.facebook.react.config; * contains mainly flags for features that are either under active development and not ready for * public consumption, or for use in experiments. * - * These values are safe defaults and should not require manual changes. + *

These values are safe defaults and should not require manual changes. */ public class ReactFeatureFlags { - /** - * Whether we should load a specific view manager immediately or when it is accessed by JS - */ + /** Whether we should load a specific view manager immediately or when it is accessed by JS */ public static boolean lazilyLoadViewManagers = false; - /** - * Reduce the number of Java-JS interops while accessing native arrays - */ + /** Reduce the number of Java-JS interops while accessing native arrays */ public static boolean useArrayNativeAccessor = false; - /** - * Reduce the number of Java-JS interops while accessing native maps - */ + /** Reduce the number of Java-JS interops while accessing native maps */ public static boolean useMapNativeAccessor = false; /** - * Should this application use TurboModules. If yes, then any module that inherits - * {@link com.facebook.react.turbomodule.core.interfaces.TurboModule} will NOT be passed in to - * C++ CatalystInstanceImpl + * Should this application use TurboModules. If yes, then any module that inherits {@link + * com.facebook.react.turbomodule.core.interfaces.TurboModule} will NOT be passed in to C++ + * CatalystInstanceImpl */ public static boolean useTurboModules = false; /** - * Log tags of when a view deleted on the native side - * {@link com.facebook.react.uimanager.NativeViewHierarchyManager dropView} + * Log tags of when a view deleted on the native side {@link + * com.facebook.react.uimanager.NativeViewHierarchyManager dropView} */ public static boolean logDroppedViews = false; diff --git a/ReactAndroid/src/main/java/com/facebook/react/devsupport/BundleDeltaClient.java b/ReactAndroid/src/main/java/com/facebook/react/devsupport/BundleDeltaClient.java index dcac48b1725..be3baa037b8 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/devsupport/BundleDeltaClient.java +++ b/ReactAndroid/src/main/java/com/facebook/react/devsupport/BundleDeltaClient.java @@ -1,25 +1,21 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.devsupport; +import android.util.JsonReader; +import android.util.Pair; +import com.facebook.react.bridge.NativeDeltaClient; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.TreeMap; import javax.annotation.Nullable; - -import android.util.JsonReader; -import android.util.JsonToken; -import android.util.Pair; -import com.facebook.react.bridge.NativeDeltaClient; import okhttp3.Headers; -import okio.Buffer; import okio.BufferedSource; public abstract class BundleDeltaClient { @@ -48,13 +44,12 @@ public abstract class BundleDeltaClient { return null; } - abstract public boolean canHandle(ClientType type); + public abstract boolean canHandle(ClientType type); - abstract protected Pair processDelta( - BufferedSource body, - File outputFile) throws IOException; + protected abstract Pair processDelta( + BufferedSource body, File outputFile) throws IOException; - final public synchronized String extendUrlForDelta(String bundleURL) { + public final synchronized String extendUrlForDelta(String bundleURL) { return mRevisionId != null ? bundleURL + "&revisionId=" + mRevisionId : bundleURL; } @@ -63,9 +58,7 @@ public abstract class BundleDeltaClient { } public synchronized Pair processDelta( - Headers headers, - BufferedSource body, - File outputFile) throws IOException { + Headers headers, BufferedSource body, File outputFile) throws IOException { mRevisionId = headers.get(METRO_DELTA_ID_HEADER); return processDelta(body, outputFile); @@ -91,8 +84,7 @@ public abstract class BundleDeltaClient { @Override public synchronized Pair processDelta( - BufferedSource body, - File outputFile) throws IOException { + BufferedSource body, File outputFile) throws IOException { JsonReader jsonReader = new JsonReader(new InputStreamReader(body.inputStream())); jsonReader.beginObject(); int numChangedModules = 0; @@ -147,7 +139,7 @@ public abstract class BundleDeltaClient { } private static int setModules(JsonReader jsonReader, TreeMap map) - throws IOException { + throws IOException { jsonReader.beginArray(); int numModules = 0; @@ -168,7 +160,7 @@ public abstract class BundleDeltaClient { } private static int removeModules(JsonReader jsonReader, TreeMap map) - throws IOException { + throws IOException { jsonReader.beginArray(); int numModules = 0; @@ -195,9 +187,8 @@ public abstract class BundleDeltaClient { } @Override - protected Pair processDelta( - BufferedSource body, - File outputFile) throws IOException { + protected Pair processDelta(BufferedSource body, File outputFile) + throws IOException { nativeClient.processDelta(body); return Pair.create(Boolean.FALSE, nativeClient); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/devsupport/BundleDownloader.java b/ReactAndroid/src/main/java/com/facebook/react/devsupport/BundleDownloader.java index e7a6fdb0cff..dbc1678c9ab 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/devsupport/BundleDownloader.java +++ b/ReactAndroid/src/main/java/com/facebook/react/devsupport/BundleDownloader.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.devsupport; import android.util.Log; @@ -145,10 +144,8 @@ public class BundleDownloader { String url = call.request().url().toString(); callback.onFailure( - DebugServerException.makeGeneric(url, - "Could not connect to development server.", - "URL: " + url, - e)); + DebugServerException.makeGeneric( + url, "Could not connect to development server.", "URL: " + url, e)); } @Override @@ -169,19 +166,19 @@ public class BundleDownloader { try (Response r = response) { if (match.find()) { processMultipartResponse( - url, r, match.group(1), outputFile, bundleInfo, clientType, callback); + url, r, match.group(1), outputFile, bundleInfo, clientType, callback); } else { // In case the server doesn't support multipart/mixed responses, fallback to normal // download. processBundleResult( - url, - r.code(), - r.headers(), - Okio.buffer(r.body().source()), - outputFile, - bundleInfo, - clientType, - callback); + url, + r.code(), + r.headers(), + Okio.buffer(r.body().source()), + outputFile, + bundleInfo, + clientType, + callback); } } } @@ -189,9 +186,11 @@ public class BundleDownloader { } private String formatBundleUrl(String bundleURL, BundleDeltaClient.ClientType clientType) { - return BundleDeltaClient.isDeltaUrl(bundleURL) && mBundleDeltaClient != null && mBundleDeltaClient.canHandle(clientType) - ? mBundleDeltaClient.extendUrlForDelta(bundleURL) - : bundleURL; + return BundleDeltaClient.isDeltaUrl(bundleURL) + && mBundleDeltaClient != null + && mBundleDeltaClient.canHandle(clientType) + ? mBundleDeltaClient.extendUrlForDelta(bundleURL) + : bundleURL; } private void processMultipartResponse( @@ -224,7 +223,14 @@ public class BundleDownloader { status = Integer.parseInt(headers.get("X-Http-Status")); } processBundleResult( - url, status, Headers.of(headers), body, outputFile, bundleInfo, clientType, callback); + url, + status, + Headers.of(headers), + body, + outputFile, + bundleInfo, + clientType, + callback); } else { if (!headers.containsKey("Content-Type") || !headers.get("Content-Type").equals("application/json")) { @@ -291,10 +297,14 @@ public class BundleDownloader { callback.onFailure(debugServerException); } else { StringBuilder sb = new StringBuilder(); - sb.append("The development server returned response error code: ").append(statusCode).append("\n\n") - .append("URL: ").append(url).append("\n\n") - .append("Body:\n") - .append(bodyString); + sb.append("The development server returned response error code: ") + .append(statusCode) + .append("\n\n") + .append("URL: ") + .append(url) + .append("\n\n") + .append("Body:\n") + .append(bodyString); callback.onFailure(new DebugServerException(sb.toString())); } return; @@ -353,8 +363,10 @@ public class BundleDownloader { return true; } - private static void populateBundleInfo(String url, Headers headers, BundleDeltaClient.ClientType clientType, BundleInfo bundleInfo) { - bundleInfo.mDeltaClientName = clientType == BundleDeltaClient.ClientType.NONE ? null : clientType.name(); + private static void populateBundleInfo( + String url, Headers headers, BundleDeltaClient.ClientType clientType, BundleInfo bundleInfo) { + bundleInfo.mDeltaClientName = + clientType == BundleDeltaClient.ClientType.NONE ? null : clientType.name(); bundleInfo.mUrl = url; String filesChangedCountStr = headers.get("X-Metro-Files-Changed-Count"); diff --git a/ReactAndroid/src/main/java/com/facebook/react/devsupport/DebugOverlayController.java b/ReactAndroid/src/main/java/com/facebook/react/devsupport/DebugOverlayController.java index 9eb96e58100..653a2fb8736 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/devsupport/DebugOverlayController.java +++ b/ReactAndroid/src/main/java/com/facebook/react/devsupport/DebugOverlayController.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.devsupport; import android.Manifest; @@ -18,17 +17,15 @@ import android.os.Build; import android.provider.Settings; import android.view.WindowManager; import android.widget.FrameLayout; - import com.facebook.common.logging.FLog; import com.facebook.react.bridge.ReactContext; import com.facebook.react.bridge.UiThreadUtil; import com.facebook.react.common.ReactConstants; - import javax.annotation.Nullable; /** - * Helper class for controlling overlay view with FPS and JS FPS info - * that gets added directly to @{link WindowManager} instance. + * Helper class for controlling overlay view with FPS and JS FPS info that gets added directly + * to @{link WindowManager} instance. */ /* package */ class DebugOverlayController { @@ -36,11 +33,14 @@ import javax.annotation.Nullable; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // Get permission to show debug overlay in dev builds. if (!Settings.canDrawOverlays(context)) { - Intent intent = new Intent( + Intent intent = + new Intent( Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + context.getPackageName())); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - FLog.w(ReactConstants.TAG, "Overlay permissions needs to be granted in order for react native apps to run in dev mode"); + FLog.w( + ReactConstants.TAG, + "Overlay permissions needs to be granted in order for react native apps to run in dev mode"); if (canHandleIntent(context, intent)) { context.startActivity(intent); } @@ -64,9 +64,10 @@ import javax.annotation.Nullable; private static boolean hasPermission(Context context, String permission) { try { - PackageInfo info = context.getPackageManager().getPackageInfo( - context.getPackageName(), - PackageManager.GET_PERMISSIONS); + PackageInfo info = + context + .getPackageManager() + .getPackageInfo(context.getPackageName(), PackageManager.GET_PERMISSIONS); if (info.requestedPermissions != null) { for (String p : info.requestedPermissions) { if (p.equals(permission)) { @@ -96,29 +97,31 @@ import javax.annotation.Nullable; } public void setFpsDebugViewVisible(final boolean fpsDebugViewVisible) { - UiThreadUtil.runOnUiThread(new Runnable() { - @Override - public void run() { - if (fpsDebugViewVisible && mFPSDebugViewContainer == null) { - if (!permissionCheck(mReactContext)) { - FLog.d(ReactConstants.TAG, "Wait for overlay permission to be set"); - return; + UiThreadUtil.runOnUiThread( + new Runnable() { + @Override + public void run() { + if (fpsDebugViewVisible && mFPSDebugViewContainer == null) { + if (!permissionCheck(mReactContext)) { + FLog.d(ReactConstants.TAG, "Wait for overlay permission to be set"); + return; + } + mFPSDebugViewContainer = new FpsView(mReactContext); + WindowManager.LayoutParams params = + new WindowManager.LayoutParams( + WindowManager.LayoutParams.MATCH_PARENT, + WindowManager.LayoutParams.MATCH_PARENT, + WindowOverlayCompat.TYPE_SYSTEM_OVERLAY, + WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE + | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE, + PixelFormat.TRANSLUCENT); + mWindowManager.addView(mFPSDebugViewContainer, params); + } else if (!fpsDebugViewVisible && mFPSDebugViewContainer != null) { + mFPSDebugViewContainer.removeAllViews(); + mWindowManager.removeView(mFPSDebugViewContainer); + mFPSDebugViewContainer = null; + } } - mFPSDebugViewContainer = new FpsView(mReactContext); - WindowManager.LayoutParams params = new WindowManager.LayoutParams( - WindowManager.LayoutParams.MATCH_PARENT, - WindowManager.LayoutParams.MATCH_PARENT, - WindowOverlayCompat.TYPE_SYSTEM_OVERLAY, - WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE - | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE, - PixelFormat.TRANSLUCENT); - mWindowManager.addView(mFPSDebugViewContainer, params); - } else if (!fpsDebugViewVisible && mFPSDebugViewContainer != null) { - mFPSDebugViewContainer.removeAllViews(); - mWindowManager.removeView(mFPSDebugViewContainer); - mFPSDebugViewContainer = null; - } - } - }); + }); } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/devsupport/DevInternalSettings.java b/ReactAndroid/src/main/java/com/facebook/react/devsupport/DevInternalSettings.java index 8777b64dac7..9474e2396d4 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/devsupport/DevInternalSettings.java +++ b/ReactAndroid/src/main/java/com/facebook/react/devsupport/DevInternalSettings.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.devsupport; import android.annotation.SuppressLint; @@ -22,9 +21,8 @@ import com.facebook.react.packagerconnection.PackagerConnectionSettings; * this class implements an external interface {@link DeveloperSettings}. */ @VisibleForTesting -public class DevInternalSettings implements - DeveloperSettings, - SharedPreferences.OnSharedPreferenceChangeListener { +public class DevInternalSettings + implements DeveloperSettings, SharedPreferences.OnSharedPreferenceChangeListener { private static final String PREFS_FPS_DEBUG_KEY = "fps_debug"; private static final String PREFS_JS_DEV_MODE_DEBUG_KEY = "js_dev_mode_debug"; @@ -45,21 +43,16 @@ public class DevInternalSettings implements private final boolean mSupportsNativeDeltaClients; public static DevInternalSettings withoutNativeDeltaClient( - Context applicationContext, - Listener listener) { + Context applicationContext, Listener listener) { return new DevInternalSettings(applicationContext, listener, false); } - public DevInternalSettings( - Context applicationContext, - Listener listener) { + public DevInternalSettings(Context applicationContext, Listener listener) { this(applicationContext, listener, true); } private DevInternalSettings( - Context applicationContext, - Listener listener, - boolean supportsNativeDeltaClients) { + Context applicationContext, Listener listener, boolean supportsNativeDeltaClients) { mListener = listener; mPreferences = PreferenceManager.getDefaultSharedPreferences(applicationContext); mPreferences.registerOnSharedPreferenceChangeListener(this); @@ -148,7 +141,8 @@ public class DevInternalSettings implements @SuppressLint("SharedPreferencesUse") public boolean isBundleDeltasCppEnabled() { - return mSupportsNativeDeltaClients && mPreferences.getBoolean(PREFS_JS_BUNDLE_DELTAS_CPP_KEY, false); + return mSupportsNativeDeltaClients + && mPreferences.getBoolean(PREFS_JS_BUNDLE_DELTAS_CPP_KEY, false); } @SuppressLint("SharedPreferencesUse") diff --git a/ReactAndroid/src/main/java/com/facebook/react/devsupport/DevLoadingViewController.java b/ReactAndroid/src/main/java/com/facebook/react/devsupport/DevLoadingViewController.java index 36b6eb07ec8..06a09d49516 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/devsupport/DevLoadingViewController.java +++ b/ReactAndroid/src/main/java/com/facebook/react/devsupport/DevLoadingViewController.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.devsupport; import static android.view.ViewGroup.LayoutParams.MATCH_PARENT; @@ -26,9 +25,7 @@ import java.net.URL; import java.util.Locale; import javax.annotation.Nullable; -/** - * Controller to display loading messages on top of the screen. All methods are thread safe. - */ +/** Controller to display loading messages on top of the screen. All methods are thread safe. */ public class DevLoadingViewController { private static boolean sEnabled = true; private final ReactInstanceManagerDevHelper mReactInstanceManagerHelper; @@ -39,7 +36,8 @@ public class DevLoadingViewController { sEnabled = enabled; } - public DevLoadingViewController(Context context, ReactInstanceManagerDevHelper reactInstanceManagerHelper) { + public DevLoadingViewController( + Context context, ReactInstanceManagerDevHelper reactInstanceManagerHelper) { mReactInstanceManagerHelper = reactInstanceManagerHelper; } @@ -48,12 +46,13 @@ public class DevLoadingViewController { return; } - UiThreadUtil.runOnUiThread(new Runnable() { - @Override - public void run() { - showInternal(message); - } - }); + UiThreadUtil.runOnUiThread( + new Runnable() { + @Override + public void run() { + showInternal(message); + } + }); } public void showForUrl(String url) { @@ -71,8 +70,8 @@ public class DevLoadingViewController { } showMessage( - context.getString(R.string.catalyst_loading_from_url, - parsedURL.getHost() + ":" + parsedURL.getPort())); + context.getString( + R.string.catalyst_loading_from_url, parsedURL.getHost() + ":" + parsedURL.getPort())); } public void showForRemoteJSEnabled() { @@ -84,25 +83,33 @@ public class DevLoadingViewController { showMessage(context.getString(R.string.catalyst_debug_connecting)); } - public void updateProgress(final @Nullable String status, final @Nullable Integer done, final @Nullable Integer total) { + public void updateProgress( + final @Nullable String status, final @Nullable Integer done, final @Nullable Integer total) { if (!sEnabled) { return; } - UiThreadUtil.runOnUiThread(new Runnable() { - @Override - public void run() { - StringBuilder message = new StringBuilder(); - message.append(status != null ? status : "Loading"); - if (done != null && total != null && total > 0) { - message.append(String.format(Locale.getDefault(), " %.1f%% (%d/%d)", (float) done / total * 100, done, total)); - } - message.append("\u2026"); // `...` character - if (mDevLoadingView != null) { - mDevLoadingView.setText(message); - } - } - }); + UiThreadUtil.runOnUiThread( + new Runnable() { + @Override + public void run() { + StringBuilder message = new StringBuilder(); + message.append(status != null ? status : "Loading"); + if (done != null && total != null && total > 0) { + message.append( + String.format( + Locale.getDefault(), + " %.1f%% (%d/%d)", + (float) done / total * 100, + done, + total)); + } + message.append("\u2026"); // `...` character + if (mDevLoadingView != null) { + mDevLoadingView.setText(message); + } + } + }); } public void hide() { @@ -110,12 +117,13 @@ public class DevLoadingViewController { return; } - UiThreadUtil.runOnUiThread(new Runnable() { - @Override - public void run() { - hideInternal(); - } - }); + UiThreadUtil.runOnUiThread( + new Runnable() { + @Override + public void run() { + hideInternal(); + } + }); } private void showInternal(String message) { @@ -126,8 +134,9 @@ public class DevLoadingViewController { Activity currentActivity = mReactInstanceManagerHelper.getCurrentActivity(); if (currentActivity == null) { - FLog.e(ReactConstants.TAG, "Unable to display loading message because react " + - "activity isn't available"); + FLog.e( + ReactConstants.TAG, + "Unable to display loading message because react " + "activity isn't available"); return; } @@ -139,7 +148,7 @@ public class DevLoadingViewController { int topOffset = rectangle.top; LayoutInflater inflater = - (LayoutInflater) currentActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + (LayoutInflater) currentActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); mDevLoadingView = (TextView) inflater.inflate(R.layout.dev_loading_view, null); mDevLoadingView.setText(message); @@ -148,10 +157,7 @@ public class DevLoadingViewController { mDevLoadingPopup.setTouchable(false); mDevLoadingPopup.showAtLocation( - currentActivity.getWindow().getDecorView(), - Gravity.NO_GRAVITY, - 0, - topOffset); + currentActivity.getWindow().getDecorView(), Gravity.NO_GRAVITY, 0, topOffset); } private void hideInternal() { diff --git a/ReactAndroid/src/main/java/com/facebook/react/devsupport/DevServerHelper.java b/ReactAndroid/src/main/java/com/facebook/react/devsupport/DevServerHelper.java index deaffe8ed5b..883d467545d 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/devsupport/DevServerHelper.java +++ b/ReactAndroid/src/main/java/com/facebook/react/devsupport/DevServerHelper.java @@ -1,14 +1,12 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.devsupport; import android.content.Context; -import android.content.res.Resources; import android.os.AsyncTask; import android.os.Handler; import android.os.Looper; @@ -56,11 +54,11 @@ import org.json.JSONObject; /** * Helper class for all things about the debug server running in the engineer's host machine. * - * One can use 'debug_http_host' shared preferences key to provide a host name for the debug server. - * If the setting is empty we support and detect two basic configuration that works well for android - * emulators connection to debug server running on emulator's host: - * - Android stock emulator with standard non-configurable local loopback alias: 10.0.2.2, - * - Genymotion emulator with default settings: 10.0.3.2 + *

One can use 'debug_http_host' shared preferences key to provide a host name for the debug + * server. If the setting is empty we support and detect two basic configuration that works well for + * android emulators connection to debug server running on emulator's host: - Android stock emulator + * with standard non-configurable local loopback alias: 10.0.2.2, - Genymotion emulator with default + * settings: 10.0.3.2 */ public class DevServerHelper { public static final String RELOAD_APP_EXTRA_JS_PROXY = "jsproxy"; @@ -79,18 +77,21 @@ public class DevServerHelper { public interface PackagerCommandListener { void onPackagerConnected(); + void onPackagerDisconnected(); + void onPackagerReloadCommand(); + void onPackagerDevMenuCommand(); + void onCaptureHeapCommand(final Responder responder); // Allow apps to provide listeners for custom packager commands. - @Nullable Map customCommandHandlers(); + @Nullable + Map customCommandHandlers(); } - public interface PackagerCustomCommandProvider { - - } + public interface PackagerCustomCommandProvider {} public interface SymbolicationListener { void onSymbolicationComplete(@Nullable Iterable stackFrames); @@ -126,17 +127,17 @@ public class DevServerHelper { private InspectorPackagerConnection.BundleStatusProvider mBundlerStatusProvider; public DevServerHelper( - DevInternalSettings settings, - String packageName, - InspectorPackagerConnection.BundleStatusProvider bundleStatusProvider - ) { + DevInternalSettings settings, + String packageName, + InspectorPackagerConnection.BundleStatusProvider bundleStatusProvider) { mSettings = settings; mBundlerStatusProvider = bundleStatusProvider; - mClient = new OkHttpClient.Builder() - .connectTimeout(HTTP_CONNECT_TIMEOUT_MS, TimeUnit.MILLISECONDS) - .readTimeout(0, TimeUnit.MILLISECONDS) - .writeTimeout(0, TimeUnit.MILLISECONDS) - .build(); + mClient = + new OkHttpClient.Builder() + .connectTimeout(HTTP_CONNECT_TIMEOUT_MS, TimeUnit.MILLISECONDS) + .readTimeout(0, TimeUnit.MILLISECONDS) + .writeTimeout(0, TimeUnit.MILLISECONDS) + .build(); mBundleDownloader = new BundleDownloader(mClient); mRestartOnChangePollingHandler = new Handler(Looper.getMainLooper()); @@ -153,24 +154,30 @@ public class DevServerHelper { @Override protected Void doInBackground(Void... backgroundParams) { Map handlers = new HashMap<>(); - handlers.put("reload", new NotificationOnlyHandler() { - @Override - public void onNotification(@Nullable Object params) { - commandListener.onPackagerReloadCommand(); - } - }); - handlers.put("devMenu", new NotificationOnlyHandler() { - @Override - public void onNotification(@Nullable Object params) { - commandListener.onPackagerDevMenuCommand(); - } - }); - handlers.put("captureHeap", new RequestOnlyHandler() { - @Override - public void onRequest(@Nullable Object params, Responder responder) { - commandListener.onCaptureHeapCommand(responder); - } - }); + handlers.put( + "reload", + new NotificationOnlyHandler() { + @Override + public void onNotification(@Nullable Object params) { + commandListener.onPackagerReloadCommand(); + } + }); + handlers.put( + "devMenu", + new NotificationOnlyHandler() { + @Override + public void onNotification(@Nullable Object params) { + commandListener.onPackagerDevMenuCommand(); + } + }); + handlers.put( + "captureHeap", + new RequestOnlyHandler() { + @Override + public void onRequest(@Nullable Object params, Responder responder) { + commandListener.onCaptureHeapCommand(responder); + } + }); Map customHandlers = commandListener.customCommandHandlers(); if (customHandlers != null) { handlers.putAll(customHandlers); @@ -178,7 +185,7 @@ public class DevServerHelper { handlers.putAll(new FileIoHandler().handlers()); ConnectionCallback onPackagerConnectedCallback = - new ConnectionCallback() { + new ConnectionCallback() { @Override public void onConnected() { commandListener.onPackagerConnected(); @@ -190,11 +197,12 @@ public class DevServerHelper { } }; - mPackagerClient = new JSPackagerClient( - clientId, - mSettings.getPackagerConnectionSettings(), - handlers, - onPackagerConnectedCallback); + mPackagerClient = + new JSPackagerClient( + clientId, + mSettings.getPackagerConnectionSettings(), + handlers, + onPackagerConnectedCallback); mPackagerClient.init(); return null; @@ -223,11 +231,9 @@ public class DevServerHelper { new AsyncTask() { @Override protected Void doInBackground(Void... params) { - mInspectorPackagerConnection = new InspectorPackagerConnection( - getInspectorDeviceUrl(), - mPackageName, - mBundlerStatusProvider - ); + mInspectorPackagerConnection = + new InspectorPackagerConnection( + getInspectorDeviceUrl(), mPackageName, mBundlerStatusProvider); mInspectorPackagerConnection.connect(); return null; } @@ -284,42 +290,45 @@ public class DevServerHelper { } public void symbolicateStackTrace( - Iterable stackFrames, - final SymbolicationListener listener) { + Iterable stackFrames, final SymbolicationListener listener) { try { - final String symbolicateURL = createSymbolicateURL( - mSettings.getPackagerConnectionSettings().getDebugServerHost()); + final String symbolicateURL = + createSymbolicateURL(mSettings.getPackagerConnectionSettings().getDebugServerHost()); final JSONArray jsonStackFrames = new JSONArray(); for (final StackFrame stackFrame : stackFrames) { jsonStackFrames.put(stackFrame.toJSON()); } - final Request request = new Request.Builder() - .url(symbolicateURL) - .post(RequestBody.create( - MediaType.parse("application/json"), - new JSONObject().put("stack", jsonStackFrames).toString())) - .build(); + final Request request = + new Request.Builder() + .url(symbolicateURL) + .post( + RequestBody.create( + MediaType.parse("application/json"), + new JSONObject().put("stack", jsonStackFrames).toString())) + .build(); Call symbolicateCall = Assertions.assertNotNull(mClient.newCall(request)); - symbolicateCall.enqueue(new Callback() { - @Override - public void onFailure(Call call, IOException e) { - FLog.w( - ReactConstants.TAG, - "Got IOException when attempting symbolicate stack trace: " + e.getMessage()); - listener.onSymbolicationComplete(null); - } + symbolicateCall.enqueue( + new Callback() { + @Override + public void onFailure(Call call, IOException e) { + FLog.w( + ReactConstants.TAG, + "Got IOException when attempting symbolicate stack trace: " + e.getMessage()); + listener.onSymbolicationComplete(null); + } - @Override - public void onResponse(Call call, final Response response) throws IOException { - try { - listener.onSymbolicationComplete(Arrays.asList( - StackTraceHelper.convertJsStackTrace(new JSONObject( - response.body().string()).getJSONArray("stack")))); - } catch (JSONException exception) { - listener.onSymbolicationComplete(null); - } - } - }); + @Override + public void onResponse(Call call, final Response response) throws IOException { + try { + listener.onSymbolicationComplete( + Arrays.asList( + StackTraceHelper.convertJsStackTrace( + new JSONObject(response.body().string()).getJSONArray("stack")))); + } catch (JSONException exception) { + listener.onSymbolicationComplete(null); + } + } + }); } catch (JSONException e) { FLog.w( ReactConstants.TAG, @@ -328,28 +337,30 @@ public class DevServerHelper { } public void openStackFrameCall(StackFrame stackFrame) { - final String openStackFrameURL = createOpenStackFrameURL( - mSettings.getPackagerConnectionSettings().getDebugServerHost()); - final Request request = new Request.Builder() - .url(openStackFrameURL) - .post(RequestBody.create( - MediaType.parse("application/json"), - stackFrame.toJSON().toString())) - .build(); + final String openStackFrameURL = + createOpenStackFrameURL(mSettings.getPackagerConnectionSettings().getDebugServerHost()); + final Request request = + new Request.Builder() + .url(openStackFrameURL) + .post( + RequestBody.create( + MediaType.parse("application/json"), stackFrame.toJSON().toString())) + .build(); Call symbolicateCall = Assertions.assertNotNull(mClient.newCall(request)); - symbolicateCall.enqueue(new Callback() { - @Override - public void onFailure(Call call, IOException e) { - FLog.w( - ReactConstants.TAG, - "Got IOException when attempting to open stack frame: " + e.getMessage()); - } + symbolicateCall.enqueue( + new Callback() { + @Override + public void onFailure(Call call, IOException e) { + FLog.w( + ReactConstants.TAG, + "Got IOException when attempting to open stack frame: " + e.getMessage()); + } - @Override - public void onResponse(Call call, final Response response) throws IOException { - // We don't have a listener for this. - } - }); + @Override + public void onResponse(Call call, final Response response) throws IOException { + // We don't have a listener for this. + } + }); } public String getWebsocketProxyURL() { @@ -379,9 +390,12 @@ public class DevServerHelper { } public void downloadBundleFromURL( - DevBundleDownloadListener callback, - File outputFile, String bundleURL, BundleDownloader.BundleInfo bundleInfo) { - mBundleDownloader.downloadBundleFromURL(callback, outputFile, bundleURL, bundleInfo, getDeltaClientType()); + DevBundleDownloadListener callback, + File outputFile, + String bundleURL, + BundleDownloader.BundleInfo bundleInfo) { + mBundleDownloader.downloadBundleFromURL( + callback, outputFile, bundleURL, bundleInfo, getDeltaClientType()); } public void downloadBundleFromURL( @@ -404,13 +418,11 @@ public class DevServerHelper { } } - /** - * @return the host to use when connecting to the bundle server from the host itself. - */ + /** @return the host to use when connecting to the bundle server from the host itself. */ private String getHostForJSProxy() { // Use custom port if configured. Note that host stays "localhost". - String host = Assertions.assertNotNull( - mSettings.getPackagerConnectionSettings().getDebugServerHost()); + String host = + Assertions.assertNotNull(mSettings.getPackagerConnectionSettings().getDebugServerHost()); int portOffset = host.lastIndexOf(':'); if (portOffset > -1) { return "localhost" + host.substring(portOffset); @@ -419,16 +431,12 @@ public class DevServerHelper { } } - /** - * @return whether we should enable dev mode when requesting JS bundles. - */ + /** @return whether we should enable dev mode when requesting JS bundles. */ private boolean getDevMode() { return mSettings.isJSDevModeEnabled(); } - /** - * @return whether we should request minified JS bundles. - */ + /** @return whether we should request minified JS bundles. */ private boolean getJSMinifyMode() { return mSettings.isJSMinifyEnabled(); } @@ -463,59 +471,62 @@ public class DevServerHelper { public String getDevServerBundleURL(final String jsModulePath) { return createBundleURL( - jsModulePath, - mSettings.isBundleDeltasEnabled() ? BundleType.DELTA : BundleType.BUNDLE, - mSettings.getPackagerConnectionSettings().getDebugServerHost() - ); + jsModulePath, + mSettings.isBundleDeltasEnabled() ? BundleType.DELTA : BundleType.BUNDLE, + mSettings.getPackagerConnectionSettings().getDebugServerHost()); } public void isPackagerRunning(final PackagerStatusCallback callback) { - String statusURL = createPackagerStatusURL( - mSettings.getPackagerConnectionSettings().getDebugServerHost()); - Request request = new Request.Builder() - .url(statusURL) - .build(); + String statusURL = + createPackagerStatusURL(mSettings.getPackagerConnectionSettings().getDebugServerHost()); + Request request = new Request.Builder().url(statusURL).build(); - mClient.newCall(request).enqueue( - new Callback() { - @Override - public void onFailure(Call call, IOException e) { - FLog.w( - ReactConstants.TAG, - "The packager does not seem to be running as we got an IOException requesting " + - "its status: " + e.getMessage()); - callback.onPackagerStatusFetched(false); - } + mClient + .newCall(request) + .enqueue( + new Callback() { + @Override + public void onFailure(Call call, IOException e) { + FLog.w( + ReactConstants.TAG, + "The packager does not seem to be running as we got an IOException requesting " + + "its status: " + + e.getMessage()); + callback.onPackagerStatusFetched(false); + } - @Override - public void onResponse(Call call, Response response) throws IOException { - if (!response.isSuccessful()) { - FLog.e( - ReactConstants.TAG, - "Got non-success http code from packager when requesting status: " + - response.code()); - callback.onPackagerStatusFetched(false); - return; - } - ResponseBody body = response.body(); - if (body == null) { - FLog.e( - ReactConstants.TAG, - "Got null body response from packager when requesting status"); - callback.onPackagerStatusFetched(false); - return; - } - String bodyString = body.string(); // cannot call body.string() twice, stored it into variable. https://github.com/square/okhttp/issues/1240#issuecomment-68142603 - if (!PACKAGER_OK_STATUS.equals(bodyString)) { - FLog.e( - ReactConstants.TAG, - "Got unexpected response from packager when requesting status: " + bodyString); - callback.onPackagerStatusFetched(false); - return; - } - callback.onPackagerStatusFetched(true); - } - }); + @Override + public void onResponse(Call call, Response response) throws IOException { + if (!response.isSuccessful()) { + FLog.e( + ReactConstants.TAG, + "Got non-success http code from packager when requesting status: " + + response.code()); + callback.onPackagerStatusFetched(false); + return; + } + ResponseBody body = response.body(); + if (body == null) { + FLog.e( + ReactConstants.TAG, + "Got null body response from packager when requesting status"); + callback.onPackagerStatusFetched(false); + return; + } + String bodyString = + body.string(); // cannot call body.string() twice, stored it into variable. + // https://github.com/square/okhttp/issues/1240#issuecomment-68142603 + if (!PACKAGER_OK_STATUS.equals(bodyString)) { + FLog.e( + ReactConstants.TAG, + "Got unexpected response from packager when requesting status: " + + bodyString); + callback.onPackagerStatusFetched(false); + return; + } + callback.onPackagerStatusFetched(true); + } + }); } private static String createPackagerStatusURL(String host) { @@ -540,24 +551,27 @@ public class DevServerHelper { } mOnChangePollingEnabled = true; mOnServerContentChangeListener = onServerContentChangeListener; - mOnChangePollingClient = new OkHttpClient.Builder() - .connectionPool(new ConnectionPool(1, LONG_POLL_KEEP_ALIVE_DURATION_MS, TimeUnit.MILLISECONDS)) - .connectTimeout(HTTP_CONNECT_TIMEOUT_MS, TimeUnit.MILLISECONDS) - .build(); + mOnChangePollingClient = + new OkHttpClient.Builder() + .connectionPool( + new ConnectionPool(1, LONG_POLL_KEEP_ALIVE_DURATION_MS, TimeUnit.MILLISECONDS)) + .connectTimeout(HTTP_CONNECT_TIMEOUT_MS, TimeUnit.MILLISECONDS) + .build(); enqueueOnChangeEndpointLongPolling(); } private void handleOnChangePollingResponse(boolean didServerContentChanged) { if (mOnChangePollingEnabled) { if (didServerContentChanged) { - UiThreadUtil.runOnUiThread(new Runnable() { - @Override - public void run() { - if (mOnServerContentChangeListener != null) { - mOnServerContentChangeListener.onServerContentChanged(); - } - } - }); + UiThreadUtil.runOnUiThread( + new Runnable() { + @Override + public void run() { + if (mOnServerContentChangeListener != null) { + mOnServerContentChangeListener.onServerContentChanged(); + } + } + }); } enqueueOnChangeEndpointLongPolling(); } @@ -565,30 +579,35 @@ public class DevServerHelper { private void enqueueOnChangeEndpointLongPolling() { Request request = new Request.Builder().url(createOnChangeEndpointUrl()).tag(this).build(); - Assertions.assertNotNull(mOnChangePollingClient).newCall(request).enqueue(new Callback() { - @Override - public void onFailure(Call call, IOException e) { - if (mOnChangePollingEnabled) { - // this runnable is used by onchange endpoint poller to delay subsequent requests in case - // of a failure, so that we don't flood network queue with frequent requests in case when - // dev server is down - FLog.d(ReactConstants.TAG, "Error while requesting /onchange endpoint", e); - mRestartOnChangePollingHandler.postDelayed( - new Runnable() { - @Override - public void run() { - handleOnChangePollingResponse(false); - } - }, - LONG_POLL_FAILURE_DELAY_MS); - } - } + Assertions.assertNotNull(mOnChangePollingClient) + .newCall(request) + .enqueue( + new Callback() { + @Override + public void onFailure(Call call, IOException e) { + if (mOnChangePollingEnabled) { + // this runnable is used by onchange endpoint poller to delay subsequent requests + // in case + // of a failure, so that we don't flood network queue with frequent requests in + // case when + // dev server is down + FLog.d(ReactConstants.TAG, "Error while requesting /onchange endpoint", e); + mRestartOnChangePollingHandler.postDelayed( + new Runnable() { + @Override + public void run() { + handleOnChangePollingResponse(false); + } + }, + LONG_POLL_FAILURE_DELAY_MS); + } + } - @Override - public void onResponse(Call call, Response response) throws IOException { - handleOnChangePollingResponse(response.code() == 205); - } - }); + @Override + public void onResponse(Call call, Response response) throws IOException { + handleOnChangePollingResponse(response.code() == 205); + } + }); } private String createOnChangeEndpointUrl() { @@ -606,21 +625,23 @@ public class DevServerHelper { } public void launchJSDevtools() { - Request request = new Request.Builder() - .url(createLaunchJSDevtoolsCommandUrl()) - .build(); - mClient.newCall(request).enqueue(new Callback() { - @Override - public void onFailure(Call call, IOException e) { - // ignore HTTP call response, this is just to open a debugger page and there is no reason - // to report failures from here - } + Request request = new Request.Builder().url(createLaunchJSDevtoolsCommandUrl()).build(); + mClient + .newCall(request) + .enqueue( + new Callback() { + @Override + public void onFailure(Call call, IOException e) { + // ignore HTTP call response, this is just to open a debugger page and there is no + // reason + // to report failures from here + } - @Override - public void onResponse(Call call, Response response) throws IOException { - // ignore HTTP call response - see above - } - }); + @Override + public void onResponse(Call call, Response response) throws IOException { + // ignore HTTP call response - see above + } + }); } public String getSourceMapUrl(String mainModuleName) { @@ -636,25 +657,21 @@ public class DevServerHelper { // The host we use when connecting to the JS bundle server from the emulator is not the // same as the one needed to connect to the same server from the JavaScript proxy running on the // host itself. - return createBundleURL( - mainModuleName, BundleType.BUNDLE, getHostForJSProxy()); + return createBundleURL(mainModuleName, BundleType.BUNDLE, getHostForJSProxy()); } /** - * This is a debug-only utility to allow fetching a file via packager. - * It's made synchronous for simplicity, but should only be used if it's absolutely - * necessary. + * This is a debug-only utility to allow fetching a file via packager. It's made synchronous for + * simplicity, but should only be used if it's absolutely necessary. + * * @return the file with the fetched content, or null if there's any failure. */ public @Nullable File downloadBundleResourceFromUrlSync( - final String resourcePath, - final File outputFile) { - final String resourceURL = createResourceURL( - mSettings.getPackagerConnectionSettings().getDebugServerHost(), - resourcePath); - final Request request = new Request.Builder() - .url(resourceURL) - .build(); + final String resourcePath, final File outputFile) { + final String resourceURL = + createResourceURL( + mSettings.getPackagerConnectionSettings().getDebugServerHost(), resourcePath); + final Request request = new Request.Builder().url(resourceURL).build(); try (Response response = mClient.newCall(request).execute()) { if (!response.isSuccessful()) { diff --git a/ReactAndroid/src/main/java/com/facebook/react/devsupport/DevSettingsActivity.java b/ReactAndroid/src/main/java/com/facebook/react/devsupport/DevSettingsActivity.java index cc5ee193cda..79274eb306d 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/devsupport/DevSettingsActivity.java +++ b/ReactAndroid/src/main/java/com/facebook/react/devsupport/DevSettingsActivity.java @@ -1,17 +1,14 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.devsupport; import android.os.Bundle; import android.preference.PreferenceActivity; - import com.facebook.react.R; -import com.facebook.react.common.DebugServerException; /** * Activity that display developers settings. Should be added to the debug manifest of the app. Can diff --git a/ReactAndroid/src/main/java/com/facebook/react/devsupport/DevSupportManagerFactory.java b/ReactAndroid/src/main/java/com/facebook/react/devsupport/DevSupportManagerFactory.java index 6f808d0b93c..c0d40285bec 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/devsupport/DevSupportManagerFactory.java +++ b/ReactAndroid/src/main/java/com/facebook/react/devsupport/DevSupportManagerFactory.java @@ -1,28 +1,24 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.devsupport; import android.content.Context; - import com.facebook.react.devsupport.interfaces.DevBundleDownloadListener; import com.facebook.react.devsupport.interfaces.DevSupportManager; import com.facebook.react.packagerconnection.RequestHandler; - import java.lang.reflect.Constructor; import java.util.Map; - import javax.annotation.Nullable; /** * A simple factory that creates instances of {@link DevSupportManager} implementations. Uses * reflection to create DevSupportManagerImpl if it exists. This allows ProGuard to strip that class - * and its dependencies in release builds. If the class isn't found, - * {@link DisabledDevSupportManager} is returned instead. + * and its dependencies in release builds. If the class isn't found, {@link + * DisabledDevSupportManager} is returned instead. */ public class DevSupportManagerFactory { @@ -37,25 +33,25 @@ public class DevSupportManagerFactory { int minNumShakes) { return create( - applicationContext, - reactInstanceManagerHelper, - packagerPathForJSBundleName, - enableOnCreate, - null, - null, - minNumShakes, - null); + applicationContext, + reactInstanceManagerHelper, + packagerPathForJSBundleName, + enableOnCreate, + null, + null, + minNumShakes, + null); } public static DevSupportManager create( - Context applicationContext, - ReactInstanceManagerDevHelper reactInstanceManagerHelper, - @Nullable String packagerPathForJSBundleName, - boolean enableOnCreate, - @Nullable RedBoxHandler redBoxHandler, - @Nullable DevBundleDownloadListener devBundleDownloadListener, - int minNumShakes, - @Nullable Map customPackagerCommandHandlers) { + Context applicationContext, + ReactInstanceManagerDevHelper reactInstanceManagerHelper, + @Nullable String packagerPathForJSBundleName, + boolean enableOnCreate, + @Nullable RedBoxHandler redBoxHandler, + @Nullable DevBundleDownloadListener devBundleDownloadListener, + int minNumShakes, + @Nullable Map customPackagerCommandHandlers) { if (!enableOnCreate) { return new DisabledDevSupportManager(); } @@ -64,36 +60,36 @@ public class DevSupportManagerFactory { // Class.forName() with a static string. So instead we generate a quasi-dynamic string to // confuse it. String className = - new StringBuilder(DEVSUPPORT_IMPL_PACKAGE) - .append(".") - .append(DEVSUPPORT_IMPL_CLASS) - .toString(); - Class devSupportManagerClass = - Class.forName(className); + new StringBuilder(DEVSUPPORT_IMPL_PACKAGE) + .append(".") + .append(DEVSUPPORT_IMPL_CLASS) + .toString(); + Class devSupportManagerClass = Class.forName(className); Constructor constructor = - devSupportManagerClass.getConstructor( - Context.class, - ReactInstanceManagerDevHelper.class, - String.class, - boolean.class, - RedBoxHandler.class, - DevBundleDownloadListener.class, - int.class, - Map.class); - return (DevSupportManager) constructor.newInstance( - applicationContext, - reactInstanceManagerHelper, - packagerPathForJSBundleName, - true, - redBoxHandler, - devBundleDownloadListener, - minNumShakes, - customPackagerCommandHandlers); + devSupportManagerClass.getConstructor( + Context.class, + ReactInstanceManagerDevHelper.class, + String.class, + boolean.class, + RedBoxHandler.class, + DevBundleDownloadListener.class, + int.class, + Map.class); + return (DevSupportManager) + constructor.newInstance( + applicationContext, + reactInstanceManagerHelper, + packagerPathForJSBundleName, + true, + redBoxHandler, + devBundleDownloadListener, + minNumShakes, + customPackagerCommandHandlers); } catch (Exception e) { throw new RuntimeException( - "Requested enabled DevSupportManager, but DevSupportManagerImpl class was not found" + - " or could not be created", - e); + "Requested enabled DevSupportManager, but DevSupportManagerImpl class was not found" + + " or could not be created", + e); } } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/devsupport/DevSupportManagerImpl.java b/ReactAndroid/src/main/java/com/facebook/react/devsupport/DevSupportManagerImpl.java index 4808a9bd3ef..4ac47639b70 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/devsupport/DevSupportManagerImpl.java +++ b/ReactAndroid/src/main/java/com/facebook/react/devsupport/DevSupportManagerImpl.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.devsupport; import android.app.Activity; @@ -18,11 +17,9 @@ import android.content.IntentFilter; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.hardware.SensorManager; -import android.net.Uri; -import android.os.AsyncTask; -import androidx.annotation.Nullable; import android.util.Pair; import android.widget.Toast; +import androidx.annotation.Nullable; import com.facebook.common.logging.FLog; import com.facebook.debug.holder.PrinterHolder; import com.facebook.debug.tags.ReactDebugOverlayTags; @@ -63,10 +60,6 @@ import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; -import okhttp3.MediaType; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; /** * Interface for accessing and interacting with development features. Following features @@ -94,10 +87,8 @@ import okhttp3.RequestBody; * {@code } * {@code } */ -public class DevSupportManagerImpl implements - DevSupportManager, - PackagerCommandListener, - DevInternalSettings.Listener { +public class DevSupportManagerImpl + implements DevSupportManager, PackagerCommandListener, DevInternalSettings.Listener { private static final int JAVA_ERROR_COOKIE = -1; private static final int JSEXCEPTION_ERROR_COOKIE = -1; @@ -109,8 +100,8 @@ public class DevSupportManagerImpl implements NATIVE } - private static final String EXOPACKAGE_LOCATION_FORMAT - = "/data/local/tmp/exopackage/%s//secondary-dex"; + private static final String EXOPACKAGE_LOCATION_FORMAT = + "/data/local/tmp/exopackage/%s//secondary-dex"; public static final String EMOJI_HUNDRED_POINTS_SYMBOL = " \uD83D\uDCAF"; public static final String EMOJI_FACE_WITH_NO_GOOD_GESTURE = " \uD83D\uDE45"; @@ -121,8 +112,7 @@ public class DevSupportManagerImpl implements private final ShakeDetector mShakeDetector; private final BroadcastReceiver mReloadAppBroadcastReceiver; private final DevServerHelper mDevServerHelper; - private final LinkedHashMap mCustomDevOptions = - new LinkedHashMap<>(); + private final LinkedHashMap mCustomDevOptions = new LinkedHashMap<>(); private final ReactInstanceManagerDevHelper mReactInstanceManagerHelper; private final @Nullable String mJSAppBundleName; private final File mJSBundleTempFile; @@ -151,20 +141,21 @@ public class DevSupportManagerImpl implements private @Nullable Map mCustomPackagerCommandHandlers; public DevSupportManagerImpl( - Context applicationContext, - ReactInstanceManagerDevHelper reactInstanceManagerHelper, - @Nullable String packagerPathForJSBundleName, - boolean enableOnCreate, - int minNumShakes) { + Context applicationContext, + ReactInstanceManagerDevHelper reactInstanceManagerHelper, + @Nullable String packagerPathForJSBundleName, + boolean enableOnCreate, + int minNumShakes) { - this(applicationContext, - reactInstanceManagerHelper, - packagerPathForJSBundleName, - enableOnCreate, - null, - null, - minNumShakes, - null); + this( + applicationContext, + reactInstanceManagerHelper, + packagerPathForJSBundleName, + enableOnCreate, + null, + null, + minNumShakes, + null); } public DevSupportManagerImpl( @@ -181,44 +172,48 @@ public class DevSupportManagerImpl implements mJSAppBundleName = packagerPathForJSBundleName; mDevSettings = new DevInternalSettings(applicationContext, this); mBundleStatus = new InspectorPackagerConnection.BundleStatus(); - mDevServerHelper = new DevServerHelper( - mDevSettings, - mApplicationContext.getPackageName(), - new InspectorPackagerConnection.BundleStatusProvider() { - @Override - public InspectorPackagerConnection.BundleStatus getBundleStatus() { - return mBundleStatus; - } - } - ); + mDevServerHelper = + new DevServerHelper( + mDevSettings, + mApplicationContext.getPackageName(), + new InspectorPackagerConnection.BundleStatusProvider() { + @Override + public InspectorPackagerConnection.BundleStatus getBundleStatus() { + return mBundleStatus; + } + }); mBundleDownloadListener = devBundleDownloadListener; // Prepare shake gesture detector (will be started/stopped from #reload) - mShakeDetector = new ShakeDetector(new ShakeDetector.ShakeListener() { - @Override - public void onShake() { - showDevOptionsDialog(); - } - }, minNumShakes); + mShakeDetector = + new ShakeDetector( + new ShakeDetector.ShakeListener() { + @Override + public void onShake() { + showDevOptionsDialog(); + } + }, + minNumShakes); mCustomPackagerCommandHandlers = customPackagerCommandHandlers; // Prepare reload APP broadcast receiver (will be registered/unregistered from #reload) - mReloadAppBroadcastReceiver = new BroadcastReceiver() { - @Override - public void onReceive(Context context, Intent intent) { - String action = intent.getAction(); - if (getReloadAppAction(context).equals(action)) { - if (intent.getBooleanExtra(DevServerHelper.RELOAD_APP_EXTRA_JS_PROXY, false)) { - mDevSettings.setRemoteJSDebugEnabled(true); - mDevServerHelper.launchJSDevtools(); - } else { - mDevSettings.setRemoteJSDebugEnabled(false); + mReloadAppBroadcastReceiver = + new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + String action = intent.getAction(); + if (getReloadAppAction(context).equals(action)) { + if (intent.getBooleanExtra(DevServerHelper.RELOAD_APP_EXTRA_JS_PROXY, false)) { + mDevSettings.setRemoteJSDebugEnabled(true); + mDevServerHelper.launchJSDevtools(); + } else { + mDevSettings.setRemoteJSDebugEnabled(false); + } + handleReloadJS(); + } } - handleReloadJS(); - } - } - }; + }; // We store JS bundle loaded from dev server in a single destination in app's data dir. // In case when someone schedule 2 subsequent reloads it may happen that JS thread will @@ -233,7 +228,7 @@ public class DevSupportManagerImpl implements mRedBoxHandler = redBoxHandler; mDevLoadingViewController = - new DevLoadingViewController(applicationContext, reactInstanceManagerHelper); + new DevLoadingViewController(applicationContext, reactInstanceManagerHelper); mExceptionLoggers.add(new JSExceptionLogger()); } @@ -259,7 +254,9 @@ public class DevSupportManagerImpl implements @Override public void log(Exception e) { - StringBuilder message = new StringBuilder(e.getMessage() == null ? "Exception in native call from JS" : e.getMessage()); + StringBuilder message = + new StringBuilder( + e.getMessage() == null ? "Exception in native call from JS" : e.getMessage()); Throwable cause = e.getCause(); while (cause != null) { message.append("\n\n").append(cause.getMessage()); @@ -273,10 +270,7 @@ public class DevSupportManagerImpl implements // TODO #11638796: convert the stack into something useful showNewError( - message.toString(), - new StackFrame[]{}, - JSEXCEPTION_ERROR_COOKIE, - ErrorType.JS); + message.toString(), new StackFrame[] {}, JSEXCEPTION_ERROR_COOKIE, ErrorType.JS); } else { showNewJavaError(message.toString(), e); } @@ -286,7 +280,8 @@ public class DevSupportManagerImpl implements @Override public void showNewJavaError(@Nullable String message, Throwable e) { FLog.e(ReactConstants.TAG, "Exception in native call", e); - showNewError(message, StackTraceHelper.convertJavaStackTrace(e), JAVA_ERROR_COOKIE, ErrorType.NATIVE); + showNewError( + message, StackTraceHelper.convertJavaStackTrace(e), JAVA_ERROR_COOKIE, ErrorType.NATIVE); } /** @@ -295,9 +290,7 @@ public class DevSupportManagerImpl implements * called. */ @Override - public void addCustomDevOption( - String optionName, - DevOptionHandler optionHandler) { + public void addCustomDevOption(String optionName, DevOptionHandler optionHandler) { mCustomDevOptions.put(optionName, optionHandler); } @@ -307,15 +300,14 @@ public class DevSupportManagerImpl implements } @Override - public void registerErrorCustomizer(ErrorCustomizer errorCustomizer){ - if (mErrorCustomizers == null){ + public void registerErrorCustomizer(ErrorCustomizer errorCustomizer) { + if (mErrorCustomizers == null) { mErrorCustomizers = new ArrayList<>(); } mErrorCustomizers.add(errorCustomizer); } - private Pair processErrorCustomizers( - Pair errorInfo) { + private Pair processErrorCustomizers(Pair errorInfo) { if (mErrorCustomizers == null) { return errorInfo; } else { @@ -331,34 +323,32 @@ public class DevSupportManagerImpl implements @Override public void updateJSError( - final String message, - final ReadableArray details, - final int errorCookie) { + final String message, final ReadableArray details, final int errorCookie) { UiThreadUtil.runOnUiThread( - new Runnable() { - @Override - public void run() { - // Since we only show the first JS error in a succession of JS errors, make sure we only - // update the error message for that error message. This assumes that updateJSError - // belongs to the most recent showNewJSError - if (mRedBoxDialog == null || - !mRedBoxDialog.isShowing() || - errorCookie != mLastErrorCookie) { - return; + new Runnable() { + @Override + public void run() { + // Since we only show the first JS error in a succession of JS errors, make sure we only + // update the error message for that error message. This assumes that updateJSError + // belongs to the most recent showNewJSError + if (mRedBoxDialog == null + || !mRedBoxDialog.isShowing() + || errorCookie != mLastErrorCookie) { + return; + } + StackFrame[] stack = StackTraceHelper.convertJsStackTrace(details); + Pair errorInfo = + processErrorCustomizers(Pair.create(message, stack)); + mRedBoxDialog.setExceptionDetails(errorInfo.first, errorInfo.second); + updateLastErrorInfo(message, stack, errorCookie, ErrorType.JS); + // JS errors are reported here after source mapping. + if (mRedBoxHandler != null) { + mRedBoxHandler.handleRedbox(message, stack, RedBoxHandler.ErrorType.JS); + mRedBoxDialog.resetReporting(); + } + mRedBoxDialog.show(); } - StackFrame[] stack = StackTraceHelper.convertJsStackTrace(details); - Pair errorInfo = - processErrorCustomizers(Pair.create(message, stack)); - mRedBoxDialog.setExceptionDetails(errorInfo.first, errorInfo.second); - updateLastErrorInfo(message, stack, errorCookie, ErrorType.JS); - // JS errors are reported here after source mapping. - if (mRedBoxHandler != null) { - mRedBoxHandler.handleRedbox(message, stack, RedBoxHandler.ErrorType.JS); - mRedBoxDialog.resetReporting(); - } - mRedBoxDialog.show(); - } - }); + }); } @Override @@ -389,8 +379,11 @@ public class DevSupportManagerImpl implements if (mRedBoxDialog == null) { Activity context = mReactInstanceManagerHelper.getCurrentActivity(); if (context == null || context.isFinishing()) { - FLog.e(ReactConstants.TAG, "Unable to launch redbox because react activity " + - "is not available, here is the error that redbox would've displayed: " + message); + FLog.e( + ReactConstants.TAG, + "Unable to launch redbox because react activity " + + "is not available, here is the error that redbox would've displayed: " + + message); return; } mRedBoxDialog = new RedBoxDialog(context, DevSupportManagerImpl.this, mRedBoxHandler); @@ -400,7 +393,8 @@ public class DevSupportManagerImpl implements // show the first and most actionable one. return; } - Pair errorInfo = processErrorCustomizers(Pair.create(message, stack)); + Pair errorInfo = + processErrorCustomizers(Pair.create(message, stack)); mRedBoxDialog.setExceptionDetails(errorInfo.first, errorInfo.second); updateLastErrorInfo(message, stack, errorCookie, errorType); // Only report native errors here. JS errors are reported @@ -422,44 +416,46 @@ public class DevSupportManagerImpl implements LinkedHashMap options = new LinkedHashMap<>(); /* register standard options */ options.put( - mApplicationContext.getString(R.string.catalyst_reload), - new DevOptionHandler() { - @Override - public void onOptionSelected() { - if (!mDevSettings.isJSDevModeEnabled() && mDevSettings.isHotModuleReplacementEnabled()) { - Toast.makeText( - mApplicationContext, - mApplicationContext.getString(R.string.catalyst_hot_reloading_auto_disable), - Toast.LENGTH_LONG).show(); - mDevSettings.setHotModuleReplacementEnabled(false); - } - handleReloadJS(); - } - }); - options.put( - mDevSettings.isNuclideJSDebugEnabled() - ? mDevSettings.isRemoteJSDebugEnabled() - ? mApplicationContext.getString(R.string.catalyst_debug_chrome_stop) - : mApplicationContext.getString(R.string.catalyst_debug_chrome) - : mDevSettings.isRemoteJSDebugEnabled() - ? mApplicationContext.getString(R.string.catalyst_debug_stop) - : mApplicationContext.getString(R.string.catalyst_debug), - new DevOptionHandler() { - @Override - public void onOptionSelected() { - mDevSettings.setRemoteJSDebugEnabled(!mDevSettings.isRemoteJSDebugEnabled()); - handleReloadJS(); - } - }); - if (mDevSettings.isNuclideJSDebugEnabled()) { - options.put( - mApplicationContext.getString(R.string.catalyst_debug_nuclide), + mApplicationContext.getString(R.string.catalyst_reload), new DevOptionHandler() { @Override public void onOptionSelected() { - mDevServerHelper.attachDebugger(mApplicationContext, "ReactNative"); + if (!mDevSettings.isJSDevModeEnabled() + && mDevSettings.isHotModuleReplacementEnabled()) { + Toast.makeText( + mApplicationContext, + mApplicationContext.getString(R.string.catalyst_hot_reloading_auto_disable), + Toast.LENGTH_LONG) + .show(); + mDevSettings.setHotModuleReplacementEnabled(false); + } + handleReloadJS(); } }); + options.put( + mDevSettings.isNuclideJSDebugEnabled() + ? mDevSettings.isRemoteJSDebugEnabled() + ? mApplicationContext.getString(R.string.catalyst_debug_chrome_stop) + : mApplicationContext.getString(R.string.catalyst_debug_chrome) + : mDevSettings.isRemoteJSDebugEnabled() + ? mApplicationContext.getString(R.string.catalyst_debug_stop) + : mApplicationContext.getString(R.string.catalyst_debug), + new DevOptionHandler() { + @Override + public void onOptionSelected() { + mDevSettings.setRemoteJSDebugEnabled(!mDevSettings.isRemoteJSDebugEnabled()); + handleReloadJS(); + } + }); + if (mDevSettings.isNuclideJSDebugEnabled()) { + options.put( + mApplicationContext.getString(R.string.catalyst_debug_nuclide), + new DevOptionHandler() { + @Override + public void onOptionSelected() { + mDevServerHelper.attachDebugger(mApplicationContext, "ReactNative"); + } + }); } options.put( // NOTE: `isElementInspectorEnabled` is not guaranteed to be accurate. @@ -485,52 +481,54 @@ public class DevSupportManagerImpl implements // See D15958697 for more context. options.put( - mDevSettings.isHotModuleReplacementEnabled() - ? mApplicationContext.getString(R.string.catalyst_hot_reloading_stop) - : mApplicationContext.getString(R.string.catalyst_hot_reloading), - new DevOptionHandler() { - @Override - public void onOptionSelected() { - boolean nextEnabled = !mDevSettings.isHotModuleReplacementEnabled(); - mDevSettings.setHotModuleReplacementEnabled(nextEnabled); - if (mCurrentContext != null) { - if (nextEnabled) { - mCurrentContext.getJSModule(HMRClient.class).enable(); - } else { - mCurrentContext.getJSModule(HMRClient.class).disable(); + mDevSettings.isHotModuleReplacementEnabled() + ? mApplicationContext.getString(R.string.catalyst_hot_reloading_stop) + : mApplicationContext.getString(R.string.catalyst_hot_reloading), + new DevOptionHandler() { + @Override + public void onOptionSelected() { + boolean nextEnabled = !mDevSettings.isHotModuleReplacementEnabled(); + mDevSettings.setHotModuleReplacementEnabled(nextEnabled); + if (mCurrentContext != null) { + if (nextEnabled) { + mCurrentContext.getJSModule(HMRClient.class).enable(); + } else { + mCurrentContext.getJSModule(HMRClient.class).disable(); + } + } + if (nextEnabled && !mDevSettings.isJSDevModeEnabled()) { + Toast.makeText( + mApplicationContext, + mApplicationContext.getString(R.string.catalyst_hot_reloading_auto_enable), + Toast.LENGTH_LONG) + .show(); + mDevSettings.setJSDevModeEnabled(true); + handleReloadJS(); } } - if (nextEnabled && !mDevSettings.isJSDevModeEnabled()) { - Toast.makeText( - mApplicationContext, - mApplicationContext.getString(R.string.catalyst_hot_reloading_auto_enable), - Toast.LENGTH_LONG).show(); - mDevSettings.setJSDevModeEnabled(true); - handleReloadJS(); - } - } - }); + }); options.put( - mDevSettings.isFpsDebugEnabled() - ? mApplicationContext.getString(R.string.catalyst_perf_monitor_stop) - : mApplicationContext.getString(R.string.catalyst_perf_monitor), - new DevOptionHandler() { - @Override - public void onOptionSelected() { - if (!mDevSettings.isFpsDebugEnabled()) { - // Request overlay permission if needed when "Show Perf Monitor" option is selected - Context context = mReactInstanceManagerHelper.getCurrentActivity(); - if (context == null) { - FLog.e(ReactConstants.TAG, "Unable to get reference to react activity"); - } else { - DebugOverlayController.requestPermission(context); + mDevSettings.isFpsDebugEnabled() + ? mApplicationContext.getString(R.string.catalyst_perf_monitor_stop) + : mApplicationContext.getString(R.string.catalyst_perf_monitor), + new DevOptionHandler() { + @Override + public void onOptionSelected() { + if (!mDevSettings.isFpsDebugEnabled()) { + // Request overlay permission if needed when "Show Perf Monitor" option is selected + Context context = mReactInstanceManagerHelper.getCurrentActivity(); + if (context == null) { + FLog.e(ReactConstants.TAG, "Unable to get reference to react activity"); + } else { + DebugOverlayController.requestPermission(context); + } } + mDevSettings.setFpsDebugEnabled(!mDevSettings.isFpsDebugEnabled()); } - mDevSettings.setFpsDebugEnabled(!mDevSettings.isFpsDebugEnabled()); - } - }); + }); options.put( - mApplicationContext.getString(R.string.catalyst_settings), new DevOptionHandler() { + mApplicationContext.getString(R.string.catalyst_settings), + new DevOptionHandler() { @Override public void onOptionSelected() { Intent intent = new Intent(mApplicationContext, DevSettingsActivity.class); @@ -547,8 +545,9 @@ public class DevSupportManagerImpl implements Activity context = mReactInstanceManagerHelper.getCurrentActivity(); if (context == null || context.isFinishing()) { - FLog.e(ReactConstants.TAG, "Unable to launch dev options menu because react activity " + - "isn't available"); + FLog.e( + ReactConstants.TAG, + "Unable to launch dev options menu because react activity " + "isn't available"); return; } mDevOptionsDialog = @@ -562,20 +561,21 @@ public class DevSupportManagerImpl implements mDevOptionsDialog = null; } }) - .setOnCancelListener(new DialogInterface.OnCancelListener() { - @Override - public void onCancel(DialogInterface dialog) { - mDevOptionsDialog = null; - } - }) + .setOnCancelListener( + new DialogInterface.OnCancelListener() { + @Override + public void onCancel(DialogInterface dialog) { + mDevOptionsDialog = null; + } + }) .create(); mDevOptionsDialog.show(); } /** - * {@link ReactInstanceDevCommandsHandler} is responsible for - * enabling/disabling dev support when a React view is attached/detached - * or when application state changes (e.g. the application is backgrounded). + * {@link ReactInstanceDevCommandsHandler} is responsible for enabling/disabling dev support when + * a React view is attached/detached or when application state changes (e.g. the application is + * backgrounded). */ @Override public void setDevSupportEnabled(boolean isDevSupportEnabled) { @@ -637,23 +637,23 @@ public class DevSupportManagerImpl implements } /** - * @return {@code true} if {@link com.facebook.react.ReactInstanceManager} should use downloaded JS bundle file - * instead of using JS file from assets. This may happen when app has not been updated since - * the last time we fetched the bundle. + * @return {@code true} if {@link com.facebook.react.ReactInstanceManager} should use downloaded + * JS bundle file instead of using JS file from assets. This may happen when app has not been + * updated since the last time we fetched the bundle. */ @Override public boolean hasUpToDateJSBundleInCache() { if (mIsDevSupportEnabled && mJSBundleTempFile.exists()) { try { String packageName = mApplicationContext.getPackageName(); - PackageInfo thisPackage = mApplicationContext.getPackageManager() - .getPackageInfo(packageName, 0); + PackageInfo thisPackage = + mApplicationContext.getPackageManager().getPackageInfo(packageName, 0); if (mJSBundleTempFile.lastModified() > thisPackage.lastUpdateTime) { // Base APK has not been updated since we downloaded JS, but if app is using exopackage // it may only be a single dex that has been updated. We check for exopackage dir update // time in that case. - File exopackageDir = new File( - String.format(Locale.US, EXOPACKAGE_LOCATION_FORMAT, packageName)); + File exopackageDir = + new File(String.format(Locale.US, EXOPACKAGE_LOCATION_FORMAT, packageName)); if (exopackageDir.exists()) { return mJSBundleTempFile.lastModified() > exopackageDir.lastModified(); } @@ -668,9 +668,9 @@ public class DevSupportManagerImpl implements } /** - * @return {@code true} if JS bundle {@param bundleAssetName} exists, in that case - * {@link com.facebook.react.ReactInstanceManager} should use that file from assets instead of - * downloading bundle from dev server + * @return {@code true} if JS bundle {@param bundleAssetName} exists, in that case {@link + * com.facebook.react.ReactInstanceManager} should use that file from assets instead of + * downloading bundle from dev server */ public boolean hasBundleInAssets(String bundleAssetName) { try { @@ -725,16 +725,19 @@ public class DevSupportManagerImpl implements if (UiThreadUtil.isOnUiThread()) { reload(); } else { - UiThreadUtil.runOnUiThread(new Runnable() { - @Override - public void run() { - reload(); - } - }); + UiThreadUtil.runOnUiThread( + new Runnable() { + @Override + public void run() { + reload(); + } + }); } } - public void onInternalSettingsChanged() { reloadSettings(); } + public void onInternalSettingsChanged() { + reloadSettings(); + } @Override public void handleReloadJS() { @@ -758,7 +761,7 @@ public class DevSupportManagerImpl implements PrinterHolder.getPrinter() .logMessage(ReactDebugOverlayTags.RN_CORE, "RNCore: load from Server"); String bundleURL = - mDevServerHelper.getDevServerBundleURL(Assertions.assertNotNull(mJSAppBundleName)); + mDevServerHelper.getDevServerBundleURL(Assertions.assertNotNull(mJSAppBundleName)); reloadJSFromServer(bundleURL); } } @@ -770,8 +773,7 @@ public class DevSupportManagerImpl implements @Override public @Nullable File downloadBundleResourceFromUrlSync( - final String resourceURL, - final File outputFile) { + final String resourceURL, final File outputFile) { return mDevServerHelper.downloadBundleResourceFromUrlSync(resourceURL, outputFile); } @@ -799,32 +801,35 @@ public class DevSupportManagerImpl implements public void onPackagerReloadCommand() { // Disable debugger to resume the JsVM & avoid thread locks while reloading mDevServerHelper.disableDebugger(); - UiThreadUtil.runOnUiThread(new Runnable() { - @Override - public void run() { - handleReloadJS(); - } - }); + UiThreadUtil.runOnUiThread( + new Runnable() { + @Override + public void run() { + handleReloadJS(); + } + }); } @Override public void onPackagerDevMenuCommand() { - UiThreadUtil.runOnUiThread(new Runnable() { - @Override - public void run() { - showDevOptionsDialog(); - } - }); + UiThreadUtil.runOnUiThread( + new Runnable() { + @Override + public void run() { + showDevOptionsDialog(); + } + }); } @Override public void onCaptureHeapCommand(final Responder responder) { - UiThreadUtil.runOnUiThread(new Runnable() { - @Override - public void run() { - handleCaptureHeap(responder); - } - }); + UiThreadUtil.runOnUiThread( + new Runnable() { + @Override + public void run() { + handleCaptureHeap(responder); + } + }); } @Override @@ -838,18 +843,18 @@ public class DevSupportManagerImpl implements } JSCHeapCapture heapCapture = mCurrentContext.getNativeModule(JSCHeapCapture.class); heapCapture.captureHeap( - mApplicationContext.getCacheDir().getPath(), - new JSCHeapCapture.CaptureCallback() { - @Override - public void onSuccess(File capture) { - responder.respond(capture.toString()); - } + mApplicationContext.getCacheDir().getPath(), + new JSCHeapCapture.CaptureCallback() { + @Override + public void onSuccess(File capture) { + responder.respond(capture.toString()); + } - @Override - public void onFailure(JSCHeapCapture.CaptureException error) { - responder.error(error.toString()); - } - }); + @Override + public void onFailure(JSCHeapCapture.CaptureException error) { + responder.error(error.toString()); + } + }); } private void updateLastErrorInfo( @@ -868,25 +873,25 @@ public class DevSupportManagerImpl implements // anyway mDevServerHelper.launchJSDevtools(); - JavaJSExecutor.Factory factory = new JavaJSExecutor.Factory() { - @Override - public JavaJSExecutor create() throws Exception { - WebsocketJavaScriptExecutor executor = new WebsocketJavaScriptExecutor(); - SimpleSettableFuture future = new SimpleSettableFuture<>(); - executor.connect( - mDevServerHelper.getWebsocketProxyURL(), - getExecutorConnectCallback(future)); - // TODO(t9349129) Don't use timeout - try { - future.get(90, TimeUnit.SECONDS); - return executor; - } catch (ExecutionException e) { - throw (Exception) e.getCause(); - } catch (InterruptedException | TimeoutException e) { - throw new RuntimeException(e); - } - } - }; + JavaJSExecutor.Factory factory = + new JavaJSExecutor.Factory() { + @Override + public JavaJSExecutor create() throws Exception { + WebsocketJavaScriptExecutor executor = new WebsocketJavaScriptExecutor(); + SimpleSettableFuture future = new SimpleSettableFuture<>(); + executor.connect( + mDevServerHelper.getWebsocketProxyURL(), getExecutorConnectCallback(future)); + // TODO(t9349129) Don't use timeout + try { + future.get(90, TimeUnit.SECONDS); + return executor; + } catch (ExecutionException e) { + throw (Exception) e.getCause(); + } catch (InterruptedException | TimeoutException e) { + throw new RuntimeException(e); + } + } + }; mReactInstanceManagerHelper.onReloadWithJSDebugger(factory); } @@ -906,8 +911,7 @@ public class DevSupportManagerImpl implements mDevLoadingViewVisible = false; FLog.e(ReactConstants.TAG, "Failed to connect to debugger!", cause); future.setException( - new IOException( - mApplicationContext.getString(R.string.catalyst_debug_error), cause)); + new IOException(mApplicationContext.getString(R.string.catalyst_debug_error), cause)); } }; } @@ -937,14 +941,18 @@ public class DevSupportManagerImpl implements new Runnable() { @Override public void run() { - ReactMarker.logMarker(ReactMarkerConstants.DOWNLOAD_END, bundleInfo.toJSONString()); + ReactMarker.logMarker( + ReactMarkerConstants.DOWNLOAD_END, bundleInfo.toJSONString()); mReactInstanceManagerHelper.onJSBundleLoadedFromServer(nativeDeltaClient); } }); } @Override - public void onProgress(@Nullable final String status, @Nullable final Integer done, @Nullable final Integer total) { + public void onProgress( + @Nullable final String status, + @Nullable final Integer done, + @Nullable final Integer total) { mDevLoadingViewController.updateProgress(status, done, total); if (mBundleDownloadListener != null) { mBundleDownloadListener.onProgress(status, done, total); @@ -971,8 +979,7 @@ public class DevSupportManagerImpl implements showNewJavaError(debugServerException.getMessage(), cause); } else { showNewJavaError( - mApplicationContext.getString(R.string.catalyst_reload_error), - cause); + mApplicationContext.getString(R.string.catalyst_reload_error), cause); } } }); @@ -1002,14 +1009,13 @@ public class DevSupportManagerImpl implements } UiThreadUtil.runOnUiThread( - new Runnable() { - @Override - public void run() { - mDevSettings.setHotModuleReplacementEnabled(isHotModuleReplacementEnabled); - handleReloadJS(); - } - } - ); + new Runnable() { + @Override + public void run() { + mDevSettings.setHotModuleReplacementEnabled(isHotModuleReplacementEnabled); + handleReloadJS(); + } + }); } @Override @@ -1019,14 +1025,13 @@ public class DevSupportManagerImpl implements } UiThreadUtil.runOnUiThread( - new Runnable() { - @Override - public void run() { - mDevSettings.setRemoteJSDebugEnabled(isRemoteJSDebugEnabled); - handleReloadJS(); - } - } - ); + new Runnable() { + @Override + public void run() { + mDevSettings.setRemoteJSDebugEnabled(isRemoteJSDebugEnabled); + handleReloadJS(); + } + }); } @Override @@ -1036,14 +1041,13 @@ public class DevSupportManagerImpl implements } UiThreadUtil.runOnUiThread( - new Runnable() { - @Override - public void run() { - mDevSettings.setReloadOnJSChangeEnabled(isReloadOnJSChangeEnabled); - handleReloadJS(); - } - } - ); + new Runnable() { + @Override + public void run() { + mDevSettings.setReloadOnJSChangeEnabled(isReloadOnJSChangeEnabled); + handleReloadJS(); + } + }); } @Override @@ -1053,13 +1057,12 @@ public class DevSupportManagerImpl implements } UiThreadUtil.runOnUiThread( - new Runnable() { - @Override - public void run() { - mDevSettings.setFpsDebugEnabled(isFpsDebugEnabled); - } - } - ); + new Runnable() { + @Override + public void run() { + mDevSettings.setFpsDebugEnabled(isFpsDebugEnabled); + } + }); } @Override @@ -1069,14 +1072,13 @@ public class DevSupportManagerImpl implements } UiThreadUtil.runOnUiThread( - new Runnable() { - @Override - public void run() { - mDevSettings.setElementInspectorEnabled(!mDevSettings.isElementInspectorEnabled()); - mReactInstanceManagerHelper.toggleElementInspector(); - } - } - ); + new Runnable() { + @Override + public void run() { + mDevSettings.setElementInspectorEnabled(!mDevSettings.isElementInspectorEnabled()); + mReactInstanceManagerHelper.toggleElementInspector(); + } + }); } private void reload() { @@ -1113,11 +1115,11 @@ public class DevSupportManagerImpl implements if (mDevSettings.isReloadOnJSChangeEnabled()) { mDevServerHelper.startPollingOnChangeEndpoint( new DevServerHelper.OnServerContentChangeListener() { - @Override - public void onServerContentChanged() { - handleReloadJS(); - } - }); + @Override + public void onServerContentChanged() { + handleReloadJS(); + } + }); } else { mDevServerHelper.stopPollingOnChangeEndpoint(); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/devsupport/DisabledDevSupportManager.java b/ReactAndroid/src/main/java/com/facebook/react/devsupport/DisabledDevSupportManager.java index f57c32ba8ff..363cf2a9d07 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/devsupport/DisabledDevSupportManager.java +++ b/ReactAndroid/src/main/java/com/facebook/react/devsupport/DisabledDevSupportManager.java @@ -1,25 +1,22 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.devsupport; -import com.facebook.react.devsupport.interfaces.ErrorCustomizer; -import javax.annotation.Nullable; - -import java.io.File; - import com.facebook.react.bridge.DefaultNativeModuleCallExceptionHandler; import com.facebook.react.bridge.ReactContext; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.devsupport.interfaces.DevOptionHandler; import com.facebook.react.devsupport.interfaces.DevSupportManager; +import com.facebook.react.devsupport.interfaces.ErrorCustomizer; import com.facebook.react.devsupport.interfaces.PackagerStatusCallback; import com.facebook.react.devsupport.interfaces.StackFrame; import com.facebook.react.modules.debug.interfaces.DeveloperSettings; +import java.io.File; +import javax.annotation.Nullable; /** * A dummy implementation of {@link DevSupportManager} to be used in production mode where @@ -34,74 +31,46 @@ public class DisabledDevSupportManager implements DevSupportManager { } @Override - public void showNewJavaError(String message, Throwable e) { - - } + public void showNewJavaError(String message, Throwable e) {} @Override - public void addCustomDevOption(String optionName, DevOptionHandler optionHandler) { - - } + public void addCustomDevOption(String optionName, DevOptionHandler optionHandler) {} @Override - public void showNewJSError(String message, ReadableArray details, int errorCookie) { - - } + public void showNewJSError(String message, ReadableArray details, int errorCookie) {} @Override - public void updateJSError(String message, ReadableArray details, int errorCookie) { - - } + public void updateJSError(String message, ReadableArray details, int errorCookie) {} @Override - public void hideRedboxDialog() { - - } + public void hideRedboxDialog() {} @Override - public void showDevOptionsDialog() { - - } + public void showDevOptionsDialog() {} @Override - public void setDevSupportEnabled(boolean isDevSupportEnabled) { - - } + public void setDevSupportEnabled(boolean isDevSupportEnabled) {} @Override - public void startInspector() { - - } + public void startInspector() {} @Override - public void stopInspector() { - - } + public void stopInspector() {} @Override - public void setHotModuleReplacementEnabled(boolean isHotModuleReplacementEnabled) { - - } + public void setHotModuleReplacementEnabled(boolean isHotModuleReplacementEnabled) {} @Override - public void setRemoteJSDebugEnabled(boolean isRemoteJSDebugEnabled) { - - } + public void setRemoteJSDebugEnabled(boolean isRemoteJSDebugEnabled) {} @Override - public void setReloadOnJSChangeEnabled(boolean isReloadOnJSChangeEnabled) { - - } + public void setReloadOnJSChangeEnabled(boolean isReloadOnJSChangeEnabled) {} @Override - public void setFpsDebugEnabled(boolean isFpsDebugEnabled) { - - } + public void setFpsDebugEnabled(boolean isFpsDebugEnabled) {} @Override - public void toggleElementInspector() { - - } + public void toggleElementInspector() {} @Override public boolean getDevSupportEnabled() { @@ -114,14 +83,10 @@ public class DisabledDevSupportManager implements DevSupportManager { } @Override - public void onNewReactContextCreated(ReactContext reactContext) { - - } + public void onNewReactContextCreated(ReactContext reactContext) {} @Override - public void onReactInstanceDestroyed(ReactContext reactContext) { - - } + public void onReactInstanceDestroyed(ReactContext reactContext) {} @Override public String getSourceMapUrl() { @@ -149,29 +114,20 @@ public class DisabledDevSupportManager implements DevSupportManager { } @Override - public void reloadSettings() { - - } + public void reloadSettings() {} @Override - public void handleReloadJS() { - - } + public void handleReloadJS() {} @Override - public void reloadJSFromServer(String bundleURL) { - - } + public void reloadJSFromServer(String bundleURL) {} @Override - public void isPackagerRunning(PackagerStatusCallback callback) { - - } + public void isPackagerRunning(PackagerStatusCallback callback) {} @Override public @Nullable File downloadBundleResourceFromUrlSync( - final String resourceURL, - final File outputFile) { + final String resourceURL, final File outputFile) { return null; } @@ -186,9 +142,7 @@ public class DisabledDevSupportManager implements DevSupportManager { } @Override - public void registerErrorCustomizer(ErrorCustomizer errorCustomizer) { - - } + public void registerErrorCustomizer(ErrorCustomizer errorCustomizer) {} @Override public void handleException(Exception e) { diff --git a/ReactAndroid/src/main/java/com/facebook/react/devsupport/DoubleTapReloadRecognizer.java b/ReactAndroid/src/main/java/com/facebook/react/devsupport/DoubleTapReloadRecognizer.java index ae604d12c9f..2c575fc9f0a 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/devsupport/DoubleTapReloadRecognizer.java +++ b/ReactAndroid/src/main/java/com/facebook/react/devsupport/DoubleTapReloadRecognizer.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.devsupport; import android.os.Handler; @@ -13,8 +12,8 @@ import android.view.View; import android.widget.EditText; /** - * A class allows recognizing double key tap of "R", used to reload JS in - * {@link AbstractReactActivity}, {@link RedBoxDialog} and {@link ReactActivity}. + * A class allows recognizing double key tap of "R", used to reload JS in {@link + * AbstractReactActivity}, {@link RedBoxDialog} and {@link ReactActivity}. */ public class DoubleTapReloadRecognizer { private boolean mDoRefresh = false; @@ -27,14 +26,15 @@ public class DoubleTapReloadRecognizer { return true; } else { mDoRefresh = true; - new Handler().postDelayed( - new Runnable() { - @Override - public void run() { - mDoRefresh = false; - } - }, - DOUBLE_TAP_DELAY); + new Handler() + .postDelayed( + new Runnable() { + @Override + public void run() { + mDoRefresh = false; + } + }, + DOUBLE_TAP_DELAY); } } return false; diff --git a/ReactAndroid/src/main/java/com/facebook/react/devsupport/FpsView.java b/ReactAndroid/src/main/java/com/facebook/react/devsupport/FpsView.java index dff56cee1bb..e328c9db8b7 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/devsupport/FpsView.java +++ b/ReactAndroid/src/main/java/com/facebook/react/devsupport/FpsView.java @@ -1,29 +1,25 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.devsupport; -import java.util.Locale; - import android.widget.FrameLayout; import android.widget.TextView; - import com.facebook.common.logging.FLog; import com.facebook.react.R; import com.facebook.react.bridge.ReactContext; import com.facebook.react.common.ReactConstants; -import com.facebook.react.modules.core.ChoreographerCompat; import com.facebook.react.modules.debug.FpsDebugFrameCallback; +import java.util.Locale; /** * View that automatically monitors and displays the current app frame rate. Also logs the current * FPS to logcat while active. * - * NB: Requires API 16 for use of FpsDebugFrameCallback. + *

NB: Requires API 16 for use of FpsDebugFrameCallback. */ public class FpsView extends FrameLayout { @@ -57,21 +53,21 @@ public class FpsView extends FrameLayout { mFPSMonitorRunnable.stop(); } - private void setCurrentFPS(double currentFPS, double currentJSFPS, int droppedUIFrames, int total4PlusFrameStutters) { - String fpsString = String.format( - Locale.US, - "UI: %.1f fps\n%d dropped so far\n%d stutters (4+) so far\nJS: %.1f fps", - currentFPS, - droppedUIFrames, - total4PlusFrameStutters, - currentJSFPS); + private void setCurrentFPS( + double currentFPS, double currentJSFPS, int droppedUIFrames, int total4PlusFrameStutters) { + String fpsString = + String.format( + Locale.US, + "UI: %.1f fps\n%d dropped so far\n%d stutters (4+) so far\nJS: %.1f fps", + currentFPS, + droppedUIFrames, + total4PlusFrameStutters, + currentJSFPS); mTextView.setText(fpsString); FLog.d(ReactConstants.TAG, fpsString); } - /** - * Timer that runs every UPDATE_INTERVAL_MS ms and updates the currently displayed FPS. - */ + /** Timer that runs every UPDATE_INTERVAL_MS ms and updates the currently displayed FPS. */ private class FPSMonitorRunnable implements Runnable { private boolean mShouldStop = false; @@ -85,7 +81,11 @@ public class FpsView extends FrameLayout { } mTotalFramesDropped += mFrameCallback.getExpectedNumFrames() - mFrameCallback.getNumFrames(); mTotal4PlusFrameStutters += mFrameCallback.get4PlusFrameStutters(); - setCurrentFPS(mFrameCallback.getFPS(), mFrameCallback.getJSFPS(), mTotalFramesDropped, mTotal4PlusFrameStutters); + setCurrentFPS( + mFrameCallback.getFPS(), + mFrameCallback.getJSFPS(), + mTotalFramesDropped, + mTotal4PlusFrameStutters); mFrameCallback.reset(); postDelayed(this, UPDATE_INTERVAL_MS); diff --git a/ReactAndroid/src/main/java/com/facebook/react/devsupport/HMRClient.java b/ReactAndroid/src/main/java/com/facebook/react/devsupport/HMRClient.java index c221dbee89c..f4ec4608a15 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/devsupport/HMRClient.java +++ b/ReactAndroid/src/main/java/com/facebook/react/devsupport/HMRClient.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.devsupport; import com.facebook.react.bridge.JavaScriptModule; @@ -12,15 +11,15 @@ import com.facebook.react.bridge.JavaScriptModule; /** * JS module interface for HMRClient * - * The HMR(Hot Module Replacement)Client allows for the application to receive updates - * from the packager server (over a web socket), allowing for injection of JavaScript to - * the running application (without a refresh). + *

The HMR(Hot Module Replacement)Client allows for the application to receive updates from the + * packager server (over a web socket), allowing for injection of JavaScript to the running + * application (without a refresh). */ public interface HMRClient extends JavaScriptModule { /** - * Enable the HMRClient so that the client will receive updates - * from the packager server. + * Enable the HMRClient so that the client will receive updates from the packager server. + * * @param platform The platform in which HMR updates will be enabled. Should be "android". * @param bundleEntry The path to the bundle entry file (e.g. index.ios.bundle). * @param host The host that the HMRClient should communicate with. @@ -30,13 +29,11 @@ public interface HMRClient extends JavaScriptModule { void setup(String platform, String bundleEntry, String host, int port, boolean isEnabled); /** - * Sets up a connection to the packager when called the first time. - * Ensures code updates received from the packager are applied. + * Sets up a connection to the packager when called the first time. Ensures code updates received + * from the packager are applied. */ void enable(); - /** - * Turns off the HMR client so it doesn't process updates from the packager. - */ + /** Turns off the HMR client so it doesn't process updates from the packager. */ void disable(); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/devsupport/InspectorPackagerConnection.java b/ReactAndroid/src/main/java/com/facebook/react/devsupport/InspectorPackagerConnection.java index 11b99dac873..82b357313c2 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/devsupport/InspectorPackagerConnection.java +++ b/ReactAndroid/src/main/java/com/facebook/react/devsupport/InspectorPackagerConnection.java @@ -5,21 +5,17 @@ package com.facebook.react.devsupport; -import javax.annotation.Nullable; - +import android.os.AsyncTask; +import android.os.Handler; +import android.os.Looper; +import com.facebook.common.logging.FLog; +import com.facebook.react.bridge.Inspector; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; - -import android.os.AsyncTask; -import android.os.Handler; -import android.os.Looper; - -import com.facebook.common.logging.FLog; -import com.facebook.react.bridge.Inspector; - +import javax.annotation.Nullable; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; @@ -38,10 +34,7 @@ public class InspectorPackagerConnection { private BundleStatusProvider mBundleStatusProvider; public InspectorPackagerConnection( - String url, - String packageName, - BundleStatusProvider bundleStatusProvider - ) { + String url, String packageName, BundleStatusProvider bundleStatusProvider) { mConnection = new Connection(url); mInspectorConnections = new HashMap<>(); mPackageName = packageName; @@ -64,8 +57,7 @@ public class InspectorPackagerConnection { } } - void handleProxyMessage(JSONObject message) - throws JSONException, IOException { + void handleProxyMessage(JSONObject message) throws JSONException, IOException { String event = message.getString("event"); switch (event) { case "getPages": @@ -101,26 +93,29 @@ public class InspectorPackagerConnection { try { // TODO: Use strings for id's too - inspectorConnection = Inspector.connect(Integer.parseInt(pageId), new Inspector.RemoteConnection() { - @Override - public void onMessage(String message) { - try { - sendWrappedEvent(pageId, message); - } catch (JSONException e) { - FLog.w(TAG, "Couldn't send event to packager", e); - } - } + inspectorConnection = + Inspector.connect( + Integer.parseInt(pageId), + new Inspector.RemoteConnection() { + @Override + public void onMessage(String message) { + try { + sendWrappedEvent(pageId, message); + } catch (JSONException e) { + FLog.w(TAG, "Couldn't send event to packager", e); + } + } - @Override - public void onDisconnect() { - try { - mInspectorConnections.remove(pageId); - sendEvent("disconnect", makePageIdPayload(pageId)); - } catch (JSONException e) { - FLog.w(TAG, "Couldn't send event to packager", e); - } - } - }); + @Override + public void onDisconnect() { + try { + mInspectorConnections.remove(pageId); + sendEvent("disconnect", makePageIdPayload(pageId)); + } catch (JSONException e) { + FLog.w(TAG, "Couldn't send event to packager", e); + } + } + }); mInspectorConnections.put(pageId, inspectorConnection); } catch (Exception e) { FLog.w(TAG, "Failed to open page: " + pageId, e); @@ -172,8 +167,7 @@ public class InspectorPackagerConnection { sendEvent("wrappedEvent", payload); } - private void sendEvent(String name, Object payload) - throws JSONException { + private void sendEvent(String name, Object payload) throws JSONException { JSONObject jsonMessage = new JSONObject(); jsonMessage.put("event", name); jsonMessage.put("payload", payload); @@ -240,11 +234,12 @@ public class InspectorPackagerConnection { throw new IllegalStateException("Can't connect closed client"); } if (mHttpClient == null) { - mHttpClient = new OkHttpClient.Builder() - .connectTimeout(10, TimeUnit.SECONDS) - .writeTimeout(10, TimeUnit.SECONDS) - .readTimeout(0, TimeUnit.MINUTES) // Disable timeouts for read - .build(); + mHttpClient = + new OkHttpClient.Builder() + .connectTimeout(10, TimeUnit.SECONDS) + .writeTimeout(10, TimeUnit.SECONDS) + .readTimeout(0, TimeUnit.MINUTES) // Disable timeouts for read + .build(); } Request request = new Request.Builder().url(mUrl).build(); @@ -319,14 +314,11 @@ public class InspectorPackagerConnection { } } - static public class BundleStatus { + public static class BundleStatus { public Boolean isLastDownloadSucess; public long updateTimestamp = -1; - public BundleStatus( - Boolean isLastDownloadSucess, - long updateTimestamp - ) { + public BundleStatus(Boolean isLastDownloadSucess, long updateTimestamp) { this.isLastDownloadSucess = isLastDownloadSucess; this.updateTimestamp = updateTimestamp; } diff --git a/ReactAndroid/src/main/java/com/facebook/react/devsupport/JSCHeapCapture.java b/ReactAndroid/src/main/java/com/facebook/react/devsupport/JSCHeapCapture.java index 803ba002dff..e5e46d62d53 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/devsupport/JSCHeapCapture.java +++ b/ReactAndroid/src/main/java/com/facebook/react/devsupport/JSCHeapCapture.java @@ -1,21 +1,18 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.devsupport; -import javax.annotation.Nullable; - -import java.io.File; - import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.module.annotations.ReactModule; +import java.io.File; +import javax.annotation.Nullable; // This module is being called only by Java via the static method "captureHeap" that // requires it to alreay be initialized, thus we eagerly initialize this module @@ -29,6 +26,7 @@ public class JSCHeapCapture extends ReactContextBaseJavaModule { CaptureException(String message) { super(message); } + CaptureException(String message, Throwable cause) { super(message, cause); } @@ -36,6 +34,7 @@ public class JSCHeapCapture extends ReactContextBaseJavaModule { public interface CaptureCallback { void onSuccess(File capture); + void onFailure(CaptureException error); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/devsupport/JSDebuggerWebSocketClient.java b/ReactAndroid/src/main/java/com/facebook/react/devsupport/JSDebuggerWebSocketClient.java index a6b44a5af04..f2bae2f1ec8 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/devsupport/JSDebuggerWebSocketClient.java +++ b/ReactAndroid/src/main/java/com/facebook/react/devsupport/JSDebuggerWebSocketClient.java @@ -1,20 +1,17 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.devsupport; import android.util.JsonReader; import android.util.JsonToken; import android.util.JsonWriter; - import com.facebook.common.logging.FLog; import com.facebook.infer.annotation.Assertions; import com.facebook.react.common.JavascriptException; - import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; @@ -22,24 +19,21 @@ import java.util.HashMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; - import javax.annotation.Nullable; - import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.WebSocket; import okhttp3.WebSocketListener; -/** - * A wrapper around WebSocketClient that recognizes RN debugging message format. - */ +/** A wrapper around WebSocketClient that recognizes RN debugging message format. */ public class JSDebuggerWebSocketClient extends WebSocketListener { private static final String TAG = "JSDebuggerWebSocketClient"; public interface JSDebuggerCallback { void onSuccess(@Nullable String response); + void onFailure(Throwable cause); } @@ -55,11 +49,12 @@ public class JSDebuggerWebSocketClient extends WebSocketListener { throw new IllegalStateException("JSDebuggerWebSocketClient is already initialized."); } mConnectCallback = callback; - mHttpClient = new OkHttpClient.Builder() - .connectTimeout(10, TimeUnit.SECONDS) - .writeTimeout(10, TimeUnit.SECONDS) - .readTimeout(0, TimeUnit.MINUTES) // Disable timeouts for read - .build(); + mHttpClient = + new OkHttpClient.Builder() + .connectTimeout(10, TimeUnit.SECONDS) + .writeTimeout(10, TimeUnit.SECONDS) + .readTimeout(0, TimeUnit.MINUTES) // Disable timeouts for read + .build(); Request request = new Request.Builder().url(url).build(); mHttpClient.newWebSocket(request, this); @@ -73,10 +68,12 @@ public class JSDebuggerWebSocketClient extends WebSocketListener { StringWriter sw = new StringWriter(); JsonWriter js = new JsonWriter(sw); js.beginObject() - .name("id").value(requestID) - .name("method").value("prepareJSRuntime") - .endObject() - .close(); + .name("id") + .value(requestID) + .name("method") + .value("prepareJSRuntime") + .endObject() + .close(); sendMessage(requestID, sw.toString()); } catch (IOException e) { triggerRequestFailure(requestID, e); @@ -84,20 +81,23 @@ public class JSDebuggerWebSocketClient extends WebSocketListener { } public void loadApplicationScript( - String sourceURL, - HashMap injectedObjects, - JSDebuggerCallback callback) { + String sourceURL, HashMap injectedObjects, JSDebuggerCallback callback) { int requestID = mRequestID.getAndIncrement(); mCallbacks.put(requestID, callback); try { StringWriter sw = new StringWriter(); - JsonWriter js = new JsonWriter(sw) - .beginObject() - .name("id").value(requestID) - .name("method").value("executeApplicationScript") - .name("url").value(sourceURL) - .name("inject").beginObject(); + JsonWriter js = + new JsonWriter(sw) + .beginObject() + .name("id") + .value(requestID) + .name("method") + .value("executeApplicationScript") + .name("url") + .value(sourceURL) + .name("inject") + .beginObject(); for (String key : injectedObjects.keySet()) { js.name(key).value(injectedObjects.get(key)); } @@ -108,10 +108,7 @@ public class JSDebuggerWebSocketClient extends WebSocketListener { } } - public void executeJSCall( - String methodName, - String jsonArgsArray, - JSDebuggerCallback callback) { + public void executeJSCall(String methodName, String jsonArgsArray, JSDebuggerCallback callback) { int requestID = mRequestID.getAndIncrement(); mCallbacks.put(requestID, callback); @@ -119,11 +116,9 @@ public class JSDebuggerWebSocketClient extends WebSocketListener { StringWriter sw = new StringWriter(); JsonWriter js = new JsonWriter(sw); - js.beginObject() - .name("id").value(requestID) - .name("method").value(methodName); + js.beginObject().name("id").value(requestID).name("method").value(methodName); /* JsonWriter does not offer writing raw string (without quotes), that's why - here we directly write to output string using the the underlying StringWriter */ + here we directly write to output string using the the underlying StringWriter */ sw.append(",\"arguments\":").append(jsonArgsArray); js.endObject().close(); sendMessage(requestID, sw.toString()); @@ -146,8 +141,7 @@ public class JSDebuggerWebSocketClient extends WebSocketListener { private void sendMessage(int requestID, String message) { if (mWebSocket == null) { triggerRequestFailure( - requestID, - new IllegalStateException("WebSocket connection no longer valid")); + requestID, new IllegalStateException("WebSocket connection no longer valid")); return; } try { diff --git a/ReactAndroid/src/main/java/com/facebook/react/devsupport/JSDevSupport.java b/ReactAndroid/src/main/java/com/facebook/react/devsupport/JSDevSupport.java index 9e98a6415ec..dcd9b5ed166 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/devsupport/JSDevSupport.java +++ b/ReactAndroid/src/main/java/com/facebook/react/devsupport/JSDevSupport.java @@ -9,7 +9,6 @@ import android.util.Pair; import android.view.View; import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.bridge.ReactApplicationContext; -import com.facebook.react.bridge.ReactContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.module.annotations.ReactModule; @@ -25,8 +24,7 @@ public class JSDevSupport extends ReactContextBaseJavaModule { public static final int ERROR_CODE_EXCEPTION = 0; public static final int ERROR_CODE_VIEW_NOT_FOUND = 1; - @Nullable - private volatile DevSupportCallback mCurrentCallback = null; + @Nullable private volatile DevSupportCallback mCurrentCallback = null; public interface JSDevSupportModule extends JavaScriptModule { void getJSHierarchy(int reactTag); @@ -55,11 +53,12 @@ public class JSDevSupport extends ReactContextBaseJavaModule { } public synchronized void getJSHierarchy(int reactTag, DevSupportCallback callback) { - JSDevSupportModule - jsDevSupportModule = getReactApplicationContext().getJSModule(JSDevSupportModule.class); + JSDevSupportModule jsDevSupportModule = + getReactApplicationContext().getJSModule(JSDevSupportModule.class); if (jsDevSupportModule == null) { - callback.onFailure(ERROR_CODE_EXCEPTION, new JSCHeapCapture.CaptureException(MODULE_NAME + - " module not registered.")); + callback.onFailure( + ERROR_CODE_EXCEPTION, + new JSCHeapCapture.CaptureException(MODULE_NAME + " module not registered.")); return; } mCurrentCallback = callback; @@ -94,5 +93,4 @@ public class JSDevSupport extends ReactContextBaseJavaModule { public String getName() { return MODULE_NAME; } - } diff --git a/ReactAndroid/src/main/java/com/facebook/react/devsupport/JSException.java b/ReactAndroid/src/main/java/com/facebook/react/devsupport/JSException.java index 7f7721fabb6..3a940334c75 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/devsupport/JSException.java +++ b/ReactAndroid/src/main/java/com/facebook/react/devsupport/JSException.java @@ -1,19 +1,17 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.devsupport; import com.facebook.proguard.annotations.DoNotStrip; /** - * This represents an error evaluating JavaScript. It includes the usual - * message, and the raw JS stack where the error occurred (which may be empty). + * This represents an error evaluating JavaScript. It includes the usual message, and the raw JS + * stack where the error occurred (which may be empty). */ - @DoNotStrip public class JSException extends Exception { private final String mStack; diff --git a/ReactAndroid/src/main/java/com/facebook/react/devsupport/MultipartStreamReader.java b/ReactAndroid/src/main/java/com/facebook/react/devsupport/MultipartStreamReader.java index a7e1db130e8..ed9e11904c8 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/devsupport/MultipartStreamReader.java +++ b/ReactAndroid/src/main/java/com/facebook/react/devsupport/MultipartStreamReader.java @@ -1,23 +1,19 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.devsupport; import java.io.IOException; import java.util.HashMap; import java.util.Map; - import okio.Buffer; import okio.BufferedSource; import okio.ByteString; -/** - * Utility class to parse the body of a response of type multipart/mixed. - */ +/** Utility class to parse the body of a response of type multipart/mixed. */ public class MultipartStreamReader { // Standard line separator for HTTP. private static final String CRLF = "\r\n"; @@ -27,14 +23,11 @@ public class MultipartStreamReader { private long mLastProgressEvent; public interface ChunkListener { - /** - * Invoked when a chunk of a multipart response is fully downloaded. - */ - void onChunkComplete(Map headers, Buffer body, boolean isLastChunk) throws IOException; + /** Invoked when a chunk of a multipart response is fully downloaded. */ + void onChunkComplete(Map headers, Buffer body, boolean isLastChunk) + throws IOException; - /** - * Invoked as bytes of the current chunk are read. - */ + /** Invoked as bytes of the current chunk are read. */ void onChunkProgress(Map headers, long loaded, long total) throws IOException; } @@ -77,7 +70,9 @@ public class MultipartStreamReader { } } - private void emitProgress(Map headers, long contentLength, boolean isFinal, ChunkListener listener) throws IOException { + private void emitProgress( + Map headers, long contentLength, boolean isFinal, ChunkListener listener) + throws IOException { if (headers == null || listener == null) { return; } @@ -85,13 +80,15 @@ public class MultipartStreamReader { long currentTime = System.currentTimeMillis(); if (currentTime - mLastProgressEvent > 16 || isFinal) { mLastProgressEvent = currentTime; - long headersContentLength = headers.get("Content-Length") != null ? Long.parseLong(headers.get("Content-Length")) : 0; + long headersContentLength = + headers.get("Content-Length") != null ? Long.parseLong(headers.get("Content-Length")) : 0; listener.onChunkProgress(headers, contentLength, headersContentLength); } } /** * Reads all parts of the multipart response and execute the listener for each chunk received. + * * @param listener Listener invoked when chunks are received. * @return If the read was successful */ diff --git a/ReactAndroid/src/main/java/com/facebook/react/devsupport/ReactInstanceManagerDevHelper.java b/ReactAndroid/src/main/java/com/facebook/react/devsupport/ReactInstanceManagerDevHelper.java index b9c35a5ee2e..bac19a8919f 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/devsupport/ReactInstanceManagerDevHelper.java +++ b/ReactAndroid/src/main/java/com/facebook/react/devsupport/ReactInstanceManagerDevHelper.java @@ -1,41 +1,32 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.devsupport; import android.app.Activity; import com.facebook.react.bridge.JavaJSExecutor; - import com.facebook.react.bridge.NativeDeltaClient; import javax.annotation.Nullable; /** - * Interface used by {@link DevSupportManager} for accessing some fields and methods of - * {@link ReactInstanceManager} for the purpose of displaying and handling developer menu options. + * Interface used by {@link DevSupportManager} for accessing some fields and methods of {@link + * ReactInstanceManager} for the purpose of displaying and handling developer menu options. */ public interface ReactInstanceManagerDevHelper { - /** - * Request react instance recreation with JS debugging enabled. - */ + /** Request react instance recreation with JS debugging enabled. */ void onReloadWithJSDebugger(JavaJSExecutor.Factory proxyExecutorFactory); - /** - * Notify react instance manager about new JS bundle version downloaded from the server. - */ + /** Notify react instance manager about new JS bundle version downloaded from the server. */ void onJSBundleLoadedFromServer(@Nullable NativeDeltaClient nativeDeltaClient); - /** - * Request to toggle the react element inspector. - */ + /** Request to toggle the react element inspector. */ void toggleElementInspector(); - /** - * Get reference to top level #{link Activity} attached to react context - */ - @Nullable Activity getCurrentActivity(); + /** Get reference to top level #{link Activity} attached to react context */ + @Nullable + Activity getCurrentActivity(); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/devsupport/RedBoxDialog.java b/ReactAndroid/src/main/java/com/facebook/react/devsupport/RedBoxDialog.java index 14c0867bb49..e4d82f47311 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/devsupport/RedBoxDialog.java +++ b/ReactAndroid/src/main/java/com/facebook/react/devsupport/RedBoxDialog.java @@ -1,14 +1,11 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.devsupport; -import javax.annotation.Nullable; - import android.app.Dialog; import android.content.Context; import android.graphics.Color; @@ -27,25 +24,22 @@ import android.widget.Button; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; - import com.facebook.common.logging.FLog; import com.facebook.infer.annotation.Assertions; import com.facebook.react.R; import com.facebook.react.common.MapBuilder; import com.facebook.react.common.ReactConstants; +import com.facebook.react.devsupport.RedBoxHandler.ReportCompletedListener; import com.facebook.react.devsupport.interfaces.DevSupportManager; import com.facebook.react.devsupport.interfaces.StackFrame; -import com.facebook.react.devsupport.RedBoxHandler.ReportCompletedListener; - +import javax.annotation.Nullable; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import org.json.JSONObject; -/** - * Dialog for displaying JS errors in an eye-catching form (red box). - */ +/** Dialog for displaying JS errors in an eye-catching form (red box). */ /* package */ class RedBoxDialog extends Dialog implements AdapterView.OnItemClickListener { private final DevSupportManager mDevSupportManager; @@ -61,48 +55,51 @@ import org.json.JSONObject; private @Nullable View mLineSeparator; private boolean isReporting = false; - private ReportCompletedListener mReportCompletedListener = new ReportCompletedListener() { - @Override - public void onReportSuccess(final SpannedString spannedString) { - isReporting = false; - Assertions.assertNotNull(mReportButton).setEnabled(true); - Assertions.assertNotNull(mLoadingIndicator).setVisibility(View.GONE); - Assertions.assertNotNull(mReportTextView).setText(spannedString); - } - @Override - public void onReportError(final SpannedString spannedString) { - isReporting = false; - Assertions.assertNotNull(mReportButton).setEnabled(true); - Assertions.assertNotNull(mLoadingIndicator).setVisibility(View.GONE); - Assertions.assertNotNull(mReportTextView).setText(spannedString); - } - }; + private ReportCompletedListener mReportCompletedListener = + new ReportCompletedListener() { + @Override + public void onReportSuccess(final SpannedString spannedString) { + isReporting = false; + Assertions.assertNotNull(mReportButton).setEnabled(true); + Assertions.assertNotNull(mLoadingIndicator).setVisibility(View.GONE); + Assertions.assertNotNull(mReportTextView).setText(spannedString); + } - private View.OnClickListener mReportButtonOnClickListener = new View.OnClickListener() { - @Override - public void onClick(View view) { - if (mRedBoxHandler == null || !mRedBoxHandler.isReportEnabled() || isReporting) { - return; - } - isReporting = true; - Assertions.assertNotNull(mReportTextView).setText("Reporting..."); - Assertions.assertNotNull(mReportTextView).setVisibility(View.VISIBLE); - Assertions.assertNotNull(mLoadingIndicator).setVisibility(View.VISIBLE); - Assertions.assertNotNull(mLineSeparator).setVisibility(View.VISIBLE); - Assertions.assertNotNull(mReportButton).setEnabled(false); + @Override + public void onReportError(final SpannedString spannedString) { + isReporting = false; + Assertions.assertNotNull(mReportButton).setEnabled(true); + Assertions.assertNotNull(mLoadingIndicator).setVisibility(View.GONE); + Assertions.assertNotNull(mReportTextView).setText(spannedString); + } + }; - String title = Assertions.assertNotNull(mDevSupportManager.getLastErrorTitle()); - StackFrame[] stack = Assertions.assertNotNull(mDevSupportManager.getLastErrorStack()); - String sourceUrl = mDevSupportManager.getSourceUrl(); + private View.OnClickListener mReportButtonOnClickListener = + new View.OnClickListener() { + @Override + public void onClick(View view) { + if (mRedBoxHandler == null || !mRedBoxHandler.isReportEnabled() || isReporting) { + return; + } + isReporting = true; + Assertions.assertNotNull(mReportTextView).setText("Reporting..."); + Assertions.assertNotNull(mReportTextView).setVisibility(View.VISIBLE); + Assertions.assertNotNull(mLoadingIndicator).setVisibility(View.VISIBLE); + Assertions.assertNotNull(mLineSeparator).setVisibility(View.VISIBLE); + Assertions.assertNotNull(mReportButton).setEnabled(false); - mRedBoxHandler.reportRedbox( - view.getContext(), - title, - stack, - sourceUrl, - Assertions.assertNotNull(mReportCompletedListener)); - } - }; + String title = Assertions.assertNotNull(mDevSupportManager.getLastErrorTitle()); + StackFrame[] stack = Assertions.assertNotNull(mDevSupportManager.getLastErrorStack()); + String sourceUrl = mDevSupportManager.getSourceUrl(); + + mRedBoxHandler.reportRedbox( + view.getContext(), + title, + stack, + sourceUrl, + Assertions.assertNotNull(mReportCompletedListener)); + } + }; private static class StackAdapter extends BaseAdapter { private static final int VIEW_TYPE_COUNT = 2; @@ -165,17 +162,20 @@ import org.json.JSONObject; @Override public View getView(int position, View convertView, ViewGroup parent) { if (position == 0) { - TextView title = convertView != null - ? (TextView) convertView - : (TextView) LayoutInflater.from(parent.getContext()) - .inflate(R.layout.redbox_item_title, parent, false); + TextView title = + convertView != null + ? (TextView) convertView + : (TextView) + LayoutInflater.from(parent.getContext()) + .inflate(R.layout.redbox_item_title, parent, false); // Remove ANSI color codes from the title title.setText(mTitle.replaceAll("\\x1b\\[[0-9;]*m", "")); return title; } else { if (convertView == null) { - convertView = LayoutInflater.from(parent.getContext()) - .inflate(R.layout.redbox_item_frame, parent, false); + convertView = + LayoutInflater.from(parent.getContext()) + .inflate(R.layout.redbox_item_frame, parent, false); convertView.setTag(new FrameViewHolder(convertView)); } StackFrame frame = mStack[position - 1]; @@ -200,13 +200,14 @@ import org.json.JSONObject; protected Void doInBackground(StackFrame... stackFrames) { try { String openStackFrameUrl = - Uri.parse(mDevSupportManager.getSourceUrl()).buildUpon() + Uri.parse(mDevSupportManager.getSourceUrl()) + .buildUpon() .path("/open-stack-frame") .query(null) .build() .toString(); OkHttpClient client = new OkHttpClient(); - for (StackFrame frame: stackFrames) { + for (StackFrame frame : stackFrames) { String payload = stackFrameToJson(frame).toString(); RequestBody body = RequestBody.create(JSON, payload); Request request = new Request.Builder().url(openStackFrameUrl).post(body).build(); @@ -224,15 +225,12 @@ import org.json.JSONObject; "file", frame.getFile(), "methodName", frame.getMethod(), "lineNumber", frame.getLine(), - "column", frame.getColumn() - )); + "column", frame.getColumn())); } } protected RedBoxDialog( - Context context, - DevSupportManager devSupportManager, - @Nullable RedBoxHandler redBoxHandler) { + Context context, DevSupportManager devSupportManager, @Nullable RedBoxHandler redBoxHandler) { super(context, R.style.Theme_Catalyst_RedBox); requestWindowFeature(Window.FEATURE_NO_TITLE); @@ -247,19 +245,21 @@ import org.json.JSONObject; mStackView.setOnItemClickListener(this); mReloadJsButton = (Button) findViewById(R.id.rn_redbox_reload_button); - mReloadJsButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - mDevSupportManager.handleReloadJS(); - } - }); + mReloadJsButton.setOnClickListener( + new View.OnClickListener() { + @Override + public void onClick(View v) { + mDevSupportManager.handleReloadJS(); + } + }); mDismissButton = (Button) findViewById(R.id.rn_redbox_dismiss_button); - mDismissButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - dismiss(); - } - }); + mDismissButton.setOnClickListener( + new View.OnClickListener() { + @Override + public void onClick(View v) { + dismiss(); + } + }); if (mRedBoxHandler != null && mRedBoxHandler.isReportEnabled()) { mLoadingIndicator = (ProgressBar) findViewById(R.id.rn_redbox_loading_indicator); @@ -276,9 +276,7 @@ import org.json.JSONObject; mStackView.setAdapter(new StackAdapter(title, stack)); } - /** - * Show the report button, hide the report textview and the loading indicator. - */ + /** Show the report button, hide the report textview and the loading indicator. */ public void resetReporting() { if (mRedBoxHandler == null || !mRedBoxHandler.isReportEnabled()) { return; @@ -293,9 +291,9 @@ import org.json.JSONObject; @Override public void onItemClick(AdapterView parent, View view, int position, long id) { - new OpenStackFrameTask(mDevSupportManager).executeOnExecutor( - AsyncTask.THREAD_POOL_EXECUTOR, - (StackFrame) mStackView.getAdapter().getItem(position)); + new OpenStackFrameTask(mDevSupportManager) + .executeOnExecutor( + AsyncTask.THREAD_POOL_EXECUTOR, (StackFrame) mStackView.getAdapter().getItem(position)); } @Override diff --git a/ReactAndroid/src/main/java/com/facebook/react/devsupport/RedBoxHandler.java b/ReactAndroid/src/main/java/com/facebook/react/devsupport/RedBoxHandler.java index 3df7aa399a2..4edaefb3dcd 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/devsupport/RedBoxHandler.java +++ b/ReactAndroid/src/main/java/com/facebook/react/devsupport/RedBoxHandler.java @@ -1,22 +1,20 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.devsupport; import android.content.Context; -import androidx.annotation.Nullable; import android.text.SpannedString; - +import androidx.annotation.Nullable; import com.facebook.react.devsupport.interfaces.StackFrame; /** - * Interface used by {@link DevSupportManagerImpl} to allow interception on any redboxes - * during development and handling the information from the redbox. - * The implementation should be passed by setRedBoxHandler in ReactInstanceManager. + * Interface used by {@link DevSupportManagerImpl} to allow interception on any redboxes during + * development and handling the information from the redbox. The implementation should be passed by + * setRedBoxHandler in ReactInstanceManager. */ public interface RedBoxHandler { enum ErrorType { @@ -24,35 +22,30 @@ public interface RedBoxHandler { NATIVE("Native"); private final String name; + ErrorType(String name) { this.name = name; } + public String getName() { return name; } } - /** - * Callback interface for {@link #reportRedbox}. - */ + /** Callback interface for {@link #reportRedbox}. */ interface ReportCompletedListener { void onReportSuccess(SpannedString spannedString); + void onReportError(SpannedString spannedString); } - /** - * Handle the information from the redbox. - */ + /** Handle the information from the redbox. */ void handleRedbox(@Nullable String title, StackFrame[] stack, ErrorType errorType); - /** - * Whether the report feature is enabled. - */ + /** Whether the report feature is enabled. */ boolean isReportEnabled(); - /** - * Report the information from the redbox and set up a callback listener. - */ + /** Report the information from the redbox and set up a callback listener. */ void reportRedbox( Context context, String title, diff --git a/ReactAndroid/src/main/java/com/facebook/react/devsupport/StackTraceHelper.java b/ReactAndroid/src/main/java/com/facebook/react/devsupport/StackTraceHelper.java index 1476b30a8ad..b6bf202cd20 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/devsupport/StackTraceHelper.java +++ b/ReactAndroid/src/main/java/com/facebook/react/devsupport/StackTraceHelper.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.devsupport; import com.facebook.react.bridge.ReadableArray; @@ -20,22 +19,18 @@ import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; -/** - * Helper class converting JS and Java stack traces into arrays of {@link StackFrame} objects. - */ +/** Helper class converting JS and Java stack traces into arrays of {@link StackFrame} objects. */ public class StackTraceHelper { public static final java.lang.String COLUMN_KEY = "column"; public static final java.lang.String LINE_NUMBER_KEY = "lineNumber"; - private static final Pattern STACK_FRAME_PATTERN1 = Pattern.compile( - "^(?:(.*?)@)?(.*?)\\:([0-9]+)\\:([0-9]+)$"); - private static final Pattern STACK_FRAME_PATTERN2 = Pattern.compile( - "\\s*(?:at)\\s*(.+?)\\s*[@(](.*):([0-9]+):([0-9]+)[)]$"); + private static final Pattern STACK_FRAME_PATTERN1 = + Pattern.compile("^(?:(.*?)@)?(.*?)\\:([0-9]+)\\:([0-9]+)$"); + private static final Pattern STACK_FRAME_PATTERN2 = + Pattern.compile("\\s*(?:at)\\s*(.+?)\\s*[@(](.*):([0-9]+):([0-9]+)[)]$"); - /** - * Represents a generic entry in a stack trace, be it originally from JS or Java. - */ + /** Represents a generic entry in a stack trace, be it originally from JS or Java. */ public static class StackFrameImpl implements StackFrame { private final String mFile; private final String mMethod; @@ -62,30 +57,24 @@ public class StackTraceHelper { /** * Get the file this stack frame points to. * - * JS traces return the full path to the file here, while Java traces only return the file name - * (the path is not known). + *

JS traces return the full path to the file here, while Java traces only return the file + * name (the path is not known). */ public String getFile() { return mFile; } - /** - * Get the name of the method this frame points to. - */ + /** Get the name of the method this frame points to. */ public String getMethod() { return mMethod; } - /** - * Get the line number this frame points to in the file returned by {@link #getFile()}. - */ + /** Get the line number this frame points to in the file returned by {@link #getFile()}. */ public int getLine() { return mLine; } - /** - * Get the column this frame points to in the file returned by {@link #getFile()}. - */ + /** Get the column this frame points to in the file returned by {@link #getFile()}. */ public int getColumn() { return mColumn; } @@ -93,16 +82,14 @@ public class StackTraceHelper { /** * Get just the name of the file this frame points to. * - * For JS traces this is different from {@link #getFile()} in that it only returns the file + *

For JS traces this is different from {@link #getFile()} in that it only returns the file * name, not the full path. For Java traces there is no difference. */ public String getFileName() { return mFileName; } - /** - * Convert the stack frame to a JSON representation. - */ + /** Convert the stack frame to a JSON representation. */ public JSONObject toJSON() { return new JSONObject( MapBuilder.of( @@ -114,8 +101,8 @@ public class StackTraceHelper { } /** - * Convert a JavaScript stack trace (see {@code parseErrorStack} JS module) to an array of - * {@link StackFrame}s. + * Convert a JavaScript stack trace (see {@code parseErrorStack} JS module) to an array of {@link + * StackFrame}s. */ public static StackFrame[] convertJsStackTrace(@Nullable ReadableArray stack) { int size = stack != null ? stack.size() : 0; @@ -143,8 +130,8 @@ public class StackTraceHelper { } /** - * Convert a JavaScript stack trace (see {@code parseErrorStack} JS module) to an array of - * {@link StackFrame}s. + * Convert a JavaScript stack trace (see {@code parseErrorStack} JS module) to an array of {@link + * StackFrame}s. */ public static StackFrame[] convertJsStackTrace(JSONArray stack) { int size = stack != null ? stack.length() : 0; @@ -170,9 +157,7 @@ public class StackTraceHelper { return result; } - /** - * Convert a JavaScript stack trace to an array of {@link StackFrame}s. - */ + /** Convert a JavaScript stack trace to an array of {@link StackFrame}s. */ public static StackFrame[] convertJsStackTrace(String stack) { String[] stackTrace = stack.split("\n"); StackFrame[] result = new StackFrame[stackTrace.length]; @@ -188,35 +173,33 @@ public class StackTraceHelper { result[i] = new StackFrameImpl(null, stackTrace[i], -1, -1); continue; } - result[i] = new StackFrameImpl( - matcher.group(2), - matcher.group(1) == null ? "(unknown)" : matcher.group(1), - Integer.parseInt(matcher.group(3)), - Integer.parseInt(matcher.group(4))); + result[i] = + new StackFrameImpl( + matcher.group(2), + matcher.group(1) == null ? "(unknown)" : matcher.group(1), + Integer.parseInt(matcher.group(3)), + Integer.parseInt(matcher.group(4))); } return result; } - /** - * Convert a {@link Throwable} to an array of {@link StackFrame}s. - */ + /** Convert a {@link Throwable} to an array of {@link StackFrame}s. */ public static StackFrame[] convertJavaStackTrace(Throwable exception) { StackTraceElement[] stackTrace = exception.getStackTrace(); StackFrame[] result = new StackFrame[stackTrace.length]; for (int i = 0; i < stackTrace.length; i++) { - result[i] = new StackFrameImpl( - stackTrace[i].getClassName(), - stackTrace[i].getFileName(), - stackTrace[i].getMethodName(), - stackTrace[i].getLineNumber(), - -1); + result[i] = + new StackFrameImpl( + stackTrace[i].getClassName(), + stackTrace[i].getFileName(), + stackTrace[i].getMethodName(), + stackTrace[i].getLineNumber(), + -1); } return result; } - /** - * Format a {@link StackFrame} to a String (method name is not included). - */ + /** Format a {@link StackFrame} to a String (method name is not included). */ public static String formatFrameSource(StackFrame frame) { StringBuilder lineInfo = new StringBuilder(); lineInfo.append(frame.getFileName()); @@ -231,14 +214,13 @@ public class StackTraceHelper { return lineInfo.toString(); } - /** - * Format an array of {@link StackFrame}s with the error title to a String. - */ + /** Format an array of {@link StackFrame}s with the error title to a String. */ public static String formatStackTrace(String title, StackFrame[] stack) { StringBuilder stackTrace = new StringBuilder(); stackTrace.append(title).append("\n"); - for (StackFrame frame: stack) { - stackTrace.append(frame.getMethod()) + for (StackFrame frame : stack) { + stackTrace + .append(frame.getMethod()) .append("\n") .append(" ") .append(formatFrameSource(frame)) diff --git a/ReactAndroid/src/main/java/com/facebook/react/devsupport/ViewHierarchyUtil.java b/ReactAndroid/src/main/java/com/facebook/react/devsupport/ViewHierarchyUtil.java index 56e617cafd8..a65287acc48 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/devsupport/ViewHierarchyUtil.java +++ b/ReactAndroid/src/main/java/com/facebook/react/devsupport/ViewHierarchyUtil.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.devsupport; import android.util.Pair; @@ -13,14 +12,10 @@ import android.view.ViewGroup; import java.util.LinkedList; import java.util.Queue; -/** - * Helper for computing information about the view hierarchy - */ +/** Helper for computing information about the view hierarchy */ public class ViewHierarchyUtil { - /** - * Returns the view instance and depth of the deepest leaf view from the given root view. - */ + /** Returns the view instance and depth of the deepest leaf view from the given root view. */ public static Pair getDeepestLeaf(View root) { Queue> queue = new LinkedList<>(); Pair maxPair = new Pair<>(root, 1); @@ -34,7 +29,7 @@ public class ViewHierarchyUtil { if (current.first instanceof ViewGroup) { ViewGroup viewGroup = (ViewGroup) current.first; Integer depth = current.second + 1; - for (int i = 0 ; i < viewGroup.getChildCount() ; i++) { + for (int i = 0; i < viewGroup.getChildCount(); i++) { queue.add(new Pair<>(viewGroup.getChildAt(i), depth)); } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/devsupport/WebsocketJavaScriptExecutor.java b/ReactAndroid/src/main/java/com/facebook/react/devsupport/WebsocketJavaScriptExecutor.java index ffeb568382e..041c4143a3b 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/devsupport/WebsocketJavaScriptExecutor.java +++ b/ReactAndroid/src/main/java/com/facebook/react/devsupport/WebsocketJavaScriptExecutor.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.devsupport; import android.os.Handler; @@ -16,9 +15,7 @@ import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicInteger; import javax.annotation.Nullable; -/** - * Executes JS remotely via the react nodejs server as a proxy to a browser on the host machine. - */ +/** Executes JS remotely via the react nodejs server as a proxy to a browser on the host machine. */ public class WebsocketJavaScriptExecutor implements JavaJSExecutor { private static final long CONNECT_TIMEOUT_MS = 5000; @@ -26,6 +23,7 @@ public class WebsocketJavaScriptExecutor implements JavaJSExecutor { public interface JSExecutorConnectCallback { void onSuccess(); + void onFailure(Throwable cause); } @@ -35,8 +33,8 @@ public class WebsocketJavaScriptExecutor implements JavaJSExecutor { } } - private static class JSExecutorCallbackFuture implements - JSDebuggerWebSocketClient.JSDebuggerCallback { + private static class JSExecutorCallbackFuture + implements JSDebuggerWebSocketClient.JSDebuggerCallback { private final Semaphore mSemaphore = new Semaphore(0); private @Nullable Throwable mCause; @@ -54,9 +52,7 @@ public class WebsocketJavaScriptExecutor implements JavaJSExecutor { mSemaphore.release(); } - /** - * Call only once per object instance! - */ + /** Call only once per object instance! */ public @Nullable String get() throws Throwable { mSemaphore.acquire(); if (mCause != null) { @@ -66,36 +62,37 @@ public class WebsocketJavaScriptExecutor implements JavaJSExecutor { } } - final private HashMap mInjectedObjects = new HashMap<>(); + private final HashMap mInjectedObjects = new HashMap<>(); private @Nullable JSDebuggerWebSocketClient mWebSocketClient; public void connect(final String webSocketServerUrl, final JSExecutorConnectCallback callback) { final AtomicInteger retryCount = new AtomicInteger(CONNECT_RETRY_COUNT); - final JSExecutorConnectCallback retryProxyCallback = new JSExecutorConnectCallback() { - @Override - public void onSuccess() { - callback.onSuccess(); - } + final JSExecutorConnectCallback retryProxyCallback = + new JSExecutorConnectCallback() { + @Override + public void onSuccess() { + callback.onSuccess(); + } - @Override - public void onFailure(Throwable cause) { - if (retryCount.decrementAndGet() <= 0) { - callback.onFailure(cause); - } else { - connectInternal(webSocketServerUrl, this); - } - } - }; + @Override + public void onFailure(Throwable cause) { + if (retryCount.decrementAndGet() <= 0) { + callback.onFailure(cause); + } else { + connectInternal(webSocketServerUrl, this); + } + } + }; connectInternal(webSocketServerUrl, retryProxyCallback); } private void connectInternal( - String webSocketServerUrl, - final JSExecutorConnectCallback callback) { + String webSocketServerUrl, final JSExecutorConnectCallback callback) { final JSDebuggerWebSocketClient client = new JSDebuggerWebSocketClient(); final Handler timeoutHandler = new Handler(Looper.getMainLooper()); client.connect( - webSocketServerUrl, new JSDebuggerWebSocketClient.JSDebuggerCallback() { + webSocketServerUrl, + new JSDebuggerWebSocketClient.JSDebuggerCallback() { // It's possible that both callbacks can fire on an error so make sure we only // dispatch results once to our callback. private boolean didSendResult = false; @@ -157,10 +154,8 @@ public class WebsocketJavaScriptExecutor implements JavaJSExecutor { @Override public void loadApplicationScript(String sourceURL) throws JavaJSExecutor.ProxyExecutorException { JSExecutorCallbackFuture callback = new JSExecutorCallbackFuture(); - Assertions.assertNotNull(mWebSocketClient).loadApplicationScript( - sourceURL, - mInjectedObjects, - callback); + Assertions.assertNotNull(mWebSocketClient) + .loadApplicationScript(sourceURL, mInjectedObjects, callback); try { callback.get(); } catch (Throwable cause) { @@ -172,10 +167,7 @@ public class WebsocketJavaScriptExecutor implements JavaJSExecutor { public @Nullable String executeJSCall(String methodName, String jsonArgsArray) throws JavaJSExecutor.ProxyExecutorException { JSExecutorCallbackFuture callback = new JSExecutorCallbackFuture(); - Assertions.assertNotNull(mWebSocketClient).executeJSCall( - methodName, - jsonArgsArray, - callback); + Assertions.assertNotNull(mWebSocketClient).executeJSCall(methodName, jsonArgsArray, callback); try { return callback.get(); } catch (Throwable cause) { diff --git a/ReactAndroid/src/main/java/com/facebook/react/devsupport/WindowOverlayCompat.java b/ReactAndroid/src/main/java/com/facebook/react/devsupport/WindowOverlayCompat.java index 9027148553d..97a39dc7098 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/devsupport/WindowOverlayCompat.java +++ b/ReactAndroid/src/main/java/com/facebook/react/devsupport/WindowOverlayCompat.java @@ -1,25 +1,29 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.devsupport; import android.os.Build; import android.view.WindowManager; /** - * Compatibility wrapper for apps targeting API level 26 or later. - * See https://developer.android.com/about/versions/oreo/android-8.0-changes.html#cwt + * Compatibility wrapper for apps targeting API level 26 or later. See + * https://developer.android.com/about/versions/oreo/android-8.0-changes.html#cwt */ /* package */ class WindowOverlayCompat { private static final int ANDROID_OREO = 26; private static final int TYPE_APPLICATION_OVERLAY = 2038; - static final int TYPE_SYSTEM_ALERT = Build.VERSION.SDK_INT < ANDROID_OREO ? WindowManager.LayoutParams.TYPE_SYSTEM_ALERT : TYPE_APPLICATION_OVERLAY; - static final int TYPE_SYSTEM_OVERLAY = Build.VERSION.SDK_INT < ANDROID_OREO ? WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY : TYPE_APPLICATION_OVERLAY; - + static final int TYPE_SYSTEM_ALERT = + Build.VERSION.SDK_INT < ANDROID_OREO + ? WindowManager.LayoutParams.TYPE_SYSTEM_ALERT + : TYPE_APPLICATION_OVERLAY; + static final int TYPE_SYSTEM_OVERLAY = + Build.VERSION.SDK_INT < ANDROID_OREO + ? WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY + : TYPE_APPLICATION_OVERLAY; } diff --git a/ReactAndroid/src/main/java/com/facebook/react/devsupport/interfaces/DevBundleDownloadListener.java b/ReactAndroid/src/main/java/com/facebook/react/devsupport/interfaces/DevBundleDownloadListener.java index 1d7f2a49eba..3338975cca7 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/devsupport/interfaces/DevBundleDownloadListener.java +++ b/ReactAndroid/src/main/java/com/facebook/react/devsupport/interfaces/DevBundleDownloadListener.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.devsupport.interfaces; import com.facebook.react.bridge.NativeDeltaClient; @@ -12,6 +11,8 @@ import javax.annotation.Nullable; public interface DevBundleDownloadListener { void onSuccess(@Nullable NativeDeltaClient nativeDeltaClient); + void onProgress(@Nullable String status, @Nullable Integer done, @Nullable Integer total); + void onFailure(Exception cause); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/devsupport/interfaces/DevOptionHandler.java b/ReactAndroid/src/main/java/com/facebook/react/devsupport/interfaces/DevOptionHandler.java index 9e84ae97432..fd7f807ae01 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/devsupport/interfaces/DevOptionHandler.java +++ b/ReactAndroid/src/main/java/com/facebook/react/devsupport/interfaces/DevOptionHandler.java @@ -1,16 +1,15 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.devsupport.interfaces; /** - * Callback class for custom options that may appear in {@link DevSupportManager} developer - * options menu. In case when option registered for this handler is selected from the menu, the - * instance method {@link #onOptionSelected} will be triggered. + * Callback class for custom options that may appear in {@link DevSupportManager} developer options + * menu. In case when option registered for this handler is selected from the menu, the instance + * method {@link #onOptionSelected} will be triggered. */ public interface DevOptionHandler { @@ -19,5 +18,4 @@ public interface DevOptionHandler { * displayed with {@link DevSupportManager}. */ public void onOptionSelected(); - } diff --git a/ReactAndroid/src/main/java/com/facebook/react/devsupport/interfaces/DevSupportManager.java b/ReactAndroid/src/main/java/com/facebook/react/devsupport/interfaces/DevSupportManager.java index 6fb3775da7a..c30c9939558 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/devsupport/interfaces/DevSupportManager.java +++ b/ReactAndroid/src/main/java/com/facebook/react/devsupport/interfaces/DevSupportManager.java @@ -1,59 +1,87 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.devsupport.interfaces; -import javax.annotation.Nullable; - -import java.io.File; - import com.facebook.react.bridge.NativeModuleCallExceptionHandler; import com.facebook.react.bridge.ReactContext; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.modules.debug.interfaces.DeveloperSettings; +import java.io.File; +import javax.annotation.Nullable; /** - * Interface for accessing and interacting with development features. - * In dev mode, use the implementation {@link DevSupportManagerImpl}. - * In production mode, use the dummy implementation {@link DisabledDevSupportManager}. + * Interface for accessing and interacting with development features. In dev mode, use the + * implementation {@link DevSupportManagerImpl}. In production mode, use the dummy implementation + * {@link DisabledDevSupportManager}. */ public interface DevSupportManager extends NativeModuleCallExceptionHandler { void showNewJavaError(String message, Throwable e); + void addCustomDevOption(String optionName, DevOptionHandler optionHandler); + void showNewJSError(String message, ReadableArray details, int errorCookie); + void updateJSError(final String message, final ReadableArray details, final int errorCookie); + void hideRedboxDialog(); + void showDevOptionsDialog(); + void setDevSupportEnabled(boolean isDevSupportEnabled); + void startInspector(); + void stopInspector(); + boolean getDevSupportEnabled(); + DeveloperSettings getDevSettings(); + void onNewReactContextCreated(ReactContext reactContext); + void onReactInstanceDestroyed(ReactContext reactContext); + String getSourceMapUrl(); + String getSourceUrl(); + String getJSBundleURLForRemoteDebugging(); + String getDownloadedJSBundleFile(); + boolean hasUpToDateJSBundleInCache(); + void reloadSettings(); + void handleReloadJS(); + void reloadJSFromServer(final String bundleURL); + void isPackagerRunning(PackagerStatusCallback callback); + void setHotModuleReplacementEnabled(final boolean isHotModuleReplacementEnabled); + void setRemoteJSDebugEnabled(final boolean isRemoteJSDebugEnabled); + void setReloadOnJSChangeEnabled(final boolean isReloadOnJSChangeEnabled); + void setFpsDebugEnabled(final boolean isFpsDebugEnabled); + void toggleElementInspector(); - @Nullable File downloadBundleResourceFromUrlSync( - final String resourceURL, - final File outputFile); - @Nullable String getLastErrorTitle(); - @Nullable StackFrame[] getLastErrorStack(); + + @Nullable + File downloadBundleResourceFromUrlSync(final String resourceURL, final File outputFile); + + @Nullable + String getLastErrorTitle(); + + @Nullable + StackFrame[] getLastErrorStack(); + void registerErrorCustomizer(ErrorCustomizer errorCustomizer); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/devsupport/interfaces/ErrorCustomizer.java b/ReactAndroid/src/main/java/com/facebook/react/devsupport/interfaces/ErrorCustomizer.java index 4d251bb0d6c..b0c7dde0a0b 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/devsupport/interfaces/ErrorCustomizer.java +++ b/ReactAndroid/src/main/java/com/facebook/react/devsupport/interfaces/ErrorCustomizer.java @@ -1,16 +1,14 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ package com.facebook.react.devsupport.interfaces; import android.util.Pair; -/** - * Interface that lets parts of the app process the errors before showing the redbox - */ +/** Interface that lets parts of the app process the errors before showing the redbox */ public interface ErrorCustomizer { /** diff --git a/ReactAndroid/src/main/java/com/facebook/react/devsupport/interfaces/PackagerStatusCallback.java b/ReactAndroid/src/main/java/com/facebook/react/devsupport/interfaces/PackagerStatusCallback.java index d257023bcd4..b5dd5c71a56 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/devsupport/interfaces/PackagerStatusCallback.java +++ b/ReactAndroid/src/main/java/com/facebook/react/devsupport/interfaces/PackagerStatusCallback.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.devsupport.interfaces; public interface PackagerStatusCallback { diff --git a/ReactAndroid/src/main/java/com/facebook/react/devsupport/interfaces/StackFrame.java b/ReactAndroid/src/main/java/com/facebook/react/devsupport/interfaces/StackFrame.java index f512198c171..b544bfb1f76 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/devsupport/interfaces/StackFrame.java +++ b/ReactAndroid/src/main/java/com/facebook/react/devsupport/interfaces/StackFrame.java @@ -1,51 +1,40 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.devsupport.interfaces; import org.json.JSONObject; -/** - * Represents a generic entry in a stack trace, be it originally from JS or Java. - */ +/** Represents a generic entry in a stack trace, be it originally from JS or Java. */ public interface StackFrame { /** - * Get the file this stack frame points to. - * - * JS traces return the full path to the file here, while Java traces only return the file name - * (the path is not known). - */ + * Get the file this stack frame points to. + * + *

JS traces return the full path to the file here, while Java traces only return the file name + * (the path is not known). + */ public String getFile(); - /** - * Get the name of the method this frame points to. - */ + /** Get the name of the method this frame points to. */ public String getMethod(); - /** - * Get the line number this frame points to in the file returned by {@link #getFile()}. - */ + /** Get the line number this frame points to in the file returned by {@link #getFile()}. */ public int getLine(); - /** - * Get the column this frame points to in the file returned by {@link #getFile()}. - */ + /** Get the column this frame points to in the file returned by {@link #getFile()}. */ public int getColumn(); /** - * Get just the name of the file this frame points to. - * - * For JS traces this is different from {@link #getFile()} in that it only returns the file - * name, not the full path. For Java traces there is no difference. - */ + * Get just the name of the file this frame points to. + * + *

For JS traces this is different from {@link #getFile()} in that it only returns the file + * name, not the full path. For Java traces there is no difference. + */ public String getFileName(); - /** - * Convert the stack frame to a JSON representation. - */ + /** Convert the stack frame to a JSON representation. */ public JSONObject toJSON(); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/fabric/Binding.java b/ReactAndroid/src/main/java/com/facebook/react/fabric/Binding.java index c77f2f1c0e8..24e099bff03 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/fabric/Binding.java +++ b/ReactAndroid/src/main/java/com/facebook/react/fabric/Binding.java @@ -41,7 +41,14 @@ public class Binding { public native void startSurface(int surfaceId, String moduleName, NativeMap initialProps); - public native void startSurfaceWithConstraints(int surfaceId, String moduleName, NativeMap initialProps, float minWidth, float maxWidth, float minHeight, float maxHeight); + public native void startSurfaceWithConstraints( + int surfaceId, + String moduleName, + NativeMap initialProps, + float minWidth, + float maxWidth, + float minHeight, + float maxHeight); public native void renderTemplateToSurface(int surfaceId, String uiTemplate); @@ -53,17 +60,22 @@ public class Binding { int surfaceId, float minWidth, float maxWidth, float minHeight, float maxHeight); public void register( - JavaScriptContextHolder jsContext, - FabricUIManager fabricUIManager, - EventBeatManager eventBeatManager, - MessageQueueThread jsMessageQueueThread, - ComponentFactoryDelegate componentFactoryDelegate, - ReactNativeConfig reactNativeConfig) { + JavaScriptContextHolder jsContext, + FabricUIManager fabricUIManager, + EventBeatManager eventBeatManager, + MessageQueueThread jsMessageQueueThread, + ComponentFactoryDelegate componentFactoryDelegate, + ReactNativeConfig reactNativeConfig) { fabricUIManager.setBinding(this); - installFabricUIManager( - jsContext.get(), fabricUIManager, eventBeatManager, jsMessageQueueThread, componentFactoryDelegate, reactNativeConfig); - setPixelDensity(PixelUtil.getDisplayMetricDensity()); - } + installFabricUIManager( + jsContext.get(), + fabricUIManager, + eventBeatManager, + jsMessageQueueThread, + componentFactoryDelegate, + reactNativeConfig); + setPixelDensity(PixelUtil.getDisplayMetricDensity()); + } private native void uninstallFabricUIManager(); diff --git a/ReactAndroid/src/main/java/com/facebook/react/fabric/ComponentFactoryDelegate.java b/ReactAndroid/src/main/java/com/facebook/react/fabric/ComponentFactoryDelegate.java index 412cec466fb..62d43fcdc61 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/fabric/ComponentFactoryDelegate.java +++ b/ReactAndroid/src/main/java/com/facebook/react/fabric/ComponentFactoryDelegate.java @@ -4,7 +4,6 @@ package com.facebook.react.fabric; import com.facebook.jni.HybridData; import com.facebook.proguard.annotations.DoNotStrip; -import com.facebook.soloader.SoLoader; @DoNotStrip public class ComponentFactoryDelegate { @@ -13,8 +12,7 @@ public class ComponentFactoryDelegate { FabricSoLoader.staticInit(); } - @DoNotStrip - private final HybridData mHybridData; + @DoNotStrip private final HybridData mHybridData; @DoNotStrip private static native HybridData initHybrid(); @@ -22,5 +20,4 @@ public class ComponentFactoryDelegate { public ComponentFactoryDelegate() { mHybridData = initHybrid(); } - } diff --git a/ReactAndroid/src/main/java/com/facebook/react/fabric/FabricComponents.java b/ReactAndroid/src/main/java/com/facebook/react/fabric/FabricComponents.java index 7d1cb572449..77ac65795bd 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/fabric/FabricComponents.java +++ b/ReactAndroid/src/main/java/com/facebook/react/fabric/FabricComponents.java @@ -1,8 +1,8 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ package com.facebook.react.fabric; @@ -35,12 +35,9 @@ public class FabricComponents { sComponentNames.put("AxialGradientView", "RCTAxialGradientView"); } - /** - * @return the name of component in the Fabric environment - */ + /** @return the name of component in the Fabric environment */ static String getFabricComponentName(String componentName) { String component = sComponentNames.get(componentName); return component != null ? component : componentName; } - } diff --git a/ReactAndroid/src/main/java/com/facebook/react/fabric/FabricJSIModuleProvider.java b/ReactAndroid/src/main/java/com/facebook/react/fabric/FabricJSIModuleProvider.java index 1ae2f49caf8..2bb54b6d8b8 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/fabric/FabricJSIModuleProvider.java +++ b/ReactAndroid/src/main/java/com/facebook/react/fabric/FabricJSIModuleProvider.java @@ -41,20 +41,19 @@ public class FabricJSIModuleProvider implements JSIModuleProvider { private final ReactNativeConfig mConfig; public FabricJSIModuleProvider( - ReactApplicationContext reactApplicationContext, - JavaScriptContextHolder jsContext, - ComponentFactoryDelegate componentFactoryDelegate, - ReactNativeConfig config) { - mReactApplicationContext = reactApplicationContext; - mJSContext = jsContext; - mComponentFactoryDelegate = componentFactoryDelegate; - mConfig = config; - } + ReactApplicationContext reactApplicationContext, + JavaScriptContextHolder jsContext, + ComponentFactoryDelegate componentFactoryDelegate, + ReactNativeConfig config) { + mReactApplicationContext = reactApplicationContext; + mJSContext = jsContext; + mComponentFactoryDelegate = componentFactoryDelegate; + mConfig = config; + } @Override public UIManager get() { - final EventBeatManager eventBeatManager = - new EventBeatManager(mReactApplicationContext); + final EventBeatManager eventBeatManager = new EventBeatManager(mReactApplicationContext); final FabricUIManager uiManager = createUIManager(eventBeatManager); Systrace.beginSection( Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "FabricJSIModuleProvider.registerBinding"); @@ -66,8 +65,13 @@ public class FabricJSIModuleProvider implements JSIModuleProvider { .getCatalystInstance() .getReactQueueConfiguration() .getJSQueueThread(); - binding.register(mJSContext, uiManager, eventBeatManager, jsMessageQueueThread, - mComponentFactoryDelegate, mConfig); + binding.register( + mJSContext, + uiManager, + eventBeatManager, + jsMessageQueueThread, + mComponentFactoryDelegate, + mConfig); Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); return uiManager; } diff --git a/ReactAndroid/src/main/java/com/facebook/react/fabric/FabricUIManager.java b/ReactAndroid/src/main/java/com/facebook/react/fabric/FabricUIManager.java index 362903d1deb..ec8d51fcf24 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/fabric/FabricUIManager.java +++ b/ReactAndroid/src/main/java/com/facebook/react/fabric/FabricUIManager.java @@ -74,8 +74,10 @@ import java.util.concurrent.ConcurrentHashMap; public class FabricUIManager implements UIManager, LifecycleEventListener { public static final String TAG = FabricUIManager.class.getSimpleName(); - public static final boolean DEBUG = ReactFeatureFlags.enableFabricLogs || - PrinterHolder.getPrinter().shouldDisplayLogMessage(ReactDebugOverlayTags.FABRIC_UI_MANAGER); + public static final boolean DEBUG = + ReactFeatureFlags.enableFabricLogs + || PrinterHolder.getPrinter() + .shouldDisplayLogMessage(ReactDebugOverlayTags.FABRIC_UI_MANAGER); private static final int FRAME_TIME_MS = 16; private static final int MAX_TIME_IN_FRAME_FOR_NON_BATCHED_OPERATIONS_MS = 8; private static final int PRE_MOUNT_ITEMS_INITIAL_SIZE_ARRAY = 250; @@ -130,9 +132,9 @@ public class FabricUIManager implements UIManager, LifecycleEventListener { @Override public int addRootView( - final T rootView, final WritableMap initialProps, final @Nullable String initialUITemplate) { + final T rootView, final WritableMap initialProps, final @Nullable String initialUITemplate) { final int rootTag = ReactRootViewTagGenerator.getNextRootViewTag(); - //TODO T31905686: Refactor both addRootView methods into one method + // TODO T31905686: Refactor both addRootView methods into one method ThemedReactContext reactContext = new ThemedReactContext(mReactApplicationContext, rootView.getContext()); mMountingManager.addRootView(rootTag, rootView); @@ -149,7 +151,11 @@ public class FabricUIManager implements UIManager, LifecycleEventListener { } public int addRootView( - final T rootView, final String moduleName, final WritableMap initialProps, int widthMeasureSpec, int heightMeasureSpec) { + final T rootView, + final String moduleName, + final WritableMap initialProps, + int widthMeasureSpec, + int heightMeasureSpec) { final int rootTag = ReactRootViewTagGenerator.getNextRootViewTag(); ThemedReactContext reactContext = new ThemedReactContext(mReactApplicationContext, rootView.getContext()); @@ -195,7 +201,7 @@ public class FabricUIManager implements UIManager, LifecycleEventListener { @Override public void onCatalystInstanceDestroy() { if (DEBUG) { - FLog.d(TAG, "Destroying Catalyst Instance" ); + FLog.d(TAG, "Destroying Catalyst Instance"); } mEventDispatcher.removeBatchEventDispatchedListener(mEventBeatManager); mEventDispatcher.unregisterEventEmitter(FABRIC); @@ -230,7 +236,7 @@ public class FabricUIManager implements UIManager, LifecycleEventListener { @DoNotStrip @SuppressWarnings("unused") private MountItem createMountItem( - String componentName, int reactRootTag, int reactTag, boolean isLayoutable) { + String componentName, int reactRootTag, int reactTag, boolean isLayoutable) { String component = getFabricComponentName(componentName); ThemedReactContext reactContext = mReactContextForRootTag.get(reactRootTag); if (reactContext == null) { @@ -440,17 +446,18 @@ public class FabricUIManager implements UIManager, LifecycleEventListener { FLog.d(TAG, "Updating Root Layout Specs"); } - mReactApplicationContext.runOnJSQueueThread(new Runnable() { - @Override - public void run() { - mBinding.setConstraints( - rootTag, - getMinSize(widthMeasureSpec), - getMaxSize(widthMeasureSpec), - getMinSize(heightMeasureSpec), - getMaxSize(heightMeasureSpec)); - } - }); + mReactApplicationContext.runOnJSQueueThread( + new Runnable() { + @Override + public void run() { + mBinding.setConstraints( + rootTag, + getMinSize(widthMeasureSpec), + getMaxSize(widthMeasureSpec), + getMinSize(heightMeasureSpec), + getMaxSize(heightMeasureSpec)); + } + }); } public void receiveEvent(int reactTag, String eventName, @Nullable WritableMap params) { @@ -489,7 +496,7 @@ public class FabricUIManager implements UIManager, LifecycleEventListener { @Override public void dispatchCommand( - final int reactTag, final String commandId, @Nullable final ReadableArray commandArgs) { + final int reactTag, final String commandId, @Nullable final ReadableArray commandArgs) { synchronized (mMountItemsLock) { mMountItems.add(new DispatchStringCommandMountItem(reactTag, commandId, commandArgs)); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/fabric/ReactNativeConfig.java b/ReactAndroid/src/main/java/com/facebook/react/fabric/ReactNativeConfig.java index a6f57f7d065..7ce8d53b518 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/fabric/ReactNativeConfig.java +++ b/ReactAndroid/src/main/java/com/facebook/react/fabric/ReactNativeConfig.java @@ -1,8 +1,8 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ package com.facebook.react.fabric; diff --git a/ReactAndroid/src/main/java/com/facebook/react/fabric/StateWrapperImpl.java b/ReactAndroid/src/main/java/com/facebook/react/fabric/StateWrapperImpl.java index a938af35e97..69a94b2c588 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/fabric/StateWrapperImpl.java +++ b/ReactAndroid/src/main/java/com/facebook/react/fabric/StateWrapperImpl.java @@ -32,10 +32,13 @@ public class StateWrapperImpl implements StateWrapper { mHybridData = initHybrid(); } - @Override public native ReadableNativeMap getState(); + @Override + public native ReadableNativeMap getState(); + public native void updateStateImpl(NativeMap map); - @Override public void updateState(WritableMap map) { - updateStateImpl((NativeMap)map); + @Override + public void updateState(WritableMap map) { + updateStateImpl((NativeMap) map); } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/ContextBasedViewPool.java b/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/ContextBasedViewPool.java index 3265d6e9577..3a3057629d8 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/ContextBasedViewPool.java +++ b/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/ContextBasedViewPool.java @@ -24,7 +24,6 @@ public final class ContextBasedViewPool implements ViewFactory { mViewManagerRegistry = viewManagerRegistry; } - @UiThread void createView(ThemedReactContext context, ReactStylesDiffMap props, String componentName) { getViewPool(context).createView(componentName, props, null, context); @@ -32,7 +31,11 @@ public final class ContextBasedViewPool implements ViewFactory { @UiThread @Override - public View getOrCreateView(String componentName, ReactStylesDiffMap props, StateWrapper stateWrapper, ThemedReactContext context) { + public View getOrCreateView( + String componentName, + ReactStylesDiffMap props, + StateWrapper stateWrapper, + ThemedReactContext context) { return getViewPool(context).getOrCreateView(componentName, props, stateWrapper, context); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/MountingManager.java b/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/MountingManager.java index 4e671aa1c51..16ceee84747 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/MountingManager.java +++ b/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/MountingManager.java @@ -204,7 +204,9 @@ public class MountingManager { if (isLayoutable) { viewManager = mViewManagerRegistry.get(componentName); - view = mViewFactory.getOrCreateView(componentName, propsDiffMap, stateWrapper, themedReactContext); + view = + mViewFactory.getOrCreateView( + componentName, propsDiffMap, stateWrapper, themedReactContext); view.setId(reactTag); if (stateWrapper != null) { viewManager.updateState(view, stateWrapper); diff --git a/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/ViewFactory.java b/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/ViewFactory.java index 086e143b16d..073e7cd9db5 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/ViewFactory.java +++ b/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/ViewFactory.java @@ -1,8 +1,8 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ package com.facebook.react.fabric.mounting; @@ -14,8 +14,11 @@ import javax.annotation.Nullable; public interface ViewFactory { - View getOrCreateView(String componentName, @Nullable ReactStylesDiffMap props, @Nullable StateWrapper stateWrapper, ThemedReactContext context); + View getOrCreateView( + String componentName, + @Nullable ReactStylesDiffMap props, + @Nullable StateWrapper stateWrapper, + ThemedReactContext context); void recycle(ThemedReactContext context, String componentName, View view); - } diff --git a/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/ViewManagerFactory.java b/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/ViewManagerFactory.java index 3e9236263ec..78766965b72 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/ViewManagerFactory.java +++ b/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/ViewManagerFactory.java @@ -1,13 +1,13 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ package com.facebook.react.fabric.mounting; -import androidx.annotation.UiThread; import android.view.View; +import androidx.annotation.UiThread; import com.facebook.react.uimanager.ReactStylesDiffMap; import com.facebook.react.uimanager.StateWrapper; import com.facebook.react.uimanager.ThemedReactContext; @@ -25,7 +25,10 @@ public class ViewManagerFactory implements ViewFactory { @UiThread @Override public View getOrCreateView( - String componentName, @Nullable ReactStylesDiffMap props, @Nullable StateWrapper stateWrapper, ThemedReactContext context) { + String componentName, + @Nullable ReactStylesDiffMap props, + @Nullable StateWrapper stateWrapper, + ThemedReactContext context) { return mViewManagerRegistry.get(componentName).createView(context, props, stateWrapper, null); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/ViewPool.java b/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/ViewPool.java index 4fc769aec83..efdb8fa30dd 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/ViewPool.java +++ b/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/ViewPool.java @@ -6,8 +6,8 @@ */ package com.facebook.react.fabric.mounting; -import androidx.annotation.UiThread; import android.view.View; +import androidx.annotation.UiThread; import com.facebook.react.common.ClearableSynchronizedPool; import com.facebook.react.uimanager.ReactStylesDiffMap; import com.facebook.react.uimanager.StateWrapper; @@ -27,7 +27,11 @@ public final class ViewPool { } @UiThread - void createView(String componentName, ReactStylesDiffMap props, StateWrapper stateWrapper, ThemedReactContext context) { + void createView( + String componentName, + ReactStylesDiffMap props, + StateWrapper stateWrapper, + ThemedReactContext context) { ClearableSynchronizedPool viewPool = getViewPoolForComponent(componentName); ViewManager viewManager = mViewManagerRegistry.get(componentName); // TODO: T31905686 Integrate / re-implement jsResponder @@ -36,7 +40,11 @@ public final class ViewPool { } @UiThread - View getOrCreateView(String componentName, ReactStylesDiffMap props, StateWrapper stateWrapper, ThemedReactContext context) { + View getOrCreateView( + String componentName, + ReactStylesDiffMap props, + StateWrapper stateWrapper, + ThemedReactContext context) { ClearableSynchronizedPool viewPool = getViewPoolForComponent(componentName); View view = viewPool.acquire(); if (view == null) { diff --git a/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/mountitems/BatchMountItem.java b/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/mountitems/BatchMountItem.java index 7a0000b260c..21381aad8c3 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/mountitems/BatchMountItem.java +++ b/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/mountitems/BatchMountItem.java @@ -9,12 +9,11 @@ package com.facebook.react.fabric.mounting.mountitems; import static com.facebook.react.fabric.FabricUIManager.DEBUG; import static com.facebook.react.fabric.FabricUIManager.TAG; +import com.facebook.common.logging.FLog; import com.facebook.proguard.annotations.DoNotStrip; import com.facebook.react.fabric.mounting.MountingManager; import com.facebook.systrace.Systrace; -import com.facebook.common.logging.FLog; - /** * This class represents a batch of {@link MountItem}s * diff --git a/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/mountitems/CreateMountItem.java b/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/mountitems/CreateMountItem.java index 980e7800cfe..31ea2fbeace 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/mountitems/CreateMountItem.java +++ b/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/mountitems/CreateMountItem.java @@ -1,8 +1,8 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ package com.facebook.react.fabric.mounting.mountitems; @@ -18,11 +18,11 @@ public class CreateMountItem implements MountItem { private final boolean mIsLayoutable; public CreateMountItem( - ThemedReactContext context, - int rootTag, - int reactTag, - String component, - boolean isLayoutable) { + ThemedReactContext context, + int rootTag, + int reactTag, + String component, + boolean isLayoutable) { mContext = context; mComponent = component; mRootTag = rootTag; @@ -40,4 +40,3 @@ public class CreateMountItem implements MountItem { return "CreateMountItem [" + mReactTag + "]"; } } - diff --git a/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/mountitems/DispatchCommandMountItem.java b/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/mountitems/DispatchCommandMountItem.java index a081d0813f6..4a1e504ef29 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/mountitems/DispatchCommandMountItem.java +++ b/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/mountitems/DispatchCommandMountItem.java @@ -7,9 +7,8 @@ package com.facebook.react.fabric.mounting.mountitems; import androidx.annotation.Nullable; -import com.facebook.react.fabric.mounting.MountingManager; import com.facebook.react.bridge.ReadableArray; -import com.facebook.react.bridge.UiThreadUtil; +import com.facebook.react.fabric.mounting.MountingManager; public class DispatchCommandMountItem implements MountItem { diff --git a/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/mountitems/DispatchStringCommandMountItem.java b/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/mountitems/DispatchStringCommandMountItem.java index 32668becaea..3c04dbaf703 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/mountitems/DispatchStringCommandMountItem.java +++ b/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/mountitems/DispatchStringCommandMountItem.java @@ -7,9 +7,8 @@ package com.facebook.react.fabric.mounting.mountitems; import androidx.annotation.Nullable; -import com.facebook.react.fabric.mounting.MountingManager; import com.facebook.react.bridge.ReadableArray; -import com.facebook.react.bridge.UiThreadUtil; +import com.facebook.react.fabric.mounting.MountingManager; public class DispatchStringCommandMountItem implements MountItem { diff --git a/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/mountitems/PreAllocateViewMountItem.java b/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/mountitems/PreAllocateViewMountItem.java index 00d0f65c009..5853ee4c50f 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/mountitems/PreAllocateViewMountItem.java +++ b/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/mountitems/PreAllocateViewMountItem.java @@ -49,7 +49,8 @@ public class PreAllocateViewMountItem implements MountItem { if (DEBUG) { FLog.d(TAG, "Executing pre-allocation of: " + toString()); } - mountingManager.preallocateView(mContext, mComponent, mReactTag, mProps, mStateWrapper, mIsLayoutable); + mountingManager.preallocateView( + mContext, mComponent, mReactTag, mProps, mStateWrapper, mIsLayoutable); } @Override diff --git a/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/mountitems/UpdateLocalDataMountItem.java b/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/mountitems/UpdateLocalDataMountItem.java index 0786e8f6138..06c8ecf3063 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/mountitems/UpdateLocalDataMountItem.java +++ b/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/mountitems/UpdateLocalDataMountItem.java @@ -6,8 +6,8 @@ */ package com.facebook.react.fabric.mounting.mountitems; -import com.facebook.react.fabric.mounting.MountingManager; import com.facebook.react.bridge.ReadableMap; +import com.facebook.react.fabric.mounting.MountingManager; public class UpdateLocalDataMountItem implements MountItem { diff --git a/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/mountitems/UpdatePropsMountItem.java b/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/mountitems/UpdatePropsMountItem.java index 62a64342efc..8d16d9ef349 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/mountitems/UpdatePropsMountItem.java +++ b/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/mountitems/UpdatePropsMountItem.java @@ -6,8 +6,8 @@ */ package com.facebook.react.fabric.mounting.mountitems; -import com.facebook.react.fabric.mounting.MountingManager; import com.facebook.react.bridge.ReadableMap; +import com.facebook.react.fabric.mounting.MountingManager; public class UpdatePropsMountItem implements MountItem { diff --git a/ReactAndroid/src/main/java/com/facebook/react/jscexecutor/JSCExecutor.java b/ReactAndroid/src/main/java/com/facebook/react/jscexecutor/JSCExecutor.java index 857f87e749b..5674f1bcd08 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/jscexecutor/JSCExecutor.java +++ b/ReactAndroid/src/main/java/com/facebook/react/jscexecutor/JSCExecutor.java @@ -4,7 +4,6 @@ *

This source code is licensed under the MIT license found in the LICENSE file in the root * directory of this source tree. */ - package com.facebook.react.jscexecutor; import com.facebook.jni.HybridData; diff --git a/ReactAndroid/src/main/java/com/facebook/react/jstasks/HeadlessJsTaskConfig.java b/ReactAndroid/src/main/java/com/facebook/react/jstasks/HeadlessJsTaskConfig.java index 1c441300ba1..4b95635e921 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/jstasks/HeadlessJsTaskConfig.java +++ b/ReactAndroid/src/main/java/com/facebook/react/jstasks/HeadlessJsTaskConfig.java @@ -7,9 +7,7 @@ package com.facebook.react.jstasks; import com.facebook.react.bridge.WritableMap; -/** - * Class that holds the various parameters needed to start a JS task. - */ +/** Class that holds the various parameters needed to start a JS task. */ public class HeadlessJsTaskConfig { private final String mTaskKey; private final WritableMap mData; @@ -18,18 +16,17 @@ public class HeadlessJsTaskConfig { private final HeadlessJsTaskRetryPolicy mRetryPolicy; /** - * Create a HeadlessJsTaskConfig. Equivalent to calling - * {@link #HeadlessJsTaskConfig(String, WritableMap, long, boolean)} with no timeout (0) and - * {@code false} for {@code allowedInBackground}. + * Create a HeadlessJsTaskConfig. Equivalent to calling {@link #HeadlessJsTaskConfig(String, + * WritableMap, long, boolean)} with no timeout (0) and {@code false} for {@code + * allowedInBackground}. */ public HeadlessJsTaskConfig(String taskKey, WritableMap data) { this(taskKey, data, 0, false); } /** - * Create a HeadlessJsTaskConfig. Equivalent to calling - * {@link #HeadlessJsTaskConfig(String, WritableMap, long, boolean)} with {@code false} for - * {@code allowedInBackground}. + * Create a HeadlessJsTaskConfig. Equivalent to calling {@link #HeadlessJsTaskConfig(String, + * WritableMap, long, boolean)} with {@code false} for {@code allowedInBackground}. */ public HeadlessJsTaskConfig(String taskKey, WritableMap data, long timeout) { this(taskKey, data, timeout, false); @@ -39,23 +36,20 @@ public class HeadlessJsTaskConfig { * Create a HeadlessJsTaskConfig. * * @param taskKey the key for the JS task to execute. This is the same key that you call {@code - * AppRegistry.registerTask} with in JS. + * AppRegistry.registerTask} with in JS. * @param data a map of parameters passed to the JS task executor. * @param timeout the amount of time (in ms) after which the React instance should be terminated - * regardless of whether the task has completed or not. This is meant as a safeguard against - * accidentally keeping the device awake for long periods of time because JS crashed or some - * request timed out. A value of 0 means no timeout (should only be used for long-running tasks - * such as music playback). + * regardless of whether the task has completed or not. This is meant as a safeguard against + * accidentally keeping the device awake for long periods of time because JS crashed or some + * request timed out. A value of 0 means no timeout (should only be used for long-running + * tasks such as music playback). * @param allowedInForeground whether to allow this task to run while the app is in the foreground - * (i.e. there is a host in resumed mode for the current ReactContext). Only set this to true if - * you really need it. Note that tasks run in the same JS thread as UI code, so doing expensive - * operations would degrade user experience. + * (i.e. there is a host in resumed mode for the current ReactContext). Only set this to true + * if you really need it. Note that tasks run in the same JS thread as UI code, so doing + * expensive operations would degrade user experience. */ public HeadlessJsTaskConfig( - String taskKey, - WritableMap data, - long timeout, - boolean allowedInForeground) { + String taskKey, WritableMap data, long timeout, boolean allowedInForeground) { this(taskKey, data, timeout, allowedInForeground, NoRetryPolicy.INSTANCE); } @@ -63,25 +57,25 @@ public class HeadlessJsTaskConfig { * Create a HeadlessJsTaskConfig. * * @param taskKey the key for the JS task to execute. This is the same key that you call {@code - * AppRegistry.registerTask} with in JS. + * AppRegistry.registerTask} with in JS. * @param data a map of parameters passed to the JS task executor. * @param timeout the amount of time (in ms) after which the React instance should be terminated - * regardless of whether the task has completed or not. This is meant as a safeguard against - * accidentally keeping the device awake for long periods of time because JS crashed or some - * request timed out. A value of 0 means no timeout (should only be used for long-running tasks - * such as music playback). + * regardless of whether the task has completed or not. This is meant as a safeguard against + * accidentally keeping the device awake for long periods of time because JS crashed or some + * request timed out. A value of 0 means no timeout (should only be used for long-running + * tasks such as music playback). * @param allowedInForeground whether to allow this task to run while the app is in the foreground - * (i.e. there is a host in resumed mode for the current ReactContext). Only set this to true if - * you really need it. Note that tasks run in the same JS thread as UI code, so doing expensive - * operations would degrade user experience. + * (i.e. there is a host in resumed mode for the current ReactContext). Only set this to true + * if you really need it. Note that tasks run in the same JS thread as UI code, so doing + * expensive operations would degrade user experience. * @param retryPolicy the number of times & delays the task should be retried on error. */ public HeadlessJsTaskConfig( - String taskKey, - WritableMap data, - long timeout, - boolean allowedInForeground, - HeadlessJsTaskRetryPolicy retryPolicy) { + String taskKey, + WritableMap data, + long timeout, + boolean allowedInForeground, + HeadlessJsTaskRetryPolicy retryPolicy) { mTaskKey = taskKey; mData = data; mTimeout = timeout; diff --git a/ReactAndroid/src/main/java/com/facebook/react/jstasks/HeadlessJsTaskContext.java b/ReactAndroid/src/main/java/com/facebook/react/jstasks/HeadlessJsTaskContext.java index e69505f396a..4ed741d329f 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/jstasks/HeadlessJsTaskContext.java +++ b/ReactAndroid/src/main/java/com/facebook/react/jstasks/HeadlessJsTaskContext.java @@ -7,13 +7,11 @@ package com.facebook.react.jstasks; import android.os.Handler; import android.util.SparseArray; - import com.facebook.infer.annotation.Assertions; import com.facebook.react.bridge.ReactContext; import com.facebook.react.bridge.UiThreadUtil; import com.facebook.react.common.LifecycleState; import com.facebook.react.modules.appregistry.AppRegistry; - import java.lang.ref.WeakReference; import java.util.Map; import java.util.Set; @@ -29,14 +27,14 @@ import java.util.concurrent.atomic.AtomicInteger; public class HeadlessJsTaskContext { private static final WeakHashMap INSTANCES = - new WeakHashMap<>(); + new WeakHashMap<>(); /** * Get the task helper instance for a particular {@link ReactContext}. There is only one instance * per context. - *

- * Note: do not hold long-lived references to the object returned here, as that - * will cause memory leaks. Instead, just call this method on-demand. + * + *

Note: do not hold long-lived references to the object returned here, as + * that will cause memory leaks. Instead, just call this method on-demand. */ public static HeadlessJsTaskContext getInstance(ReactContext context) { HeadlessJsTaskContext helper = INSTANCES.get(context); @@ -49,7 +47,7 @@ public class HeadlessJsTaskContext { private final WeakReference mReactContext; private final Set mHeadlessJsTaskEventListeners = - new CopyOnWriteArraySet<>(); + new CopyOnWriteArraySet<>(); private final AtomicInteger mLastTaskId = new AtomicInteger(0); private final Handler mHandler = new Handler(); private final Set mActiveTasks = new CopyOnWriteArraySet<>(); @@ -60,23 +58,17 @@ public class HeadlessJsTaskContext { mReactContext = new WeakReference(reactContext); } - /** - * Register a task lifecycle event listener. - */ + /** Register a task lifecycle event listener. */ public void addTaskEventListener(HeadlessJsTaskEventListener listener) { mHeadlessJsTaskEventListeners.add(listener); } - /** - * Unregister a task lifecycle event listener. - */ + /** Unregister a task lifecycle event listener. */ public void removeTaskEventListener(HeadlessJsTaskEventListener listener) { mHeadlessJsTaskEventListeners.remove(listener); } - /** - * Get whether there are any running JS tasks at the moment. - */ + /** Get whether there are any running JS tasks at the moment. */ public boolean hasActiveTasks() { return mActiveTasks.size() > 0; } @@ -99,19 +91,22 @@ public class HeadlessJsTaskContext { */ private synchronized void startTask(final HeadlessJsTaskConfig taskConfig, int taskId) { UiThreadUtil.assertOnUiThread(); - ReactContext reactContext = Assertions.assertNotNull( - mReactContext.get(), - "Tried to start a task on a react context that has already been destroyed"); - if (reactContext.getLifecycleState() == LifecycleState.RESUMED && - !taskConfig.isAllowedInForeground()) { + ReactContext reactContext = + Assertions.assertNotNull( + mReactContext.get(), + "Tried to start a task on a react context that has already been destroyed"); + if (reactContext.getLifecycleState() == LifecycleState.RESUMED + && !taskConfig.isAllowedInForeground()) { throw new IllegalStateException( - "Tried to start task " + taskConfig.getTaskKey() + - " while in foreground, but this is not allowed."); + "Tried to start task " + + taskConfig.getTaskKey() + + " while in foreground, but this is not allowed."); } mActiveTasks.add(taskId); mActiveTaskConfigs.put(taskId, new HeadlessJsTaskConfig(taskConfig)); - reactContext.getJSModule(AppRegistry.class) - .startHeadlessTask(taskId, taskConfig.getTaskKey(), taskConfig.getData()); + reactContext + .getJSModule(AppRegistry.class) + .startHeadlessTask(taskId, taskConfig.getTaskKey(), taskConfig.getData()); if (taskConfig.getTimeout() > 0) { scheduleTaskTimeout(taskId, taskConfig.getTimeout()); } @@ -121,17 +116,17 @@ public class HeadlessJsTaskContext { } /** - * Retry a running JS task with a delay. Invokes - * {@link HeadlessJsTaskContext#startTask(HeadlessJsTaskConfig, int)} as long as the process does - * not get killed. + * Retry a running JS task with a delay. Invokes {@link + * HeadlessJsTaskContext#startTask(HeadlessJsTaskConfig, int)} as long as the process does not get + * killed. * * @return true if a retry attempt has been posted. */ public synchronized boolean retryTask(final int taskId) { final HeadlessJsTaskConfig sourceTaskConfig = mActiveTaskConfigs.get(taskId); Assertions.assertCondition( - sourceTaskConfig != null, - "Tried to retrieve non-existent task config with id " + taskId + "."); + sourceTaskConfig != null, + "Tried to retrieve non-existent task config with id " + taskId + "."); final HeadlessJsTaskRetryPolicy retryPolicy = sourceTaskConfig.getRetryPolicy(); if (!retryPolicy.canRetry()) { @@ -139,20 +134,21 @@ public class HeadlessJsTaskContext { } removeTimeout(taskId); - final HeadlessJsTaskConfig taskConfig = new HeadlessJsTaskConfig( + final HeadlessJsTaskConfig taskConfig = + new HeadlessJsTaskConfig( sourceTaskConfig.getTaskKey(), sourceTaskConfig.getData(), sourceTaskConfig.getTimeout(), sourceTaskConfig.isAllowedInForeground(), - retryPolicy.update() - ); + retryPolicy.update()); - final Runnable retryAttempt = new Runnable() { - @Override - public void run() { - startTask(taskConfig, taskId); - } - }; + final Runnable retryAttempt = + new Runnable() { + @Override + public void run() { + startTask(taskConfig, taskId); + } + }; UiThreadUtil.runOnUiThread(retryAttempt, retryPolicy.getDelay()); return true; @@ -166,20 +162,20 @@ public class HeadlessJsTaskContext { */ public synchronized void finishTask(final int taskId) { Assertions.assertCondition( - mActiveTasks.remove(taskId), - "Tried to finish non-existent task with id " + taskId + "."); + mActiveTasks.remove(taskId), "Tried to finish non-existent task with id " + taskId + "."); Assertions.assertCondition( - mActiveTaskConfigs.remove(taskId) != null, - "Tried to remove non-existent task config with id " + taskId + "."); + mActiveTaskConfigs.remove(taskId) != null, + "Tried to remove non-existent task config with id " + taskId + "."); removeTimeout(taskId); - UiThreadUtil.runOnUiThread(new Runnable() { - @Override - public void run() { - for (HeadlessJsTaskEventListener listener : mHeadlessJsTaskEventListeners) { - listener.onHeadlessJsTaskFinish(taskId); - } - } - }); + UiThreadUtil.runOnUiThread( + new Runnable() { + @Override + public void run() { + for (HeadlessJsTaskEventListener listener : mHeadlessJsTaskEventListeners) { + listener.onHeadlessJsTaskFinish(taskId); + } + } + }); } private void removeTimeout(int taskId) { @@ -199,12 +195,13 @@ public class HeadlessJsTaskContext { } private void scheduleTaskTimeout(final int taskId, long timeout) { - Runnable runnable = new Runnable() { - @Override - public void run() { - finishTask(taskId); - } - }; + Runnable runnable = + new Runnable() { + @Override + public void run() { + finishTask(taskId); + } + }; mTaskTimeouts.append(taskId, runnable); mHandler.postDelayed(runnable, timeout); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/jstasks/HeadlessJsTaskEventListener.java b/ReactAndroid/src/main/java/com/facebook/react/jstasks/HeadlessJsTaskEventListener.java index 420abed320e..165a302f9b6 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/jstasks/HeadlessJsTaskEventListener.java +++ b/ReactAndroid/src/main/java/com/facebook/react/jstasks/HeadlessJsTaskEventListener.java @@ -1,15 +1,12 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.jstasks; -/** - * Listener interface for task lifecycle events. - */ +/** Listener interface for task lifecycle events. */ public interface HeadlessJsTaskEventListener { /** @@ -20,9 +17,9 @@ public interface HeadlessJsTaskEventListener { void onHeadlessJsTaskStart(int taskId); /** - * Called when a JS task finishes (i.e. when - * {@link HeadlessJsTaskSupportModule#notifyTaskFinished} is called, or when it times out), on the - * UI thread. + * Called when a JS task finishes (i.e. when {@link + * HeadlessJsTaskSupportModule#notifyTaskFinished} is called, or when it times out), on the UI + * thread. */ void onHeadlessJsTaskFinish(int taskId); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/jstasks/HeadlessJsTaskRetryPolicy.java b/ReactAndroid/src/main/java/com/facebook/react/jstasks/HeadlessJsTaskRetryPolicy.java index 215f5b8b44c..c65c92f7637 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/jstasks/HeadlessJsTaskRetryPolicy.java +++ b/ReactAndroid/src/main/java/com/facebook/react/jstasks/HeadlessJsTaskRetryPolicy.java @@ -4,13 +4,12 @@ import javax.annotation.CheckReturnValue; public interface HeadlessJsTaskRetryPolicy { - boolean canRetry(); + boolean canRetry(); - int getDelay(); + int getDelay(); - @CheckReturnValue - HeadlessJsTaskRetryPolicy update(); - - HeadlessJsTaskRetryPolicy copy(); + @CheckReturnValue + HeadlessJsTaskRetryPolicy update(); + HeadlessJsTaskRetryPolicy copy(); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/jstasks/LinearCountingRetryPolicy.java b/ReactAndroid/src/main/java/com/facebook/react/jstasks/LinearCountingRetryPolicy.java index b319d35435e..ae86b2447c7 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/jstasks/LinearCountingRetryPolicy.java +++ b/ReactAndroid/src/main/java/com/facebook/react/jstasks/LinearCountingRetryPolicy.java @@ -2,37 +2,37 @@ package com.facebook.react.jstasks; public class LinearCountingRetryPolicy implements HeadlessJsTaskRetryPolicy { - private final int mRetryAttempts; - private final int mDelayBetweenAttemptsInMs; + private final int mRetryAttempts; + private final int mDelayBetweenAttemptsInMs; - public LinearCountingRetryPolicy(int retryAttempts, int delayBetweenAttemptsInMs) { - mRetryAttempts = retryAttempts; - mDelayBetweenAttemptsInMs = delayBetweenAttemptsInMs; + public LinearCountingRetryPolicy(int retryAttempts, int delayBetweenAttemptsInMs) { + mRetryAttempts = retryAttempts; + mDelayBetweenAttemptsInMs = delayBetweenAttemptsInMs; + } + + @Override + public boolean canRetry() { + return mRetryAttempts > 0; + } + + @Override + public int getDelay() { + return mDelayBetweenAttemptsInMs; + } + + @Override + public HeadlessJsTaskRetryPolicy update() { + final int remainingRetryAttempts = mRetryAttempts - 1; + + if (remainingRetryAttempts > 0) { + return new LinearCountingRetryPolicy(remainingRetryAttempts, mDelayBetweenAttemptsInMs); + } else { + return NoRetryPolicy.INSTANCE; } + } - @Override - public boolean canRetry() { - return mRetryAttempts > 0; - } - - @Override - public int getDelay() { - return mDelayBetweenAttemptsInMs; - } - - @Override - public HeadlessJsTaskRetryPolicy update() { - final int remainingRetryAttempts = mRetryAttempts - 1; - - if (remainingRetryAttempts > 0) { - return new LinearCountingRetryPolicy(remainingRetryAttempts, mDelayBetweenAttemptsInMs); - } else { - return NoRetryPolicy.INSTANCE; - } - } - - @Override - public HeadlessJsTaskRetryPolicy copy() { - return new LinearCountingRetryPolicy(mRetryAttempts, mDelayBetweenAttemptsInMs); - } + @Override + public HeadlessJsTaskRetryPolicy copy() { + return new LinearCountingRetryPolicy(mRetryAttempts, mDelayBetweenAttemptsInMs); + } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/jstasks/NoRetryPolicy.java b/ReactAndroid/src/main/java/com/facebook/react/jstasks/NoRetryPolicy.java index ac707ab70d7..60cd2f52599 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/jstasks/NoRetryPolicy.java +++ b/ReactAndroid/src/main/java/com/facebook/react/jstasks/NoRetryPolicy.java @@ -2,29 +2,28 @@ package com.facebook.react.jstasks; public class NoRetryPolicy implements HeadlessJsTaskRetryPolicy { - public static final NoRetryPolicy INSTANCE = new NoRetryPolicy(); + public static final NoRetryPolicy INSTANCE = new NoRetryPolicy(); - private NoRetryPolicy() { - } + private NoRetryPolicy() {} - @Override - public boolean canRetry() { - return false; - } + @Override + public boolean canRetry() { + return false; + } - @Override - public int getDelay() { - throw new IllegalStateException("Should not retrieve delay as canRetry is: " + canRetry()); - } + @Override + public int getDelay() { + throw new IllegalStateException("Should not retrieve delay as canRetry is: " + canRetry()); + } - @Override - public HeadlessJsTaskRetryPolicy update() { - throw new IllegalStateException("Should not update as canRetry is: " + canRetry()); - } + @Override + public HeadlessJsTaskRetryPolicy update() { + throw new IllegalStateException("Should not update as canRetry is: " + canRetry()); + } - @Override - public HeadlessJsTaskRetryPolicy copy() { - // Class is immutable so no need to copy - return this; - } + @Override + public HeadlessJsTaskRetryPolicy copy() { + // Class is immutable so no need to copy + return this; + } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/module/annotations/ReactModule.java b/ReactAndroid/src/main/java/com/facebook/react/module/annotations/ReactModule.java index 3ff3a56fba4..9fde7acf4b6 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/module/annotations/ReactModule.java +++ b/ReactAndroid/src/main/java/com/facebook/react/module/annotations/ReactModule.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.module.annotations; import static java.lang.annotation.ElementType.TYPE; @@ -14,37 +13,35 @@ import java.lang.annotation.Retention; import java.lang.annotation.Target; /** - * Annotation for use on {@link com.facebook.react.bridge.BaseJavaModule}s to describe properties for that module. + * Annotation for use on {@link com.facebook.react.bridge.BaseJavaModule}s to describe properties + * for that module. */ @Retention(RUNTIME) @Target(TYPE) public @interface ReactModule { - /** - * Name used to {@code require()} this module from JavaScript. - */ + /** Name used to {@code require()} this module from JavaScript. */ String name(); /** - * True if you intend to override some other native module that was registered e.g. as part - * of a different package (such as the core one). Trying to override without returning true from - * this method is considered an error and will throw an exception during initialization. By - * default all modules return false. + * True if you intend to override some other native module that was registered e.g. as part of a + * different package (such as the core one). Trying to override without returning true from this + * method is considered an error and will throw an exception during initialization. By default all + * modules return false. */ boolean canOverrideExistingModule() default false; - /** - * Whether this module needs to be loaded immediately. - */ + /** Whether this module needs to be loaded immediately. */ boolean needsEagerInit() default false; /** - * Whether this module has constants to add, defaults to true as that is safer for when a - * correct annotation is not included + * Whether this module has constants to add, defaults to true as that is safer for when a correct + * annotation is not included */ boolean hasConstants() default true; /** * Indicates if a module is a C++ module or a Java Module + * * @return */ boolean isCxxModule() default false; diff --git a/ReactAndroid/src/main/java/com/facebook/react/module/annotations/ReactModuleList.java b/ReactAndroid/src/main/java/com/facebook/react/module/annotations/ReactModuleList.java index d23eb245f93..99310f3c2b4 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/module/annotations/ReactModuleList.java +++ b/ReactAndroid/src/main/java/com/facebook/react/module/annotations/ReactModuleList.java @@ -5,14 +5,13 @@ package com.facebook.react.module.annotations; -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import com.facebook.react.bridge.NativeModule; - import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.SOURCE; +import com.facebook.react.bridge.NativeModule; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + /** * Annotates a function that returns a list of ModuleSpecs from which we get a list of NativeModules * to create ReactModuleInfos from. @@ -23,6 +22,7 @@ public @interface ReactModuleList { /** * The Native modules in this list should be annotated with {@link ReactModule}. + * * @return List of Native modules in the package. */ Class[] nativeModules(); diff --git a/ReactAndroid/src/main/java/com/facebook/react/module/model/ReactModuleInfo.java b/ReactAndroid/src/main/java/com/facebook/react/module/model/ReactModuleInfo.java index 9e2f1cd737d..c9736cab30c 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/module/model/ReactModuleInfo.java +++ b/ReactAndroid/src/main/java/com/facebook/react/module/model/ReactModuleInfo.java @@ -20,13 +20,13 @@ public class ReactModuleInfo { private final boolean mIsTurboModule; public ReactModuleInfo( - String name, - String className, - boolean canOverrideExistingModule, - boolean needsEagerInit, - boolean hasConstants, - boolean isCxxModule, - boolean isTurboModule) { + String name, + String className, + boolean canOverrideExistingModule, + boolean needsEagerInit, + boolean hasConstants, + boolean isCxxModule, + boolean isTurboModule) { mName = name; mClassName = className; mCanOverrideExistingModule = canOverrideExistingModule; @@ -40,7 +40,9 @@ public class ReactModuleInfo { return mName; } - public String className() {return mClassName;} + public String className() { + return mClassName; + } public boolean canOverrideExistingModule() { return mCanOverrideExistingModule; @@ -54,8 +56,11 @@ public class ReactModuleInfo { return mHasConstants; } - public boolean isCxxModule() {return mIsCxxModule; } - - public boolean isTurboModule() {return mIsTurboModule; } + public boolean isCxxModule() { + return mIsCxxModule; + } + public boolean isTurboModule() { + return mIsTurboModule; + } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/module/model/ReactModuleInfoProvider.java b/ReactAndroid/src/main/java/com/facebook/react/module/model/ReactModuleInfoProvider.java index 3d575a1ddf3..72b07847ab3 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/module/model/ReactModuleInfoProvider.java +++ b/ReactAndroid/src/main/java/com/facebook/react/module/model/ReactModuleInfoProvider.java @@ -7,9 +7,7 @@ package com.facebook.react.module.model; import java.util.Map; -/** - * Interface for auto-generated class by ReactModuleSpecProcessor. - */ +/** Interface for auto-generated class by ReactModuleSpecProcessor. */ public interface ReactModuleInfoProvider { Map getReactModuleInfos(); diff --git a/ReactAndroid/src/main/java/com/facebook/react/module/processing/ReactModuleSpecProcessor.java b/ReactAndroid/src/main/java/com/facebook/react/module/processing/ReactModuleSpecProcessor.java index cf0c30b11a9..3115f161295 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/module/processing/ReactModuleSpecProcessor.java +++ b/ReactAndroid/src/main/java/com/facebook/react/module/processing/ReactModuleSpecProcessor.java @@ -27,7 +27,6 @@ import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Optional; import java.util.Set; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.Filer; @@ -46,10 +45,9 @@ import javax.lang.model.type.TypeMirror; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; - /** - * Generates a list of ReactModuleInfo for modules annotated with {@link ReactModule} in - * {@link ReactPackage}s annotated with {@link ReactModuleList}. + * Generates a list of ReactModuleInfo for modules annotated with {@link ReactModule} in {@link + * ReactPackage}s annotated with {@link ReactModuleList}. */ @SupportedAnnotationTypes({ "com.facebook.react.module.annotations.ReactModule", @@ -59,18 +57,13 @@ import javax.lang.model.util.Types; public class ReactModuleSpecProcessor extends AbstractProcessor { private static final TypeName COLLECTIONS_TYPE = ParameterizedTypeName.get(Collections.class); - private static final TypeName MAP_TYPE = ParameterizedTypeName.get( - Map.class, - String.class, - ReactModuleInfo.class); + private static final TypeName MAP_TYPE = + ParameterizedTypeName.get(Map.class, String.class, ReactModuleInfo.class); private static final TypeName INSTANTIATED_MAP_TYPE = ParameterizedTypeName.get(HashMap.class); - @SuppressFieldNotInitialized - private Filer mFiler; - @SuppressFieldNotInitialized - private Elements mElements; - @SuppressFieldNotInitialized - private Messager mMessager; + @SuppressFieldNotInitialized private Filer mFiler; + @SuppressFieldNotInitialized private Elements mElements; + @SuppressFieldNotInitialized private Messager mMessager; private Types mTypes; @Override @@ -85,8 +78,8 @@ public class ReactModuleSpecProcessor extends AbstractProcessor { @Override public boolean process(Set annotations, RoundEnvironment roundEnv) { - Set reactModuleListElements = roundEnv.getElementsAnnotatedWith( - ReactModuleList.class); + Set reactModuleListElements = + roundEnv.getElementsAnnotatedWith(ReactModuleList.class); for (Element reactModuleListElement : reactModuleListElements) { if (!(reactModuleListElement instanceof TypeElement)) { continue; @@ -115,27 +108,29 @@ public class ReactModuleSpecProcessor extends AbstractProcessor { MethodSpec getReactModuleInfosMethod; try { - getReactModuleInfosMethod = MethodSpec.methodBuilder("getReactModuleInfos") - .addAnnotation(Override.class) - .addModifiers(PUBLIC) - .addCode(getCodeBlockForReactModuleInfos(nativeModules)) - .returns(MAP_TYPE) - .build(); + getReactModuleInfosMethod = + MethodSpec.methodBuilder("getReactModuleInfos") + .addAnnotation(Override.class) + .addModifiers(PUBLIC) + .addCode(getCodeBlockForReactModuleInfos(nativeModules)) + .returns(MAP_TYPE) + .build(); } catch (ReactModuleSpecException reactModuleSpecException) { mMessager.printMessage(ERROR, reactModuleSpecException.mMessage); return false; } - TypeSpec reactModulesInfosTypeSpec = TypeSpec.classBuilder( - fileName + "$$ReactModuleInfoProvider") - .addModifiers(Modifier.PUBLIC) - .addMethod(getReactModuleInfosMethod) - .addSuperinterface(ReactModuleInfoProvider.class) - .build(); + TypeSpec reactModulesInfosTypeSpec = + TypeSpec.classBuilder(fileName + "$$ReactModuleInfoProvider") + .addModifiers(Modifier.PUBLIC) + .addMethod(getReactModuleInfosMethod) + .addSuperinterface(ReactModuleInfoProvider.class) + .build(); - JavaFile javaFile = JavaFile.builder(packageName, reactModulesInfosTypeSpec) - .addFileComment("Generated by " + getClass().getName()) - .build(); + JavaFile javaFile = + JavaFile.builder(packageName, reactModulesInfosTypeSpec) + .addFileComment("Generated by " + getClass().getName()) + .build(); try { javaFile.writeTo(mFiler); @@ -148,7 +143,7 @@ public class ReactModuleSpecProcessor extends AbstractProcessor { } private CodeBlock getCodeBlockForReactModuleInfos(List nativeModules) - throws ReactModuleSpecException { + throws ReactModuleSpecException { final CodeBlock.Builder builder = CodeBlock.builder(); if (nativeModules == null || nativeModules.isEmpty()) { builder.addStatement("return $T.emptyMap()", COLLECTIONS_TYPE); @@ -161,46 +156,62 @@ public class ReactModuleSpecProcessor extends AbstractProcessor { TypeElement typeElement = mElements.getTypeElement(nativeModule); if (typeElement == null) { throw new ReactModuleSpecException( - keyString + " not found by ReactModuleSpecProcessor. " + - "Did you misspell the module?"); + keyString + + " not found by ReactModuleSpecProcessor. " + + "Did you misspell the module?"); } ReactModule reactModule = typeElement.getAnnotation(ReactModule.class); if (reactModule == null) { throw new ReactModuleSpecException( - keyString + " not found by ReactModuleSpecProcessor. " + - "Did you forget to add the @ReactModule annotation to the native module?"); + keyString + + " not found by ReactModuleSpecProcessor. " + + "Did you forget to add the @ReactModule annotation to the native module?"); } boolean isTurboModule = isTurboModuleTypeElement(typeElement); if (!isTurboModule) { TypeMirror nativeModuleSpecTypeMirror = typeElement.getSuperclass(); - isTurboModule = isTurboModuleTypeElement(mElements.getTypeElement(nativeModuleSpecTypeMirror.toString())); + isTurboModule = + isTurboModuleTypeElement( + mElements.getTypeElement(nativeModuleSpecTypeMirror.toString())); } List elements = typeElement.getEnclosedElements(); boolean hasConstants = false; if (elements != null) { hasConstants = - elements - .stream() + elements.stream() .filter(element -> element.getKind() == ElementKind.METHOD) .map(Element::getSimpleName) .anyMatch( - name -> name.contentEquals("getConstants") || name.contentEquals("getTypedExportedConstants")); + name -> + name.contentEquals("getConstants") + || name.contentEquals("getTypedExportedConstants")); } - String valueString = new StringBuilder() - .append("new ReactModuleInfo(") - .append("\"").append(reactModule.name()).append("\"").append(", ") - .append("\"").append(keyString).append("\"").append(", ") - .append(reactModule.canOverrideExistingModule()).append(", ") - .append(reactModule.needsEagerInit()).append(", ") - .append(hasConstants).append(", ") - .append(reactModule.isCxxModule()).append(", ") - .append(isTurboModule) - .append(")") - .toString(); + String valueString = + new StringBuilder() + .append("new ReactModuleInfo(") + .append("\"") + .append(reactModule.name()) + .append("\"") + .append(", ") + .append("\"") + .append(keyString) + .append("\"") + .append(", ") + .append(reactModule.canOverrideExistingModule()) + .append(", ") + .append(reactModule.needsEagerInit()) + .append(", ") + .append(hasConstants) + .append(", ") + .append(reactModule.isCxxModule()) + .append(", ") + .append(isTurboModule) + .append(")") + .toString(); builder.addStatement("map.put(\"" + reactModule.name() + "\", " + valueString + ")"); } @@ -210,14 +221,15 @@ public class ReactModuleSpecProcessor extends AbstractProcessor { } /** - * A Module is a Turbo Module if it either implements TurboModule or its super class, - * typically NativeModuleSpec implements TurboMobile + * A Module is a Turbo Module if it either implements TurboModule or its super class, typically + * NativeModuleSpec implements TurboMobile */ private boolean isTurboModuleTypeElement(TypeElement typeElement) { if (typeElement == null) { return false; } - return typeElement.getInterfaces().stream().anyMatch(el -> el.toString().equals(TurboModule.class.getName())); + return typeElement.getInterfaces().stream() + .anyMatch(el -> el.toString().equals(TurboModule.class.getName())); } private static class ReactModuleSpecException extends Exception { diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/accessibilityinfo/AccessibilityInfoModule.java b/ReactAndroid/src/main/java/com/facebook/react/modules/accessibilityinfo/AccessibilityInfoModule.java index 04f2883856b..90058e1a5bf 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/accessibilityinfo/AccessibilityInfoModule.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/accessibilityinfo/AccessibilityInfoModule.java @@ -5,11 +5,9 @@ package com.facebook.react.modules.accessibilityinfo; -import javax.annotation.Nullable; - import android.annotation.TargetApi; -import android.content.Context; import android.content.ContentResolver; +import android.content.Context; import android.database.ContentObserver; import android.net.Uri; import android.os.Build; @@ -18,7 +16,6 @@ import android.os.Looper; import android.provider.Settings; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityManager; - import com.facebook.react.bridge.Callback; import com.facebook.react.bridge.LifecycleEventListener; import com.facebook.react.bridge.ReactApplicationContext; @@ -26,163 +23,167 @@ import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.module.annotations.ReactModule; import com.facebook.react.modules.core.DeviceEventManagerModule; +import javax.annotation.Nullable; /** - * Module that monitors and provides information about the state of Touch Exploration service - * on the device. For API >= 19. + * Module that monitors and provides information about the state of Touch Exploration service on the + * device. For API >= 19. */ @ReactModule(name = AccessibilityInfoModule.NAME) public class AccessibilityInfoModule extends ReactContextBaseJavaModule - implements LifecycleEventListener { + implements LifecycleEventListener { - public static final String NAME = "AccessibilityInfo"; + public static final String NAME = "AccessibilityInfo"; - @TargetApi(Build.VERSION_CODES.KITKAT) - private class ReactTouchExplorationStateChangeListener - implements AccessibilityManager.TouchExplorationStateChangeListener { + @TargetApi(Build.VERSION_CODES.KITKAT) + private class ReactTouchExplorationStateChangeListener + implements AccessibilityManager.TouchExplorationStateChangeListener { - @Override - public void onTouchExplorationStateChanged(boolean enabled) { - updateAndSendTouchExplorationChangeEvent(enabled); - } + @Override + public void onTouchExplorationStateChanged(boolean enabled) { + updateAndSendTouchExplorationChangeEvent(enabled); } + } - // Listener that is notified when the global TRANSITION_ANIMATION_SCALE. - private final ContentObserver animationScaleObserver = new ContentObserver(new Handler(Looper.getMainLooper())) { + // Listener that is notified when the global TRANSITION_ANIMATION_SCALE. + private final ContentObserver animationScaleObserver = + new ContentObserver(new Handler(Looper.getMainLooper())) { @Override public void onChange(boolean selfChange) { - this.onChange(selfChange, null); + this.onChange(selfChange, null); } @Override public void onChange(boolean selfChange, Uri uri) { - if (getReactApplicationContext().hasActiveCatalystInstance()) { - AccessibilityInfoModule.this.updateAndSendReduceMotionChangeEvent(); - } + if (getReactApplicationContext().hasActiveCatalystInstance()) { + AccessibilityInfoModule.this.updateAndSendReduceMotionChangeEvent(); + } } - }; + }; - private @Nullable AccessibilityManager mAccessibilityManager; - private @Nullable ReactTouchExplorationStateChangeListener mTouchExplorationStateChangeListener; - private final ContentResolver mContentResolver; - private boolean mReduceMotionEnabled = false; - private boolean mTouchExplorationEnabled = false; + private @Nullable AccessibilityManager mAccessibilityManager; + private @Nullable ReactTouchExplorationStateChangeListener mTouchExplorationStateChangeListener; + private final ContentResolver mContentResolver; + private boolean mReduceMotionEnabled = false; + private boolean mTouchExplorationEnabled = false; - private static final String REDUCE_MOTION_EVENT_NAME = "reduceMotionDidChange"; - private static final String TOUCH_EXPLORATION_EVENT_NAME = "touchExplorationDidChange"; + private static final String REDUCE_MOTION_EVENT_NAME = "reduceMotionDidChange"; + private static final String TOUCH_EXPLORATION_EVENT_NAME = "touchExplorationDidChange"; - public AccessibilityInfoModule(ReactApplicationContext context) { - super(context); - Context appContext = context.getApplicationContext(); - mAccessibilityManager = (AccessibilityManager) appContext.getSystemService(Context.ACCESSIBILITY_SERVICE); - mContentResolver = getReactApplicationContext().getContentResolver(); - mTouchExplorationEnabled = mAccessibilityManager.isTouchExplorationEnabled(); - mReduceMotionEnabled = this.getIsReduceMotionEnabledValue(); + public AccessibilityInfoModule(ReactApplicationContext context) { + super(context); + Context appContext = context.getApplicationContext(); + mAccessibilityManager = + (AccessibilityManager) appContext.getSystemService(Context.ACCESSIBILITY_SERVICE); + mContentResolver = getReactApplicationContext().getContentResolver(); + mTouchExplorationEnabled = mAccessibilityManager.isTouchExplorationEnabled(); + mReduceMotionEnabled = this.getIsReduceMotionEnabledValue(); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { - mTouchExplorationStateChangeListener = new ReactTouchExplorationStateChangeListener(); - } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { + mTouchExplorationStateChangeListener = new ReactTouchExplorationStateChangeListener(); } + } - @Override - public String getName() { - return "AccessibilityInfo"; - } + @Override + public String getName() { + return "AccessibilityInfo"; + } - private boolean getIsReduceMotionEnabledValue() { - String value = Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1 ? null + private boolean getIsReduceMotionEnabledValue() { + String value = + Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1 + ? null : Settings.Global.getString( - mContentResolver, - Settings.Global.TRANSITION_ANIMATION_SCALE - ); + mContentResolver, Settings.Global.TRANSITION_ANIMATION_SCALE); - return value != null && value.equals("0.0"); + return value != null && value.equals("0.0"); + } + + @ReactMethod + public void isReduceMotionEnabled(Callback successCallback) { + successCallback.invoke(mReduceMotionEnabled); + } + + @ReactMethod + public void isTouchExplorationEnabled(Callback successCallback) { + successCallback.invoke(mTouchExplorationEnabled); + } + + private void updateAndSendReduceMotionChangeEvent() { + boolean isReduceMotionEnabled = this.getIsReduceMotionEnabledValue(); + + if (mReduceMotionEnabled != isReduceMotionEnabled) { + mReduceMotionEnabled = isReduceMotionEnabled; + getReactApplicationContext() + .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) + .emit(REDUCE_MOTION_EVENT_NAME, mReduceMotionEnabled); + } + } + + private void updateAndSendTouchExplorationChangeEvent(boolean enabled) { + if (mTouchExplorationEnabled != enabled) { + mTouchExplorationEnabled = enabled; + getReactApplicationContext() + .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) + .emit(TOUCH_EXPLORATION_EVENT_NAME, mTouchExplorationEnabled); + } + } + + @Override + public void onHostResume() { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { + mAccessibilityManager.addTouchExplorationStateChangeListener( + mTouchExplorationStateChangeListener); } - @ReactMethod - public void isReduceMotionEnabled(Callback successCallback) { - successCallback.invoke(mReduceMotionEnabled); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { + Uri transitionUri = Settings.Global.getUriFor(Settings.Global.TRANSITION_ANIMATION_SCALE); + mContentResolver.registerContentObserver(transitionUri, false, animationScaleObserver); } - @ReactMethod - public void isTouchExplorationEnabled(Callback successCallback) { - successCallback.invoke(mTouchExplorationEnabled); + updateAndSendTouchExplorationChangeEvent(mAccessibilityManager.isTouchExplorationEnabled()); + updateAndSendReduceMotionChangeEvent(); + } + + @Override + public void onHostPause() { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { + mAccessibilityManager.removeTouchExplorationStateChangeListener( + mTouchExplorationStateChangeListener); } - private void updateAndSendReduceMotionChangeEvent() { - boolean isReduceMotionEnabled = this.getIsReduceMotionEnabledValue(); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { + mContentResolver.unregisterContentObserver(animationScaleObserver); + } + } - if (mReduceMotionEnabled != isReduceMotionEnabled) { - mReduceMotionEnabled = isReduceMotionEnabled; - getReactApplicationContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) - .emit(REDUCE_MOTION_EVENT_NAME, mReduceMotionEnabled); - } + @Override + public void initialize() { + getReactApplicationContext().addLifecycleEventListener(this); + updateAndSendTouchExplorationChangeEvent(mAccessibilityManager.isTouchExplorationEnabled()); + updateAndSendReduceMotionChangeEvent(); + } + + @Override + public void onCatalystInstanceDestroy() { + super.onCatalystInstanceDestroy(); + getReactApplicationContext().removeLifecycleEventListener(this); + } + + @Override + public void onHostDestroy() {} + + @ReactMethod + public void announceForAccessibility(String message) { + if (mAccessibilityManager == null || !mAccessibilityManager.isEnabled()) { + return; } - private void updateAndSendTouchExplorationChangeEvent(boolean enabled) { - if (mTouchExplorationEnabled != enabled) { - mTouchExplorationEnabled = enabled; - getReactApplicationContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) - .emit(TOUCH_EXPLORATION_EVENT_NAME, mTouchExplorationEnabled); - } - } + AccessibilityEvent event = AccessibilityEvent.obtain(AccessibilityEvent.TYPE_ANNOUNCEMENT); + event.getText().add(message); + event.setClassName(AccessibilityInfoModule.class.getName()); + event.setPackageName(getReactApplicationContext().getPackageName()); - @Override - public void onHostResume() { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { - mAccessibilityManager.addTouchExplorationStateChangeListener( - mTouchExplorationStateChangeListener); - } - - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { - Uri transitionUri = Settings.Global.getUriFor(Settings.Global.TRANSITION_ANIMATION_SCALE); - mContentResolver.registerContentObserver(transitionUri, false, animationScaleObserver); - } - - updateAndSendTouchExplorationChangeEvent(mAccessibilityManager.isTouchExplorationEnabled()); - updateAndSendReduceMotionChangeEvent(); - } - - @Override - public void onHostPause() { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { - mAccessibilityManager.removeTouchExplorationStateChangeListener( - mTouchExplorationStateChangeListener); - } - - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { - mContentResolver.unregisterContentObserver(animationScaleObserver); - } - } - - @Override - public void initialize() { - getReactApplicationContext().addLifecycleEventListener(this); - updateAndSendTouchExplorationChangeEvent(mAccessibilityManager.isTouchExplorationEnabled()); - updateAndSendReduceMotionChangeEvent(); - } - - @Override - public void onCatalystInstanceDestroy() { - super.onCatalystInstanceDestroy(); - getReactApplicationContext().removeLifecycleEventListener(this); - } - - @Override - public void onHostDestroy() { - } - - @ReactMethod - public void announceForAccessibility(String message) { - if (mAccessibilityManager == null || !mAccessibilityManager.isEnabled()) { - return; - } - - AccessibilityEvent event = AccessibilityEvent.obtain(AccessibilityEvent.TYPE_ANNOUNCEMENT); - event.getText().add(message); - event.setClassName(AccessibilityInfoModule.class.getName()); - event.setPackageName(getReactApplicationContext().getPackageName()); - - mAccessibilityManager.sendAccessibilityEvent(event); - } + mAccessibilityManager.sendAccessibilityEvent(event); + } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/appregistry/AppRegistry.java b/ReactAndroid/src/main/java/com/facebook/react/modules/appregistry/AppRegistry.java index da206630c3f..a431907c8bd 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/appregistry/AppRegistry.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/appregistry/AppRegistry.java @@ -1,21 +1,20 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.appregistry; import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.bridge.WritableMap; -/** - * JS module interface - main entry point for launching React application for a given key. - */ +/** JS module interface - main entry point for launching React application for a given key. */ public interface AppRegistry extends JavaScriptModule { void runApplication(String appKey, WritableMap appParameters); + void unmountApplicationComponentAtRootTag(int rootNodeTag); + void startHeadlessTask(int taskId, String taskKey, WritableMap data); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/appstate/AppStateModule.java b/ReactAndroid/src/main/java/com/facebook/react/modules/appstate/AppStateModule.java index 4b43bb7c0cf..bd7bcd1bb3d 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/appstate/AppStateModule.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/appstate/AppStateModule.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.appstate; import com.facebook.react.bridge.Arguments; @@ -18,13 +17,12 @@ import com.facebook.react.bridge.WritableMap; import com.facebook.react.common.LifecycleState; import com.facebook.react.module.annotations.ReactModule; import com.facebook.react.modules.core.DeviceEventManagerModule.RCTDeviceEventEmitter; - import java.util.HashMap; import java.util.Map; @ReactModule(name = AppStateModule.NAME) public class AppStateModule extends ReactContextBaseJavaModule - implements LifecycleEventListener, WindowFocusChangeListener { + implements LifecycleEventListener, WindowFocusChangeListener { public static final String NAME = "AppState"; @@ -39,8 +37,10 @@ public class AppStateModule extends ReactContextBaseJavaModule super(reactContext); reactContext.addLifecycleEventListener(this); reactContext.addWindowFocusChangeListener(this); - mAppState = (reactContext.getLifecycleState() == LifecycleState.RESUMED ? - APP_STATE_ACTIVE : APP_STATE_BACKGROUND); + mAppState = + (reactContext.getLifecycleState() == LifecycleState.RESUMED + ? APP_STATE_ACTIVE + : APP_STATE_BACKGROUND); } @Override @@ -80,8 +80,9 @@ public class AppStateModule extends ReactContextBaseJavaModule @Override public void onWindowFocusChange(boolean hasFocus) { - getReactApplicationContext().getJSModule(RCTDeviceEventEmitter.class) - .emit("appStateFocusChange", hasFocus); + getReactApplicationContext() + .getJSModule(RCTDeviceEventEmitter.class) + .emit("appStateFocusChange", hasFocus); } private WritableMap createAppStateEventMap() { @@ -91,7 +92,8 @@ public class AppStateModule extends ReactContextBaseJavaModule } private void sendAppStateChangeEvent() { - getReactApplicationContext().getJSModule(RCTDeviceEventEmitter.class) - .emit("appStateDidChange", createAppStateEventMap()); + getReactApplicationContext() + .getJSModule(RCTDeviceEventEmitter.class) + .emit("appStateDidChange", createAppStateEventMap()); } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/blob/BlobModule.java b/ReactAndroid/src/main/java/com/facebook/react/modules/blob/BlobModule.java index d968e5800c7..90a89847cd2 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/blob/BlobModule.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/blob/BlobModule.java @@ -1,20 +1,17 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ package com.facebook.react.modules.blob; -import android.content.ContentResolver; -import android.content.Context; import android.content.res.Resources; import android.database.Cursor; import android.net.Uri; import android.provider.MediaStore; -import androidx.annotation.Nullable; import android.webkit.MimeTypeMap; - +import androidx.annotation.Nullable; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; @@ -26,7 +23,6 @@ import com.facebook.react.common.MapBuilder; import com.facebook.react.module.annotations.ReactModule; import com.facebook.react.modules.network.NetworkingModule; import com.facebook.react.modules.websocket.WebSocketModule; - import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; @@ -39,7 +35,6 @@ import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.UUID; - import okhttp3.MediaType; import okhttp3.RequestBody; import okhttp3.ResponseBody; @@ -53,99 +48,96 @@ public class BlobModule extends ReactContextBaseJavaModule { private final Map mBlobs = new HashMap<>(); private final WebSocketModule.ContentHandler mWebSocketContentHandler = - new WebSocketModule.ContentHandler() { - @Override - public void onMessage(String text, WritableMap params) { - params.putString("data", text); - } + new WebSocketModule.ContentHandler() { + @Override + public void onMessage(String text, WritableMap params) { + params.putString("data", text); + } - @Override - public void onMessage(ByteString bytes, WritableMap params) { - byte[] data = bytes.toByteArray(); + @Override + public void onMessage(ByteString bytes, WritableMap params) { + byte[] data = bytes.toByteArray(); - WritableMap blob = Arguments.createMap(); + WritableMap blob = Arguments.createMap(); - blob.putString("blobId", store(data)); - blob.putInt("offset", 0); - blob.putInt("size", data.length); + blob.putString("blobId", store(data)); + blob.putInt("offset", 0); + blob.putInt("size", data.length); - params.putMap("data", blob); - params.putString("type", "blob"); - } - }; + params.putMap("data", blob); + params.putString("type", "blob"); + } + }; private final NetworkingModule.UriHandler mNetworkingUriHandler = - new NetworkingModule.UriHandler() { - @Override - public boolean supports(Uri uri, String responseType) { - String scheme = uri.getScheme(); - boolean isRemote = "http".equals(scheme) || "https".equals(scheme); + new NetworkingModule.UriHandler() { + @Override + public boolean supports(Uri uri, String responseType) { + String scheme = uri.getScheme(); + boolean isRemote = "http".equals(scheme) || "https".equals(scheme); - return (!isRemote && "blob".equals(responseType)); - } + return (!isRemote && "blob".equals(responseType)); + } - @Override - public WritableMap fetch(Uri uri) throws IOException { - byte[] data = getBytesFromUri(uri); + @Override + public WritableMap fetch(Uri uri) throws IOException { + byte[] data = getBytesFromUri(uri); - WritableMap blob = Arguments.createMap(); - blob.putString("blobId", store(data)); - blob.putInt("offset", 0); - blob.putInt("size", data.length); - blob.putString("type", getMimeTypeFromUri(uri)); + WritableMap blob = Arguments.createMap(); + blob.putString("blobId", store(data)); + blob.putInt("offset", 0); + blob.putInt("size", data.length); + blob.putString("type", getMimeTypeFromUri(uri)); - // Needed for files - blob.putString("name", getNameFromUri(uri)); - blob.putDouble("lastModified", getLastModifiedFromUri(uri)); + // Needed for files + blob.putString("name", getNameFromUri(uri)); + blob.putDouble("lastModified", getLastModifiedFromUri(uri)); - return blob; - } - }; + return blob; + } + }; private final NetworkingModule.RequestBodyHandler mNetworkingRequestBodyHandler = - new NetworkingModule.RequestBodyHandler() { - @Override - public boolean supports(ReadableMap data) { - return data.hasKey("blob"); - } - - @Override - public RequestBody toRequestBody(ReadableMap data, String contentType) { - String type = contentType; - if (data.hasKey("type") && !data.getString("type").isEmpty()) { - type = data.getString("type"); + new NetworkingModule.RequestBodyHandler() { + @Override + public boolean supports(ReadableMap data) { + return data.hasKey("blob"); } - if (type == null) { - type = "application/octet-stream"; - } - ReadableMap blob = data.getMap("blob"); - String blobId = blob.getString("blobId"); - byte[] bytes = resolve( - blobId, - blob.getInt("offset"), - blob.getInt("size")); - return RequestBody.create(MediaType.parse(type), bytes); - } - }; + @Override + public RequestBody toRequestBody(ReadableMap data, String contentType) { + String type = contentType; + if (data.hasKey("type") && !data.getString("type").isEmpty()) { + type = data.getString("type"); + } + if (type == null) { + type = "application/octet-stream"; + } + ReadableMap blob = data.getMap("blob"); + String blobId = blob.getString("blobId"); + byte[] bytes = resolve(blobId, blob.getInt("offset"), blob.getInt("size")); + + return RequestBody.create(MediaType.parse(type), bytes); + } + }; private final NetworkingModule.ResponseHandler mNetworkingResponseHandler = - new NetworkingModule.ResponseHandler() { - @Override - public boolean supports(String responseType) { - return "blob".equals(responseType); - } + new NetworkingModule.ResponseHandler() { + @Override + public boolean supports(String responseType) { + return "blob".equals(responseType); + } - @Override - public WritableMap toResponseData(ResponseBody body) throws IOException { - byte[] data = body.bytes(); - WritableMap blob = Arguments.createMap(); - blob.putString("blobId", store(data)); - blob.putInt("offset", 0); - blob.putInt("size", data.length); - return blob; - } - }; + @Override + public WritableMap toResponseData(ResponseBody body) throws IOException { + byte[] data = body.bytes(); + WritableMap blob = Arguments.createMap(); + blob.putString("blobId", store(data)); + blob.putInt("offset", 0); + blob.putInt("size", data.length); + return blob; + } + }; public BlobModule(ReactApplicationContext reactContext) { super(reactContext); @@ -168,7 +160,7 @@ public class BlobModule extends ReactContextBaseJavaModule { } return MapBuilder.of( - "BLOB_URI_SCHEME", "content", "BLOB_URI_HOST", resources.getString(resourceId)); + "BLOB_URI_SCHEME", "content", "BLOB_URI_HOST", resources.getString(resourceId)); } public String store(byte[] data) { @@ -240,9 +232,10 @@ public class BlobModule extends ReactContextBaseJavaModule { return contentUri.getLastPathSegment(); } String[] projection = {MediaStore.MediaColumns.DISPLAY_NAME}; - Cursor metaCursor = getReactApplicationContext() - .getContentResolver() - .query(contentUri, projection, null, null, null); + Cursor metaCursor = + getReactApplicationContext() + .getContentResolver() + .query(contentUri, projection, null, null, null); if (metaCursor != null) { try { if (metaCursor.moveToFirst()) { @@ -285,7 +278,8 @@ public class BlobModule extends ReactContextBaseJavaModule { @ReactMethod public void addNetworkingHandler() { - NetworkingModule networkingModule = getReactApplicationContext().getNativeModule(NetworkingModule.class); + NetworkingModule networkingModule = + getReactApplicationContext().getNativeModule(NetworkingModule.class); networkingModule.addUriHandler(mNetworkingUriHandler); networkingModule.addRequestBodyHandler(mNetworkingRequestBodyHandler); networkingModule.addResponseHandler(mNetworkingResponseHandler); diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/blob/BlobProvider.java b/ReactAndroid/src/main/java/com/facebook/react/modules/blob/BlobProvider.java index c6766aec761..748930b6378 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/blob/BlobProvider.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/blob/BlobProvider.java @@ -1,8 +1,8 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ package com.facebook.react.modules.blob; diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/blob/FileReaderModule.java b/ReactAndroid/src/main/java/com/facebook/react/modules/blob/FileReaderModule.java index bb8f35e8d37..895a40234da 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/blob/FileReaderModule.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/blob/FileReaderModule.java @@ -1,14 +1,12 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.blob; import android.util.Base64; - import com.facebook.react.bridge.Promise; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; @@ -16,7 +14,6 @@ import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.module.annotations.ReactModule; - @ReactModule(name = FileReaderModule.NAME) public class FileReaderModule extends ReactContextBaseJavaModule { @@ -39,10 +36,9 @@ public class FileReaderModule extends ReactContextBaseJavaModule { @ReactMethod public void readAsText(ReadableMap blob, String encoding, Promise promise) { - byte[] bytes = getBlobModule().resolve( - blob.getString("blobId"), - blob.getInt("offset"), - blob.getInt("size")); + byte[] bytes = + getBlobModule() + .resolve(blob.getString("blobId"), blob.getInt("offset"), blob.getInt("size")); if (bytes == null) { promise.reject(ERROR_INVALID_BLOB, "The specified blob is invalid"); @@ -58,10 +54,9 @@ public class FileReaderModule extends ReactContextBaseJavaModule { @ReactMethod public void readAsDataURL(ReadableMap blob, Promise promise) { - byte[] bytes = getBlobModule().resolve( - blob.getString("blobId"), - blob.getInt("offset"), - blob.getInt("size")); + byte[] bytes = + getBlobModule() + .resolve(blob.getString("blobId"), blob.getInt("offset"), blob.getInt("size")); if (bytes == null) { promise.reject(ERROR_INVALID_BLOB, "The specified blob is invalid"); diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/camera/CameraRollManager.java b/ReactAndroid/src/main/java/com/facebook/react/modules/camera/CameraRollManager.java index 25780267549..2d5826bdc6a 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/camera/CameraRollManager.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/camera/CameraRollManager.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.camera; import android.content.ContentResolver; @@ -16,11 +15,9 @@ import android.media.MediaMetadataRetriever; import android.media.MediaScannerConnection; import android.net.Uri; import android.os.AsyncTask; -import android.os.Build; import android.os.Environment; import android.provider.MediaStore; import android.provider.MediaStore.Images; -import android.provider.MediaStore.MediaColumns; import android.text.TextUtils; import com.facebook.common.logging.FLog; import com.facebook.react.bridge.GuardedAsyncTask; @@ -43,6 +40,7 @@ import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; +import java.net.URL; import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.channels.FileChannel; @@ -50,7 +48,6 @@ import java.nio.channels.ReadableByteChannel; import java.util.ArrayList; import java.util.List; import javax.annotation.Nullable; -import java.net.URL; // TODO #6015104: rename to something less iOSish /** @@ -130,7 +127,7 @@ public class CameraRollManager extends ReactContextBaseJavaModule { File source = new File(mUri.getPath()); try { String scheme = mUri.getScheme(); - if (scheme.equals("http") || scheme.equals("https")){ + if (scheme.equals("http") || scheme.equals("https")) { input = Channels.newChannel(new URL(mUri.toString()).openStream()); } else { input = new FileInputStream(source).getChannel(); @@ -165,7 +162,7 @@ public class CameraRollManager extends ReactContextBaseJavaModule { } // Drains the buffer buffer.flip(); - while (buffer.hasRemaining()){ + while (buffer.hasRemaining()) { output.write(buffer); } input.close(); @@ -173,7 +170,7 @@ public class CameraRollManager extends ReactContextBaseJavaModule { MediaScannerConnection.scanFile( mContext, - new String[]{dest.getAbsolutePath()}, + new String[] {dest.getAbsolutePath()}, null, new MediaScannerConnection.OnScanCompletedListener() { @Override @@ -210,47 +207,35 @@ public class CameraRollManager extends ReactContextBaseJavaModule { * Get photos from {@link MediaStore.Images}, most recent first. * * @param params a map containing the following keys: - *

    - *
  • first (mandatory): a number representing the number of photos to fetch
  • - *
  • - * after (optional): a cursor that matches page_info[end_cursor] returned by a - * previous call to {@link #getPhotos} - *
  • - *
  • groupName (optional): an album name
  • - *
  • - * mimeType (optional): restrict returned images to a specific mimetype (e.g. - * image/jpeg) - *
  • - *
  • - * assetType (optional): chooses between either photos or videos from the camera roll. - * Valid values are "Photos" or "Videos". Defaults to photos. - *
  • - *
+ *
    + *
  • first (mandatory): a number representing the number of photos to fetch + *
  • after (optional): a cursor that matches page_info[end_cursor] returned by a previous + * call to {@link #getPhotos} + *
  • groupName (optional): an album name + *
  • mimeType (optional): restrict returned images to a specific mimetype (e.g. + * image/jpeg) + *
  • assetType (optional): chooses between either photos or videos from the camera roll. + * Valid values are "Photos" or "Videos". Defaults to photos. + *
+ * * @param promise the Promise to be resolved when the photos are loaded; for a format of the - * parameters passed to this callback, see {@code getPhotosReturnChecker} in CameraRoll.js + * parameters passed to this callback, see {@code getPhotosReturnChecker} in CameraRoll.js */ @ReactMethod public void getPhotos(final ReadableMap params, final Promise promise) { int first = params.getInt("first"); String after = params.hasKey("after") ? params.getString("after") : null; String groupName = params.hasKey("groupName") ? params.getString("groupName") : null; - String assetType = params.hasKey("assetType") ? params.getString("assetType") : ASSET_TYPE_PHOTOS; - ReadableArray mimeTypes = params.hasKey("mimeTypes") - ? params.getArray("mimeTypes") - : null; + String assetType = + params.hasKey("assetType") ? params.getString("assetType") : ASSET_TYPE_PHOTOS; + ReadableArray mimeTypes = params.hasKey("mimeTypes") ? params.getArray("mimeTypes") : null; if (params.hasKey("groupTypes")) { throw new JSApplicationIllegalArgumentException("groupTypes is not supported on Android"); } new GetMediaTask( - getReactApplicationContext(), - first, - after, - groupName, - mimeTypes, - assetType, - promise) - .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + getReactApplicationContext(), first, after, groupName, mimeTypes, assetType, promise) + .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } private static class GetMediaTask extends GuardedAsyncTask { @@ -295,28 +280,44 @@ public class CameraRollManager extends ReactContextBaseJavaModule { switch (mAssetType) { case ASSET_TYPE_PHOTOS: - selection.append(" AND " + MediaStore.Files.FileColumns.MEDIA_TYPE + " = " - + MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE); + selection.append( + " AND " + + MediaStore.Files.FileColumns.MEDIA_TYPE + + " = " + + MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE); break; case ASSET_TYPE_VIDEOS: - selection.append(" AND " + MediaStore.Files.FileColumns.MEDIA_TYPE + " = " - + MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO); + selection.append( + " AND " + + MediaStore.Files.FileColumns.MEDIA_TYPE + + " = " + + MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO); break; case ASSET_TYPE_ALL: - selection.append(" AND " + MediaStore.Files.FileColumns.MEDIA_TYPE + " IN (" - + MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO + "," - + MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE + ")"); + selection.append( + " AND " + + MediaStore.Files.FileColumns.MEDIA_TYPE + + " IN (" + + MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO + + "," + + MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE + + ")"); break; default: mPromise.reject( - ERROR_UNABLE_TO_FILTER, - "Invalid filter option: '" + mAssetType + "'. Expected one of '" - + ASSET_TYPE_PHOTOS + "', '" + ASSET_TYPE_VIDEOS + "' or '" + ASSET_TYPE_ALL + "'." - ); + ERROR_UNABLE_TO_FILTER, + "Invalid filter option: '" + + mAssetType + + "'. Expected one of '" + + ASSET_TYPE_PHOTOS + + "', '" + + ASSET_TYPE_VIDEOS + + "' or '" + + ASSET_TYPE_ALL + + "'."); return; } - if (mMimeTypes != null && mMimeTypes.size() > 0) { selection.append(" AND " + Images.Media.MIME_TYPE + " IN ("); for (int i = 0; i < mMimeTypes.size(); i++) { @@ -331,13 +332,18 @@ public class CameraRollManager extends ReactContextBaseJavaModule { // setting a limit at all), but it works because this specific ContentProvider is backed by // an SQLite DB and forwards parameters to it without doing any parsing / validation. try { - Cursor media = resolver.query( - MediaStore.Files.getContentUri("external"), - PROJECTION, - selection.toString(), - selectionArgs.toArray(new String[selectionArgs.size()]), - Images.Media.DATE_TAKEN + " DESC, " + Images.Media.DATE_MODIFIED + " DESC LIMIT " + - (mFirst + 1)); // set LIMIT to first + 1 so that we know how to populate page_info + Cursor media = + resolver.query( + MediaStore.Files.getContentUri("external"), + PROJECTION, + selection.toString(), + selectionArgs.toArray(new String[selectionArgs.size()]), + Images.Media.DATE_TAKEN + + " DESC, " + + Images.Media.DATE_MODIFIED + + " DESC LIMIT " + + (mFirst + + 1)); // set LIMIT to first + 1 so that we know how to populate page_info if (media == null) { mPromise.reject(ERROR_UNABLE_TO_LOAD, "Could not get media"); } else { @@ -364,17 +370,13 @@ public class CameraRollManager extends ReactContextBaseJavaModule { if (limit < media.getCount()) { media.moveToPosition(limit - 1); pageInfo.putString( - "end_cursor", - media.getString(media.getColumnIndex(Images.Media.DATE_TAKEN))); + "end_cursor", media.getString(media.getColumnIndex(Images.Media.DATE_TAKEN))); } response.putMap("page_info", pageInfo); } private static void putEdges( - ContentResolver resolver, - Cursor media, - WritableMap response, - int limit) { + ContentResolver resolver, Cursor media, WritableMap response, int limit) { WritableArray edges = new WritableNativeArray(); media.moveToFirst(); int idIndex = media.getColumnIndex(Images.Media._ID); @@ -391,8 +393,8 @@ public class CameraRollManager extends ReactContextBaseJavaModule { WritableMap edge = new WritableNativeMap(); WritableMap node = new WritableNativeMap(); boolean imageInfoSuccess = - putImageInfo(resolver, media, node, idIndex, widthIndex, heightIndex, dataIndex, - mimeTypeIndex); + putImageInfo( + resolver, media, node, idIndex, widthIndex, heightIndex, dataIndex, mimeTypeIndex); if (imageInfoSuccess) { putBasicNodeInfo(media, node, mimeTypeIndex, groupNameIndex, dateTakenIndex); putLocationInfo(media, node, longitudeIndex, latitudeIndex); @@ -410,11 +412,7 @@ public class CameraRollManager extends ReactContextBaseJavaModule { } private static void putBasicNodeInfo( - Cursor media, - WritableMap node, - int mimeTypeIndex, - int groupNameIndex, - int dateTakenIndex) { + Cursor media, WritableMap node, int mimeTypeIndex, int groupNameIndex, int dateTakenIndex) { node.putString("type", media.getString(mimeTypeIndex)); node.putString("group_name", media.getString(groupNameIndex)); node.putDouble("timestamp", media.getLong(dateTakenIndex) / 1000d); @@ -437,8 +435,7 @@ public class CameraRollManager extends ReactContextBaseJavaModule { String mimeType = media.getString(mimeTypeIndex); - if (mimeType != null - && mimeType.startsWith("video")) { + if (mimeType != null && mimeType.startsWith("video")) { try { AssetFileDescriptor photoDescriptor = resolver.openAssetFileDescriptor(photoUri, "r"); MediaMetadataRetriever retriever = new MediaMetadataRetriever(); @@ -499,10 +496,7 @@ public class CameraRollManager extends ReactContextBaseJavaModule { } private static void putLocationInfo( - Cursor media, - WritableMap node, - int longitudeIndex, - int latitudeIndex) { + Cursor media, WritableMap node, int longitudeIndex, int latitudeIndex) { double longitude = media.getDouble(longitudeIndex); double latitude = media.getDouble(latitudeIndex); if (longitude > 0 || latitude > 0) { diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/camera/ImageEditingManager.java b/ReactAndroid/src/main/java/com/facebook/react/modules/camera/ImageEditingManager.java index 152afdfd340..bbf7f9e0a44 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/camera/ImageEditingManager.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/camera/ImageEditingManager.java @@ -1,14 +1,36 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.camera; -import javax.annotation.Nullable; - +import android.annotation.SuppressLint; +import android.content.Context; +import android.database.Cursor; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.graphics.BitmapRegionDecoder; +import android.graphics.Matrix; +import android.graphics.Rect; +import android.media.ExifInterface; +import android.net.Uri; +import android.os.AsyncTask; +import android.provider.MediaStore; +import android.text.TextUtils; +import com.facebook.common.logging.FLog; +import com.facebook.infer.annotation.Assertions; +import com.facebook.react.bridge.Callback; +import com.facebook.react.bridge.GuardedAsyncTask; +import com.facebook.react.bridge.JSApplicationIllegalArgumentException; +import com.facebook.react.bridge.ReactApplicationContext; +import com.facebook.react.bridge.ReactContext; +import com.facebook.react.bridge.ReactContextBaseJavaModule; +import com.facebook.react.bridge.ReactMethod; +import com.facebook.react.bridge.ReadableMap; +import com.facebook.react.common.ReactConstants; +import com.facebook.react.module.annotations.ReactModule; import java.io.File; import java.io.FileOutputStream; import java.io.FilenameFilter; @@ -21,77 +43,50 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; +import javax.annotation.Nullable; -import android.annotation.SuppressLint; -import android.content.Context; -import android.database.Cursor; -import android.graphics.Bitmap; -import android.graphics.BitmapRegionDecoder; -import android.graphics.BitmapFactory; -import android.graphics.Matrix; -import android.graphics.Rect; -import android.media.ExifInterface; -import android.net.Uri; -import android.os.AsyncTask; -import android.provider.MediaStore; -import android.text.TextUtils; - -import com.facebook.common.logging.FLog; -import com.facebook.react.bridge.Callback; -import com.facebook.react.bridge.GuardedAsyncTask; -import com.facebook.react.bridge.ReactApplicationContext; -import com.facebook.react.bridge.ReactContext; -import com.facebook.react.bridge.ReactContextBaseJavaModule; -import com.facebook.react.bridge.ReactMethod; -import com.facebook.react.bridge.JSApplicationIllegalArgumentException; -import com.facebook.react.bridge.ReadableMap; -import com.facebook.infer.annotation.Assertions; -import com.facebook.react.common.ReactConstants; -import com.facebook.react.module.annotations.ReactModule; - -/** - * Native module that provides image cropping functionality. - */ +/** Native module that provides image cropping functionality. */ @ReactModule(name = ImageEditingManager.NAME) public class ImageEditingManager extends ReactContextBaseJavaModule { public static final String NAME = "ImageEditingManager"; - private static final List LOCAL_URI_PREFIXES = Arrays.asList( - "file://", "content://"); + private static final List LOCAL_URI_PREFIXES = Arrays.asList("file://", "content://"); private static final String TEMP_FILE_PREFIX = "ReactNative_cropped_image_"; /** Compress quality of the output file. */ private static final int COMPRESS_QUALITY = 90; - @SuppressLint("InlinedApi") private static final String[] EXIF_ATTRIBUTES = new String[] { - ExifInterface.TAG_APERTURE, - ExifInterface.TAG_DATETIME, - ExifInterface.TAG_DATETIME_DIGITIZED, - ExifInterface.TAG_EXPOSURE_TIME, - ExifInterface.TAG_FLASH, - ExifInterface.TAG_FOCAL_LENGTH, - ExifInterface.TAG_GPS_ALTITUDE, - ExifInterface.TAG_GPS_ALTITUDE_REF, - ExifInterface.TAG_GPS_DATESTAMP, - ExifInterface.TAG_GPS_LATITUDE, - ExifInterface.TAG_GPS_LATITUDE_REF, - ExifInterface.TAG_GPS_LONGITUDE, - ExifInterface.TAG_GPS_LONGITUDE_REF, - ExifInterface.TAG_GPS_PROCESSING_METHOD, - ExifInterface.TAG_GPS_TIMESTAMP, - ExifInterface.TAG_IMAGE_LENGTH, - ExifInterface.TAG_IMAGE_WIDTH, - ExifInterface.TAG_ISO, - ExifInterface.TAG_MAKE, - ExifInterface.TAG_MODEL, - ExifInterface.TAG_ORIENTATION, - ExifInterface.TAG_SUBSEC_TIME, - ExifInterface.TAG_SUBSEC_TIME_DIG, - ExifInterface.TAG_SUBSEC_TIME_ORIG, - ExifInterface.TAG_WHITE_BALANCE - }; + @SuppressLint("InlinedApi") + private static final String[] EXIF_ATTRIBUTES = + new String[] { + ExifInterface.TAG_APERTURE, + ExifInterface.TAG_DATETIME, + ExifInterface.TAG_DATETIME_DIGITIZED, + ExifInterface.TAG_EXPOSURE_TIME, + ExifInterface.TAG_FLASH, + ExifInterface.TAG_FOCAL_LENGTH, + ExifInterface.TAG_GPS_ALTITUDE, + ExifInterface.TAG_GPS_ALTITUDE_REF, + ExifInterface.TAG_GPS_DATESTAMP, + ExifInterface.TAG_GPS_LATITUDE, + ExifInterface.TAG_GPS_LATITUDE_REF, + ExifInterface.TAG_GPS_LONGITUDE, + ExifInterface.TAG_GPS_LONGITUDE_REF, + ExifInterface.TAG_GPS_PROCESSING_METHOD, + ExifInterface.TAG_GPS_TIMESTAMP, + ExifInterface.TAG_IMAGE_LENGTH, + ExifInterface.TAG_IMAGE_WIDTH, + ExifInterface.TAG_ISO, + ExifInterface.TAG_MAKE, + ExifInterface.TAG_MODEL, + ExifInterface.TAG_ORIENTATION, + ExifInterface.TAG_SUBSEC_TIME, + ExifInterface.TAG_SUBSEC_TIME_DIG, + ExifInterface.TAG_SUBSEC_TIME_ORIG, + ExifInterface.TAG_WHITE_BALANCE + }; public ImageEditingManager(ReactApplicationContext reactContext) { super(reactContext); @@ -136,15 +131,16 @@ public class ImageEditingManager extends ReactContextBaseJavaModule { } private void cleanDirectory(File directory) { - File[] toDelete = directory.listFiles( - new FilenameFilter() { - @Override - public boolean accept(File dir, String filename) { - return filename.startsWith(TEMP_FILE_PREFIX); - } - }); + File[] toDelete = + directory.listFiles( + new FilenameFilter() { + @Override + public boolean accept(File dir, String filename) { + return filename.startsWith(TEMP_FILE_PREFIX); + } + }); if (toDelete != null) { - for (File file: toDelete) { + for (File file : toDelete) { file.delete(); } } @@ -158,44 +154,43 @@ public class ImageEditingManager extends ReactContextBaseJavaModule { * * @param uri the MediaStore URI of the image to crop * @param options crop parameters specified as {@code {offset: {x, y}, size: {width, height}}}. - * Optionally this also contains {@code {targetSize: {width, height}}}. If this is - * specified, the cropped image will be resized to that size. - * All units are in pixels (not DPs). + * Optionally this also contains {@code {targetSize: {width, height}}}. If this is specified, + * the cropped image will be resized to that size. All units are in pixels (not DPs). * @param success callback to be invoked when the image has been cropped; the only argument that - * is passed to this callback is the file:// URI of the new image + * is passed to this callback is the file:// URI of the new image * @param error callback to be invoked when an error occurs (e.g. can't create file etc.) */ @ReactMethod public void cropImage( - String uri, - ReadableMap options, - final Callback success, - final Callback error) { + String uri, ReadableMap options, final Callback success, final Callback error) { ReadableMap offset = options.hasKey("offset") ? options.getMap("offset") : null; ReadableMap size = options.hasKey("size") ? options.getMap("size") : null; - if (offset == null || size == null || - !offset.hasKey("x") || !offset.hasKey("y") || - !size.hasKey("width") || !size.hasKey("height")) { + if (offset == null + || size == null + || !offset.hasKey("x") + || !offset.hasKey("y") + || !size.hasKey("width") + || !size.hasKey("height")) { throw new JSApplicationIllegalArgumentException("Please specify offset and size"); } if (uri == null || uri.isEmpty()) { throw new JSApplicationIllegalArgumentException("Please specify a URI"); } - CropTask cropTask = new CropTask( - getReactApplicationContext(), - uri, - (int) offset.getDouble("x"), - (int) offset.getDouble("y"), - (int) size.getDouble("width"), - (int) size.getDouble("height"), - success, - error); + CropTask cropTask = + new CropTask( + getReactApplicationContext(), + uri, + (int) offset.getDouble("x"), + (int) offset.getDouble("y"), + (int) size.getDouble("width"), + (int) size.getDouble("height"), + success, + error); if (options.hasKey("displaySize")) { ReadableMap targetSize = options.getMap("displaySize"); cropTask.setTargetSize( - (int) targetSize.getDouble("width"), - (int) targetSize.getDouble("height")); + (int) targetSize.getDouble("width"), (int) targetSize.getDouble("height")); } cropTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } @@ -223,8 +218,8 @@ public class ImageEditingManager extends ReactContextBaseJavaModule { Callback error) { super(context); if (x < 0 || y < 0 || width <= 0 || height <= 0) { - throw new JSApplicationIllegalArgumentException(String.format( - "Invalid crop rectangle: [%d, %d, %d, %d]", x, y, width, height)); + throw new JSApplicationIllegalArgumentException( + String.format("Invalid crop rectangle: [%d, %d, %d, %d]", x, y, width, height)); } mContext = context; mUri = uri; @@ -238,8 +233,8 @@ public class ImageEditingManager extends ReactContextBaseJavaModule { public void setTargetSize(int width, int height) { if (width <= 0 || height <= 0) { - throw new JSApplicationIllegalArgumentException(String.format( - "Invalid target size: [%d, %d]", width, height)); + throw new JSApplicationIllegalArgumentException( + String.format("Invalid target size: [%d, %d]", width, height)); } mTargetWidth = width; mTargetHeight = height; @@ -294,6 +289,7 @@ public class ImageEditingManager extends ReactContextBaseJavaModule { /** * Reads and crops the bitmap. + * * @param outOptions Bitmap options, useful to determine {@code outMimeType}. */ private Bitmap crop(BitmapFactory.Options outOptions) throws IOException { @@ -313,15 +309,13 @@ public class ImageEditingManager extends ReactContextBaseJavaModule { } /** - * Crop the rectangle given by {@code mX, mY, mWidth, mHeight} within the source bitmap - * and scale the result to {@code targetWidth, targetHeight}. + * Crop the rectangle given by {@code mX, mY, mWidth, mHeight} within the source bitmap and + * scale the result to {@code targetWidth, targetHeight}. + * * @param outOptions Bitmap options, useful to determine {@code outMimeType}. */ private Bitmap cropAndResize( - int targetWidth, - int targetHeight, - BitmapFactory.Options outOptions) - throws IOException { + int targetWidth, int targetHeight, BitmapFactory.Options outOptions) throws IOException { Assertions.assertNotNull(outOptions); // Loading large bitmaps efficiently: @@ -418,8 +412,10 @@ public class ImageEditingManager extends ReactContextBaseJavaModule { if (uri.getScheme().equals("file")) { return new File(uri.getPath()); } else if (uri.getScheme().equals("content")) { - Cursor cursor = context.getContentResolver() - .query(uri, new String[] { MediaStore.MediaColumns.DATA }, null, null, null); + Cursor cursor = + context + .getContentResolver() + .query(uri, new String[] {MediaStore.MediaColumns.DATA}, null, null, null); if (cursor != null) { try { if (cursor.moveToFirst()) { @@ -494,21 +490,22 @@ public class ImageEditingManager extends ReactContextBaseJavaModule { } if (externalCacheDir == null) { cacheDir = internalCacheDir; - } - else if (internalCacheDir == null) { + } else if (internalCacheDir == null) { cacheDir = externalCacheDir; } else { - cacheDir = externalCacheDir.getFreeSpace() > internalCacheDir.getFreeSpace() ? - externalCacheDir : internalCacheDir; + cacheDir = + externalCacheDir.getFreeSpace() > internalCacheDir.getFreeSpace() + ? externalCacheDir + : internalCacheDir; } return File.createTempFile(TEMP_FILE_PREFIX, getFileExtensionForType(mimeType), cacheDir); } /** - * When scaling down the bitmap, decode only every n-th pixel in each dimension. - * Calculate the largest {@code inSampleSize} value that is a power of 2 and keeps both - * {@code width, height} larger or equal to {@code targetWidth, targetHeight}. - * This can significantly reduce memory usage. + * When scaling down the bitmap, decode only every n-th pixel in each dimension. Calculate the + * largest {@code inSampleSize} value that is a power of 2 and keeps both {@code width, height} + * larger or equal to {@code targetWidth, targetHeight}. This can significantly reduce memory + * usage. */ private static int getDecodeSampleSize(int width, int height, int targetWidth, int targetHeight) { int inSampleSize = 1; diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/camera/ImageStoreManager.java b/ReactAndroid/src/main/java/com/facebook/react/modules/camera/ImageStoreManager.java index afe625ffc56..f66bf88a92f 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/camera/ImageStoreManager.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/camera/ImageStoreManager.java @@ -1,24 +1,16 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.camera; -import java.io.ByteArrayOutputStream; -import java.io.Closeable; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; - import android.content.ContentResolver; import android.net.Uri; import android.os.AsyncTask; import android.util.Base64; import android.util.Base64OutputStream; - import com.facebook.react.bridge.Callback; import com.facebook.react.bridge.GuardedAsyncTask; import com.facebook.react.bridge.ReactApplicationContext; @@ -26,6 +18,11 @@ import com.facebook.react.bridge.ReactContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.module.annotations.ReactModule; +import java.io.ByteArrayOutputStream; +import java.io.Closeable; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; @ReactModule(name = ImageStoreManager.NAME) public class ImageStoreManager extends ReactContextBaseJavaModule { @@ -60,11 +57,7 @@ public class ImageStoreManager extends ReactContextBaseJavaModule { private final Callback mSuccess; private final Callback mError; - private GetBase64Task( - ReactContext reactContext, - String uri, - Callback success, - Callback error) { + private GetBase64Task(ReactContext reactContext, String uri, Callback success, Callback error) { super(reactContext); mUri = uri; mSuccess = success; diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/clipboard/ClipboardModule.java b/ReactAndroid/src/main/java/com/facebook/react/modules/clipboard/ClipboardModule.java index 3ac75048af7..8fc038626ac 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/clipboard/ClipboardModule.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/clipboard/ClipboardModule.java @@ -1,24 +1,20 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.clipboard; -import android.content.ClipboardManager; import android.content.ClipData; +import android.content.ClipboardManager; import android.content.Context; - import com.facebook.react.bridge.ContextBaseJavaModule; -import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.Promise; +import com.facebook.react.bridge.ReactMethod; import com.facebook.react.module.annotations.ReactModule; -/** - * A module that allows JS to get/set clipboard contents. - */ +/** A module that allows JS to get/set clipboard contents. */ @ReactModule(name = ClipboardModule.NAME) public class ClipboardModule extends ContextBaseJavaModule { diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/common/ModuleDataCleaner.java b/ReactAndroid/src/main/java/com/facebook/react/modules/common/ModuleDataCleaner.java index b794529d0f1..2f7ec73086d 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/common/ModuleDataCleaner.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/common/ModuleDataCleaner.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.common; import com.facebook.common.logging.FLog; @@ -21,16 +20,15 @@ public class ModuleDataCleaner { /** * Indicates a module may contain sensitive user data and should be cleaned on logout. * - * Types of data that should be cleaned: - * - Persistent data (disk) that may contain user information or content. - * - Retained (static) in-memory data that may contain user info or content. + *

Types of data that should be cleaned: - Persistent data (disk) that may contain user + * information or content. - Retained (static) in-memory data that may contain user info or + * content. * - * Note that the following types of modules do not need to be cleaned here: - * - Modules whose user data is kept in memory in non-static fields, assuming the app uses a - * separate instance for each viewer context. - * - Modules that remove all persistent data (temp files, etc) when the catalyst instance is - * destroyed. This is because logout implies that the instance is destroyed. Apps should enforce - * this. + *

Note that the following types of modules do not need to be cleaned here: - Modules whose + * user data is kept in memory in non-static fields, assuming the app uses a separate instance for + * each viewer context. - Modules that remove all persistent data (temp files, etc) when the + * catalyst instance is destroyed. This is because logout implies that the instance is destroyed. + * Apps should enforce this. */ public interface Cleanable { diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/core/ChoreographerCompat.java b/ReactAndroid/src/main/java/com/facebook/react/modules/core/ChoreographerCompat.java index 6642e63dfd5..d6cad6a8bb8 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/core/ChoreographerCompat.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/core/ChoreographerCompat.java @@ -26,7 +26,7 @@ public class ChoreographerCompat { public static ChoreographerCompat getInstance() { UiThreadUtil.assertOnUiThread(); - if (sInstance == null){ + if (sInstance == null) { sInstance = new ChoreographerCompat(); } return sInstance; @@ -57,8 +57,7 @@ public class ChoreographerCompat { } private void choreographerPostFrameCallbackDelayed( - Choreographer.FrameCallback frameCallback, - long delayMillis) { + Choreographer.FrameCallback frameCallback, long delayMillis) { mChoreographer.postFrameCallbackDelayed(frameCallback, delayMillis); } @@ -67,41 +66,44 @@ public class ChoreographerCompat { } /** - * This class provides a compatibility wrapper around the JellyBean FrameCallback with methods - * to access cached wrappers for submitting a real FrameCallback to a Choreographer or a Runnable - * to a Handler. + * This class provides a compatibility wrapper around the JellyBean FrameCallback with methods to + * access cached wrappers for submitting a real FrameCallback to a Choreographer or a Runnable to + * a Handler. */ - public static abstract class FrameCallback { + public abstract static class FrameCallback { private Runnable mRunnable; private Choreographer.FrameCallback mFrameCallback; Choreographer.FrameCallback getFrameCallback() { if (mFrameCallback == null) { - mFrameCallback = new Choreographer.FrameCallback() { - @Override - public void doFrame(long frameTimeNanos) { - FrameCallback.this.doFrame(frameTimeNanos); - } - }; + mFrameCallback = + new Choreographer.FrameCallback() { + @Override + public void doFrame(long frameTimeNanos) { + FrameCallback.this.doFrame(frameTimeNanos); + } + }; } return mFrameCallback; } Runnable getRunnable() { if (mRunnable == null) { - mRunnable = new Runnable() { - @Override - public void run() { - doFrame(System.nanoTime()); - } - }; + mRunnable = + new Runnable() { + @Override + public void run() { + doFrame(System.nanoTime()); + } + }; } return mRunnable; } /** - * Just a wrapper for frame callback, see {@link android.view.Choreographer.FrameCallback#doFrame(long)}. + * Just a wrapper for frame callback, see {@link + * android.view.Choreographer.FrameCallback#doFrame(long)}. */ public abstract void doFrame(long frameTimeNanos); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/core/DefaultHardwareBackBtnHandler.java b/ReactAndroid/src/main/java/com/facebook/react/modules/core/DefaultHardwareBackBtnHandler.java index 288f4032850..5768d2aeded 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/core/DefaultHardwareBackBtnHandler.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/core/DefaultHardwareBackBtnHandler.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.core; /** @@ -16,8 +15,8 @@ public interface DefaultHardwareBackBtnHandler { /** * By default, all onBackPress() calls should not execute the default backpress handler and should - * instead propagate it to the JS instance. If JS doesn't want to handle the back press itself, - * it shall call back into native to invoke this function which should execute the default handler + * instead propagate it to the JS instance. If JS doesn't want to handle the back press itself, it + * shall call back into native to invoke this function which should execute the default handler */ void invokeDefaultOnBackPressed(); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/core/DeviceEventManagerModule.java b/ReactAndroid/src/main/java/com/facebook/react/modules/core/DeviceEventManagerModule.java index c78527208cc..e7935399b98 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/core/DeviceEventManagerModule.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/core/DeviceEventManagerModule.java @@ -1,32 +1,28 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.core; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - import android.net.Uri; - import com.facebook.react.bridge.Arguments; +import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; -import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.bridge.UiThreadUtil; import com.facebook.react.bridge.WritableMap; import com.facebook.react.module.annotations.ReactModule; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; -/** - * Native module that handles device hardware events like hardware back presses. - */ +/** Native module that handles device hardware events like hardware back presses. */ @ReactModule(name = DeviceEventManagerModule.NAME) public class DeviceEventManagerModule extends ReactContextBaseJavaModule { public static final String NAME = "DeviceEventManager"; + public interface RCTDeviceEventEmitter extends JavaScriptModule { void emit(@Nonnull String eventName, @Nullable Object data); } @@ -34,36 +30,30 @@ public class DeviceEventManagerModule extends ReactContextBaseJavaModule { private final Runnable mInvokeDefaultBackPressRunnable; public DeviceEventManagerModule( - ReactApplicationContext reactContext, - final DefaultHardwareBackBtnHandler backBtnHandler) { + ReactApplicationContext reactContext, final DefaultHardwareBackBtnHandler backBtnHandler) { super(reactContext); - mInvokeDefaultBackPressRunnable = new Runnable() { - @Override - public void run() { - UiThreadUtil.assertOnUiThread(); - backBtnHandler.invokeDefaultOnBackPressed(); - } - }; + mInvokeDefaultBackPressRunnable = + new Runnable() { + @Override + public void run() { + UiThreadUtil.assertOnUiThread(); + backBtnHandler.invokeDefaultOnBackPressed(); + } + }; } - /** - * Sends an event to the JS instance that the hardware back has been pressed. - */ + /** Sends an event to the JS instance that the hardware back has been pressed. */ public void emitHardwareBackPressed() { getReactApplicationContext() .getJSModule(RCTDeviceEventEmitter.class) .emit("hardwareBackPress", null); } - /** - * Sends an event to the JS instance that a new intent was received. - */ + /** Sends an event to the JS instance that a new intent was received. */ public void emitNewIntentReceived(Uri uri) { WritableMap map = Arguments.createMap(); map.putString("url", uri.toString()); - getReactApplicationContext() - .getJSModule(RCTDeviceEventEmitter.class) - .emit("url", map); + getReactApplicationContext().getJSModule(RCTDeviceEventEmitter.class).emit("url", map); } /** diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/core/ExceptionsManagerModule.java b/ReactAndroid/src/main/java/com/facebook/react/modules/core/ExceptionsManagerModule.java index 76f95a6a441..7c27b632111 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/core/ExceptionsManagerModule.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/core/ExceptionsManagerModule.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.core; import com.facebook.common.logging.FLog; diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/core/HeadlessJsTaskSupportModule.java b/ReactAndroid/src/main/java/com/facebook/react/modules/core/HeadlessJsTaskSupportModule.java index e9c2cae2a69..e17f50897c6 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/core/HeadlessJsTaskSupportModule.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/core/HeadlessJsTaskSupportModule.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.core; import com.facebook.common.logging.FLog; @@ -36,15 +35,15 @@ public class HeadlessJsTaskSupportModule extends ReactContextBaseJavaModule { @ReactMethod public void notifyTaskRetry(int taskId, Promise promise) { HeadlessJsTaskContext headlessJsTaskContext = - HeadlessJsTaskContext.getInstance(getReactApplicationContext()); + HeadlessJsTaskContext.getInstance(getReactApplicationContext()); if (headlessJsTaskContext.isTaskRunning(taskId)) { final boolean retryPosted = headlessJsTaskContext.retryTask(taskId); promise.resolve(retryPosted); } else { FLog.w( - HeadlessJsTaskSupportModule.class, - "Tried to retry non-active task with id %d. Did it time out?", - taskId); + HeadlessJsTaskSupportModule.class, + "Tried to retry non-active task with id %d. Did it time out?", + taskId); promise.resolve(false); } } @@ -52,14 +51,14 @@ public class HeadlessJsTaskSupportModule extends ReactContextBaseJavaModule { @ReactMethod public void notifyTaskFinished(int taskId) { HeadlessJsTaskContext headlessJsTaskContext = - HeadlessJsTaskContext.getInstance(getReactApplicationContext()); + HeadlessJsTaskContext.getInstance(getReactApplicationContext()); if (headlessJsTaskContext.isTaskRunning(taskId)) { headlessJsTaskContext.finishTask(taskId); } else { FLog.w( - HeadlessJsTaskSupportModule.class, - "Tried to finish non-active task with id %d. Did it time out?", - taskId); + HeadlessJsTaskSupportModule.class, + "Tried to finish non-active task with id %d. Did it time out?", + taskId); } } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/core/JSTimers.java b/ReactAndroid/src/main/java/com/facebook/react/modules/core/JSTimers.java index 9db79d5568b..ed7e1cf94cb 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/core/JSTimers.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/core/JSTimers.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.core; import com.facebook.react.bridge.JavaScriptModule; @@ -12,6 +11,8 @@ import com.facebook.react.bridge.WritableArray; public interface JSTimers extends JavaScriptModule { void callTimers(WritableArray timerIDs); + void callIdleCallbacks(double frameTime); + void emitTimeDriftWarning(String warningMessage); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/core/PermissionAwareActivity.java b/ReactAndroid/src/main/java/com/facebook/react/modules/core/PermissionAwareActivity.java index 8d1149220f0..a196363ebf4 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/core/PermissionAwareActivity.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/core/PermissionAwareActivity.java @@ -1,37 +1,28 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.core; import android.app.Activity; /** - * Interface used to denote activities that can forward permission requests and call - * {@link PermissionListener}s with the permission request results. + * Interface used to denote activities that can forward permission requests and call {@link + * PermissionListener}s with the permission request results. */ public interface PermissionAwareActivity { - /** - * See {@link Activity#checkPermission}. - */ + /** See {@link Activity#checkPermission}. */ int checkPermission(String permission, int pid, int uid); - /** - * See {@link Activity#checkSelfPermission}. - */ + /** See {@link Activity#checkSelfPermission}. */ int checkSelfPermission(String permission); - /** - * See {@link Activity#shouldShowRequestPermissionRationale}. - */ + /** See {@link Activity#shouldShowRequestPermissionRationale}. */ boolean shouldShowRequestPermissionRationale(String permission); - /** - * See {@link Activity#requestPermissions}. - */ + /** See {@link Activity#requestPermissions}. */ void requestPermissions(String[] permissions, int requestCode, PermissionListener listener); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/core/PermissionListener.java b/ReactAndroid/src/main/java/com/facebook/react/modules/core/PermissionListener.java index a8b524fa6c6..569b4ce7f98 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/core/PermissionListener.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/core/PermissionListener.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.core; import android.app.Activity; @@ -16,8 +15,8 @@ import android.app.Activity; public interface PermissionListener { /** - * Method called whenever there's a result to a permission request. It is forwarded from - * {@link Activity#onRequestPermissionsResult}. + * Method called whenever there's a result to a permission request. It is forwarded from {@link + * Activity#onRequestPermissionsResult}. * * @return boolean Whether the PermissionListener can be removed. */ diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/core/RCTNativeAppEventEmitter.java b/ReactAndroid/src/main/java/com/facebook/react/modules/core/RCTNativeAppEventEmitter.java index 2ec210fd09d..7ecd4cd7ff7 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/core/RCTNativeAppEventEmitter.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/core/RCTNativeAppEventEmitter.java @@ -1,20 +1,15 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.core; +import com.facebook.react.bridge.JavaScriptModule; import javax.annotation.Nullable; -import com.facebook.react.bridge.JavaScriptModule; - -/** - * Module that handles global application events. - */ +/** Module that handles global application events. */ public interface RCTNativeAppEventEmitter extends JavaScriptModule { void emit(String eventName, @Nullable Object data); } - diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/core/ReactChoreographer.java b/ReactAndroid/src/main/java/com/facebook/react/modules/core/ReactChoreographer.java index 071c36546fa..16d5bab29c5 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/core/ReactChoreographer.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/core/ReactChoreographer.java @@ -1,53 +1,42 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.core; -import com.facebook.react.bridge.UiThreadUtil; -import java.util.ArrayDeque; -import javax.annotation.Nullable; - import com.facebook.common.logging.FLog; import com.facebook.infer.annotation.Assertions; +import com.facebook.react.bridge.UiThreadUtil; import com.facebook.react.common.ReactConstants; +import java.util.ArrayDeque; +import javax.annotation.Nullable; import javax.annotation.concurrent.GuardedBy; /** - * A simple wrapper around Choreographer that allows us to control the order certain callbacks - * are executed within a given frame. The main difference is that we enforce this is accessed from - * the UI thread: this is because this ordering cannot be guaranteed across multiple threads. + * A simple wrapper around Choreographer that allows us to control the order certain callbacks are + * executed within a given frame. The main difference is that we enforce this is accessed from the + * UI thread: this is because this ordering cannot be guaranteed across multiple threads. */ public class ReactChoreographer { public enum CallbackType { - /** - * For use by perf markers that need to happen immediately after draw - */ + /** For use by perf markers that need to happen immediately after draw */ PERF_MARKERS(0), - /** - * For use by {@link com.facebook.react.uimanager.UIManagerModule} - */ + /** For use by {@link com.facebook.react.uimanager.UIManagerModule} */ DISPATCH_UI(1), - /** - * For use by {@link com.facebook.react.animated.NativeAnimatedModule} - */ + /** For use by {@link com.facebook.react.animated.NativeAnimatedModule} */ NATIVE_ANIMATED_MODULE(2), - /** - * Events that make JS do things. - */ + /** Events that make JS do things. */ TIMERS_EVENTS(3), /** - * Event used to trigger the idle callback. Called after all UI work has been - * dispatched to JS. + * Event used to trigger the idle callback. Called after all UI work has been dispatched to JS. */ IDLE_EVENT(4), ; @@ -80,6 +69,7 @@ public class ReactChoreographer { private @Nullable volatile ChoreographerCompat mChoreographer; private final ReactChoreographerDispatcher mReactChoreographerDispatcher; private final Object mCallbackQueuesLock = new Object(); + @GuardedBy("mCallbackQueuesLock") private final ArrayDeque[] mCallbackQueues; @@ -96,8 +86,7 @@ public class ReactChoreographer { } public void postFrameCallback( - CallbackType type, - ChoreographerCompat.FrameCallback frameCallback) { + CallbackType type, ChoreographerCompat.FrameCallback frameCallback) { synchronized (mCallbackQueuesLock) { mCallbackQueues[type.getOrder()].addLast(frameCallback); mTotalCallbacks++; @@ -119,8 +108,8 @@ public class ReactChoreographer { } /** - * This method writes on mHasPostedCallback and it should be called from another method that - * has the lock mCallbackQueuesLock + * This method writes on mHasPostedCallback and it should be called from another method that has + * the lock mCallbackQueuesLock */ private void postFrameCallbackOnChoreographer() { mChoreographer.postFrameCallback(mReactChoreographerDispatcher); @@ -128,24 +117,24 @@ public class ReactChoreographer { } public void initializeChoreographer(@Nullable final Runnable runnable) { - UiThreadUtil.runOnUiThread(new Runnable() { - @Override - public void run() { - synchronized (ReactChoreographer.class) { - if (mChoreographer == null) { - mChoreographer = ChoreographerCompat.getInstance(); + UiThreadUtil.runOnUiThread( + new Runnable() { + @Override + public void run() { + synchronized (ReactChoreographer.class) { + if (mChoreographer == null) { + mChoreographer = ChoreographerCompat.getInstance(); + } + } + if (runnable != null) { + runnable.run(); + } } - } - if (runnable != null) { - runnable.run(); - } - } - }); + }); } public void removeFrameCallback( - CallbackType type, - ChoreographerCompat.FrameCallback frameCallback) { + CallbackType type, ChoreographerCompat.FrameCallback frameCallback) { synchronized (mCallbackQueuesLock) { if (mCallbackQueues[type.getOrder()].removeFirstOccurrence(frameCallback)) { mTotalCallbacks--; diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/core/Timing.java b/ReactAndroid/src/main/java/com/facebook/react/modules/core/Timing.java index 9fe45e741dc..58f2fd31795 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/core/Timing.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/core/Timing.java @@ -1,20 +1,12 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.core; -import javax.annotation.Nullable; - -import java.util.Comparator; -import java.util.PriorityQueue; -import java.util.concurrent.atomic.AtomicBoolean; - import android.util.SparseArray; - import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.LifecycleEventListener; import com.facebook.react.bridge.ReactApplicationContext; @@ -27,13 +19,15 @@ import com.facebook.react.devsupport.interfaces.DevSupportManager; import com.facebook.react.jstasks.HeadlessJsTaskContext; import com.facebook.react.jstasks.HeadlessJsTaskEventListener; import com.facebook.react.module.annotations.ReactModule; +import java.util.Comparator; +import java.util.PriorityQueue; +import java.util.concurrent.atomic.AtomicBoolean; +import javax.annotation.Nullable; -/** - * Native module for JS timer execution. Timers fire on frame boundaries. - */ +/** Native module for JS timer execution. Timers fire on frame boundaries. */ @ReactModule(name = Timing.NAME) -public final class Timing extends ReactContextBaseJavaModule implements LifecycleEventListener, - HeadlessJsTaskEventListener { +public final class Timing extends ReactContextBaseJavaModule + implements LifecycleEventListener, HeadlessJsTaskEventListener { public static final String NAME = "Timing"; @@ -53,11 +47,7 @@ public final class Timing extends ReactContextBaseJavaModule implements Lifecycl private final int mInterval; private long mTargetTime; - private Timer( - int callbackID, - long initialTargetTime, - int duration, - boolean repeat) { + private Timer(int callbackID, long initialTargetTime, int duration, boolean repeat) { mCallbackID = callbackID; mTargetTime = initialTargetTime; mInterval = duration; @@ -70,9 +60,7 @@ public final class Timing extends ReactContextBaseJavaModule implements Lifecycl // Temporary map for constructing the individual arrays of timers to call private @Nullable WritableArray mTimersToCall = null; - /** - * Calls all timers that have expired since the last time this frame callback was called. - */ + /** Calls all timers that have expired since the last time this frame callback was called. */ @Override public void doFrame(long frameTimeNanos) { if (isPaused.get() && !isRunningTasks.get()) { @@ -155,7 +143,8 @@ public final class Timing extends ReactContextBaseJavaModule implements Lifecycl } if (sendIdleEvents) { - getReactApplicationContext().getJSModule(JSTimers.class) + getReactApplicationContext() + .getJSModule(JSTimers.class) .callIdleCallbacks(absoluteFrameStartTime); } @@ -185,21 +174,22 @@ public final class Timing extends ReactContextBaseJavaModule implements Lifecycl super(reactContext); mDevSupportManager = devSupportManager; // We store timers sorted by finish time. - mTimers = new PriorityQueue( - 11, // Default capacity: for some reason they don't expose a (Comparator) constructor - new Comparator() { - @Override - public int compare(Timer lhs, Timer rhs) { - long diff = lhs.mTargetTime - rhs.mTargetTime; - if (diff == 0) { - return 0; - } else if (diff < 0) { - return -1; - } else { - return 1; - } - } - }); + mTimers = + new PriorityQueue( + 11, // Default capacity: for some reason they don't expose a (Comparator) constructor + new Comparator() { + @Override + public int compare(Timer lhs, Timer rhs) { + long diff = lhs.mTargetTime - rhs.mTargetTime; + if (diff == 0) { + return 0; + } else if (diff < 0) { + return -1; + } else { + return 1; + } + } + }); mTimerIdsToTimers = new SparseArray<>(); mReactChoreographer = ReactChoreographer.getInstance(); } @@ -208,7 +198,7 @@ public final class Timing extends ReactContextBaseJavaModule implements Lifecycl public void initialize() { getReactApplicationContext().addLifecycleEventListener(this); HeadlessJsTaskContext headlessJsTaskContext = - HeadlessJsTaskContext.getInstance(getReactApplicationContext()); + HeadlessJsTaskContext.getInstance(getReactApplicationContext()); headlessJsTaskContext.addTaskEventListener(this); } @@ -245,7 +235,7 @@ public final class Timing extends ReactContextBaseJavaModule implements Lifecycl @Override public void onHeadlessJsTaskFinish(int taskId) { HeadlessJsTaskContext headlessJsTaskContext = - HeadlessJsTaskContext.getInstance(getReactApplicationContext()); + HeadlessJsTaskContext.getInstance(getReactApplicationContext()); if (!headlessJsTaskContext.hasActiveTasks()) { isRunningTasks.set(false); clearFrameCallback(); @@ -258,7 +248,7 @@ public final class Timing extends ReactContextBaseJavaModule implements Lifecycl clearFrameCallback(); clearChoreographerIdleCallback(); HeadlessJsTaskContext headlessJsTaskContext = - HeadlessJsTaskContext.getInstance(getReactApplicationContext()); + HeadlessJsTaskContext.getInstance(getReactApplicationContext()); headlessJsTaskContext.removeTaskEventListener(this); } @@ -279,20 +269,17 @@ public final class Timing extends ReactContextBaseJavaModule implements Lifecycl private void setChoreographerCallback() { if (!mFrameCallbackPosted) { mReactChoreographer.postFrameCallback( - ReactChoreographer.CallbackType.TIMERS_EVENTS, - mTimerFrameCallback); + ReactChoreographer.CallbackType.TIMERS_EVENTS, mTimerFrameCallback); mFrameCallbackPosted = true; } } private void clearFrameCallback() { HeadlessJsTaskContext headlessJsTaskContext = - HeadlessJsTaskContext.getInstance(getReactApplicationContext()); - if (mFrameCallbackPosted && isPaused.get() && - !headlessJsTaskContext.hasActiveTasks()) { + HeadlessJsTaskContext.getInstance(getReactApplicationContext()); + if (mFrameCallbackPosted && isPaused.get() && !headlessJsTaskContext.hasActiveTasks()) { mReactChoreographer.removeFrameCallback( - ReactChoreographer.CallbackType.TIMERS_EVENTS, - mTimerFrameCallback); + ReactChoreographer.CallbackType.TIMERS_EVENTS, mTimerFrameCallback); mFrameCallbackPosted = false; } } @@ -300,8 +287,7 @@ public final class Timing extends ReactContextBaseJavaModule implements Lifecycl private void setChoreographerIdleCallback() { if (!mFrameIdleCallbackPosted) { mReactChoreographer.postFrameCallback( - ReactChoreographer.CallbackType.IDLE_EVENT, - mIdleFrameCallback); + ReactChoreographer.CallbackType.IDLE_EVENT, mIdleFrameCallback); mFrameIdleCallbackPosted = true; } } @@ -309,8 +295,7 @@ public final class Timing extends ReactContextBaseJavaModule implements Lifecycl private void clearChoreographerIdleCallback() { if (mFrameIdleCallbackPosted) { mReactChoreographer.removeFrameCallback( - ReactChoreographer.CallbackType.IDLE_EVENT, - mIdleFrameCallback); + ReactChoreographer.CallbackType.IDLE_EVENT, mIdleFrameCallback); mFrameIdleCallbackPosted = false; } } @@ -335,10 +320,11 @@ public final class Timing extends ReactContextBaseJavaModule implements Lifecycl if (mDevSupportManager.getDevSupportEnabled()) { long driftTime = Math.abs(remoteTime - deviceTime); if (driftTime > 60000) { - getReactApplicationContext().getJSModule(JSTimers.class) - .emitTimeDriftWarning( - "Debugger and device times have drifted by more than 60s. Please correct this by " + - "running adb shell \"date `date +%m%d%H%M%Y.%S`\" on your debugger machine."); + getReactApplicationContext() + .getJSModule(JSTimers.class) + .emitTimeDriftWarning( + "Debugger and device times have drifted by more than 60s. Please correct this by " + + "running adb shell \"date `date +%m%d%H%M%Y.%S`\" on your debugger machine."); } } @@ -347,8 +333,7 @@ public final class Timing extends ReactContextBaseJavaModule implements Lifecycl if (duration == 0 && !repeat) { WritableArray timerToCall = Arguments.createArray(); timerToCall.pushInt(callbackID); - getReactApplicationContext().getJSModule(JSTimers.class) - .callTimers(timerToCall); + getReactApplicationContext().getJSModule(JSTimers.class).callTimers(timerToCall); return; } @@ -378,17 +363,18 @@ public final class Timing extends ReactContextBaseJavaModule implements Lifecycl mSendIdleEvents = sendIdleEvents; } - UiThreadUtil.runOnUiThread(new Runnable() { - @Override - public void run() { - synchronized (mIdleCallbackGuard) { - if (sendIdleEvents) { - setChoreographerIdleCallback(); - } else { - clearChoreographerIdleCallback(); + UiThreadUtil.runOnUiThread( + new Runnable() { + @Override + public void run() { + synchronized (mIdleCallbackGuard) { + if (sendIdleEvents) { + setChoreographerIdleCallback(); + } else { + clearChoreographerIdleCallback(); + } + } } - } - } - }); + }); } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/datepicker/DatePickerDialogFragment.java b/ReactAndroid/src/main/java/com/facebook/react/modules/datepicker/DatePickerDialogFragment.java index 70d4466ad00..35677067b3d 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/datepicker/DatePickerDialogFragment.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/datepicker/DatePickerDialogFragment.java @@ -1,17 +1,11 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.datepicker; -import javax.annotation.Nullable; - -import java.util.Calendar; -import java.util.Locale; - import android.annotation.SuppressLint; import android.app.DatePickerDialog; import android.app.DatePickerDialog.OnDateSetListener; @@ -22,21 +16,20 @@ import android.content.DialogInterface.OnDismissListener; import android.graphics.drawable.ColorDrawable; import android.os.Build; import android.os.Bundle; -import androidx.fragment.app.DialogFragment; import android.widget.DatePicker; +import androidx.fragment.app.DialogFragment; +import java.util.Calendar; +import java.util.Locale; +import javax.annotation.Nullable; @SuppressLint("ValidFragment") public class DatePickerDialogFragment extends DialogFragment { - /** - * Minimum date supported by {@link DatePicker}, 01 Jan 1900 - */ + /** Minimum date supported by {@link DatePicker}, 01 Jan 1900 */ private static final long DEFAULT_MIN_DATE = -2208988800001l; - @Nullable - private OnDateSetListener mOnDateSetListener; - @Nullable - private OnDismissListener mOnDismissListener; + @Nullable private OnDateSetListener mOnDateSetListener; + @Nullable private OnDismissListener mOnDismissListener; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { @@ -56,7 +49,9 @@ public class DatePickerDialogFragment extends DialogFragment { DatePickerMode mode = DatePickerMode.DEFAULT; if (args != null && args.getString(DatePickerDialogModule.ARG_MODE, null) != null) { - mode = DatePickerMode.valueOf(args.getString(DatePickerDialogModule.ARG_MODE).toUpperCase(Locale.US)); + mode = + DatePickerMode.valueOf( + args.getString(DatePickerDialogModule.ARG_MODE).toUpperCase(Locale.US)); } DatePickerDialog dialog = null; @@ -64,22 +59,39 @@ public class DatePickerDialogFragment extends DialogFragment { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { switch (mode) { case CALENDAR: - dialog = new DismissableDatePickerDialog(activityContext, - activityContext.getResources().getIdentifier("CalendarDatePickerDialog", "style", activityContext.getPackageName()), - onDateSetListener, year, month, day); + dialog = + new DismissableDatePickerDialog( + activityContext, + activityContext + .getResources() + .getIdentifier( + "CalendarDatePickerDialog", "style", activityContext.getPackageName()), + onDateSetListener, + year, + month, + day); break; case SPINNER: - dialog = new DismissableDatePickerDialog(activityContext, - android.R.style.Theme_Holo_Light_Dialog, - onDateSetListener, year, month, day); - dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT)); + dialog = + new DismissableDatePickerDialog( + activityContext, + android.R.style.Theme_Holo_Light_Dialog, + onDateSetListener, + year, + month, + day); + dialog + .getWindow() + .setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT)); break; case DEFAULT: - dialog = new DismissableDatePickerDialog(activityContext, onDateSetListener, year, month, day); + dialog = + new DismissableDatePickerDialog(activityContext, onDateSetListener, year, month, day); break; } } else { - dialog = new DismissableDatePickerDialog(activityContext, onDateSetListener, year, month, day); + dialog = + new DismissableDatePickerDialog(activityContext, onDateSetListener, year, month, day); switch (mode) { case CALENDAR: diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/datepicker/DatePickerDialogModule.java b/ReactAndroid/src/main/java/com/facebook/react/modules/datepicker/DatePickerDialogModule.java index 0ac30469346..535ca4178cc 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/datepicker/DatePickerDialogModule.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/datepicker/DatePickerDialogModule.java @@ -1,25 +1,22 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.datepicker; - import android.app.DatePickerDialog.OnDateSetListener; import android.content.DialogInterface; import android.content.DialogInterface.OnDismissListener; import android.os.Bundle; +import android.widget.DatePicker; import androidx.fragment.app.DialogFragment; import androidx.fragment.app.FragmentActivity; import androidx.fragment.app.FragmentManager; -import android.widget.DatePicker; import com.facebook.react.bridge.*; import com.facebook.react.common.annotations.VisibleForTesting; import com.facebook.react.module.annotations.ReactModule; - import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -30,8 +27,7 @@ import javax.annotation.Nullable; @ReactModule(name = DatePickerDialogModule.FRAGMENT_TAG) public class DatePickerDialogModule extends ReactContextBaseJavaModule { - @VisibleForTesting - public static final String FRAGMENT_TAG = "DatePickerAndroid"; + @VisibleForTesting public static final String FRAGMENT_TAG = "DatePickerAndroid"; private static final String ERROR_NO_ACTIVITY = "E_NO_ACTIVITY"; @@ -89,34 +85,25 @@ public class DatePickerDialogModule extends ReactContextBaseJavaModule { * Show a date picker dialog. * * @param options a map containing options. Available keys are: + *

    + *
  • {@code date} (timestamp in milliseconds) the date to show by default + *
  • {@code minDate} (timestamp in milliseconds) the minimum date the user should be + * allowed to select + *
  • {@code maxDate} (timestamp in milliseconds) the maximum date the user should be + * allowed to select + *
  • {@code mode} To set the date picker mode to 'calendar/spinner/default' + *
* - *
    - *
  • {@code date} (timestamp in milliseconds) the date to show by default
  • - *
  • - * {@code minDate} (timestamp in milliseconds) the minimum date the user should be allowed - * to select - *
  • - *
  • - * {@code maxDate} (timestamp in milliseconds) the maximum date the user should be allowed - * to select - *
  • - *
  • - * {@code mode} To set the date picker mode to 'calendar/spinner/default' - *
  • - *
- * - * @param promise This will be invoked with parameters action, year, - * month (0-11), day, where action is {@code dateSetAction} or - * {@code dismissedAction}, depending on what the user did. If the action is - * dismiss, year, month and date are undefined. + * @param promise This will be invoked with parameters action, year, month (0-11), day, where + * action is {@code dateSetAction} or {@code dismissedAction}, depending on what the user did. + * If the action is dismiss, year, month and date are undefined. */ @ReactMethod public void open(@Nullable final ReadableMap options, Promise promise) { FragmentActivity activity = (FragmentActivity) getCurrentActivity(); if (activity == null) { promise.reject( - ERROR_NO_ACTIVITY, - "Tried to open a DatePicker dialog while not attached to an Activity"); + ERROR_NO_ACTIVITY, "Tried to open a DatePicker dialog while not attached to an Activity"); return; } diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/datepicker/DatePickerMode.java b/ReactAndroid/src/main/java/com/facebook/react/modules/datepicker/DatePickerMode.java index 61dc5c620f9..3b3571d23d2 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/datepicker/DatePickerMode.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/datepicker/DatePickerMode.java @@ -1,15 +1,12 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.datepicker; -/** - * Date picker modes - */ +/** Date picker modes */ public enum DatePickerMode { CALENDAR, SPINNER, diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/datepicker/DismissableDatePickerDialog.java b/ReactAndroid/src/main/java/com/facebook/react/modules/datepicker/DismissableDatePickerDialog.java index e73a0ac4343..65398f7c745 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/datepicker/DismissableDatePickerDialog.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/datepicker/DismissableDatePickerDialog.java @@ -1,32 +1,26 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.datepicker; import android.app.DatePickerDialog; import android.content.Context; -import android.os.Build; import android.content.res.TypedArray; +import android.os.Build; import android.util.AttributeSet; import android.widget.DatePicker; - -import javax.annotation.Nullable; import java.lang.reflect.Field; import java.lang.reflect.Method; +import javax.annotation.Nullable; /** - *

- * Certain versions of Android (Jellybean-KitKat) have a bug where when dismissed, the - * {@link DatePickerDialog} still calls the OnDateSetListener. This class works around that issue. - *

+ * Certain versions of Android (Jellybean-KitKat) have a bug where when dismissed, the {@link + * DatePickerDialog} still calls the OnDateSetListener. This class works around that issue. * - *

- * See: Issue 34833 - *

+ *

See: Issue 34833 */ public class DismissableDatePickerDialog extends DatePickerDialog { @@ -69,30 +63,44 @@ public class DismissableDatePickerDialog extends DatePickerDialog { Field datePickerStyleableField = styleableClass.getField("DatePicker"); int[] datePickerStyleable = (int[]) datePickerStyleableField.get(null); - final TypedArray a = context.obtainStyledAttributes(null, datePickerStyleable, android.R.attr.datePickerStyle, 0); + final TypedArray a = + context.obtainStyledAttributes( + null, datePickerStyleable, android.R.attr.datePickerStyle, 0); Field datePickerModeStyleableField = styleableClass.getField("DatePicker_datePickerMode"); int datePickerModeStyleable = datePickerModeStyleableField.getInt(null); final int mode = a.getInt(datePickerModeStyleable, MODE_SPINNER); a.recycle(); if (mode == MODE_SPINNER) { - DatePicker datePicker = (DatePicker) findField(DatePickerDialog.class, DatePicker.class, "mDatePicker").get(this); + DatePicker datePicker = + (DatePicker) + findField(DatePickerDialog.class, DatePicker.class, "mDatePicker").get(this); Class delegateClass = Class.forName("android.widget.DatePickerSpinnerDelegate"); Field delegateField = findField(DatePicker.class, delegateClass, "mDelegate"); Object delegate = delegateField.get(datePicker); Class spinnerDelegateClass; spinnerDelegateClass = Class.forName("android.widget.DatePickerSpinnerDelegate"); - // In 7.0 Nougat for some reason the datePickerMode is ignored and the delegate is DatePickerClockDelegate + // In 7.0 Nougat for some reason the datePickerMode is ignored and the delegate is + // DatePickerClockDelegate if (delegate.getClass() != spinnerDelegateClass) { delegateField.set(datePicker, null); // throw out the DatePickerClockDelegate! datePicker.removeAllViews(); // remove the DatePickerClockDelegate views - Method createSpinnerUIDelegate = DatePicker.class.getDeclaredMethod("createSpinnerUIDelegate", Context.class, AttributeSet.class, int.class, int.class); + Method createSpinnerUIDelegate = + DatePicker.class.getDeclaredMethod( + "createSpinnerUIDelegate", + Context.class, + AttributeSet.class, + int.class, + int.class); createSpinnerUIDelegate.setAccessible(true); // Instantiate a DatePickerSpinnerDelegate throughout createSpinnerUIDelegate method - delegate = createSpinnerUIDelegate.invoke(datePicker, context, null, android.R.attr.datePickerStyle, 0); - delegateField.set(datePicker, delegate); // set the DatePicker.mDelegate to the spinner delegate + delegate = + createSpinnerUIDelegate.invoke( + datePicker, context, null, android.R.attr.datePickerStyle, 0); + delegateField.set( + datePicker, delegate); // set the DatePicker.mDelegate to the spinner delegate datePicker.setCalendarViewShown(false); // Initialize the date for the DatePicker delegate again datePicker.init(year, month, dayOfMonth, this); diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/debug/AnimationsDebugModule.java b/ReactAndroid/src/main/java/com/facebook/react/modules/debug/AnimationsDebugModule.java index df103404c69..be7e2c20378 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/debug/AnimationsDebugModule.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/debug/AnimationsDebugModule.java @@ -1,18 +1,12 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.debug; -import javax.annotation.Nullable; - -import java.util.Locale; - import android.widget.Toast; - import com.facebook.common.logging.FLog; import com.facebook.react.bridge.JSApplicationCausedNativeException; import com.facebook.react.bridge.ReactApplicationContext; @@ -20,8 +14,9 @@ import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.common.ReactConstants; import com.facebook.react.module.annotations.ReactModule; -import com.facebook.react.modules.core.ChoreographerCompat; import com.facebook.react.modules.debug.interfaces.DeveloperSettings; +import java.util.Locale; +import javax.annotation.Nullable; /** * Module that records debug information during transitions (animated navigation events such as @@ -36,8 +31,7 @@ public class AnimationsDebugModule extends ReactContextBaseJavaModule { private @Nullable final DeveloperSettings mCatalystSettings; public AnimationsDebugModule( - ReactApplicationContext reactContext, - DeveloperSettings catalystSettings) { + ReactApplicationContext reactContext, DeveloperSettings catalystSettings) { super(reactContext); mCatalystSettings = catalystSettings; } @@ -49,8 +43,7 @@ public class AnimationsDebugModule extends ReactContextBaseJavaModule { @ReactMethod public void startRecordingFps() { - if (mCatalystSettings == null || - !mCatalystSettings.isAnimationFpsDebugEnabled()) { + if (mCatalystSettings == null || !mCatalystSettings.isAnimationFpsDebugEnabled()) { return; } @@ -58,8 +51,7 @@ public class AnimationsDebugModule extends ReactContextBaseJavaModule { throw new JSApplicationCausedNativeException("Already recording FPS!"); } - mFrameCallback = new FpsDebugFrameCallback( - getReactApplicationContext()); + mFrameCallback = new FpsDebugFrameCallback(getReactApplicationContext()); mFrameCallback.startAndRecordFpsAtEachFrame(); } @@ -82,20 +74,27 @@ public class AnimationsDebugModule extends ReactContextBaseJavaModule { if (fpsInfo == null) { Toast.makeText(getReactApplicationContext(), "Unable to get FPS info", Toast.LENGTH_LONG); } else { - String fpsString = String.format( - Locale.US, - "FPS: %.2f, %d frames (%d expected)", - fpsInfo.fps, - fpsInfo.totalFrames, - fpsInfo.totalExpectedFrames); - String jsFpsString = String.format( - Locale.US, - "JS FPS: %.2f, %d frames (%d expected)", - fpsInfo.jsFps, - fpsInfo.totalJsFrames, - fpsInfo.totalExpectedFrames); - String debugString = fpsString + "\n" + jsFpsString + "\n" + - "Total Time MS: " + String.format(Locale.US, "%d", fpsInfo.totalTimeMs); + String fpsString = + String.format( + Locale.US, + "FPS: %.2f, %d frames (%d expected)", + fpsInfo.fps, + fpsInfo.totalFrames, + fpsInfo.totalExpectedFrames); + String jsFpsString = + String.format( + Locale.US, + "JS FPS: %.2f, %d frames (%d expected)", + fpsInfo.jsFps, + fpsInfo.totalJsFrames, + fpsInfo.totalExpectedFrames); + String debugString = + fpsString + + "\n" + + jsFpsString + + "\n" + + "Total Time MS: " + + String.format(Locale.US, "%d", fpsInfo.totalTimeMs); FLog.d(ReactConstants.TAG, debugString); Toast.makeText(getReactApplicationContext(), debugString, Toast.LENGTH_LONG).show(); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/debug/DevSettingsModule.java b/ReactAndroid/src/main/java/com/facebook/react/modules/debug/DevSettingsModule.java index 3f067c62b0c..af47025d789 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/debug/DevSettingsModule.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/debug/DevSettingsModule.java @@ -1,18 +1,16 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.debug; import com.facebook.react.bridge.BaseJavaModule; -import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; +import com.facebook.react.bridge.UiThreadUtil; import com.facebook.react.devsupport.interfaces.DevSupportManager; import com.facebook.react.module.annotations.ReactModule; -import com.facebook.react.bridge.UiThreadUtil; /** * Module that exposes the URL to the source code map (used for exception stack trace parsing) to JS @@ -36,12 +34,13 @@ public class DevSettingsModule extends BaseJavaModule { @ReactMethod public void reload() { if (mDevSupportManager.getDevSupportEnabled()) { - UiThreadUtil.runOnUiThread(new Runnable() { - @Override - public void run() { - mDevSupportManager.handleReloadJS(); - } - }); + UiThreadUtil.runOnUiThread( + new Runnable() { + @Override + public void run() { + mDevSupportManager.handleReloadJS(); + } + }); } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/debug/DidJSUpdateUiDuringFrameDetector.java b/ReactAndroid/src/main/java/com/facebook/react/modules/debug/DidJSUpdateUiDuringFrameDetector.java index 02171bf163f..291afa1e577 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/debug/DidJSUpdateUiDuringFrameDetector.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/debug/DidJSUpdateUiDuringFrameDetector.java @@ -1,14 +1,13 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.debug; -import com.facebook.react.bridge.ReactBridge; import com.facebook.react.bridge.NotThreadSafeBridgeIdleDebugListener; +import com.facebook.react.bridge.ReactBridge; import com.facebook.react.common.LongArray; import com.facebook.react.modules.core.ChoreographerCompat; import com.facebook.react.uimanager.UIManagerModule; @@ -16,13 +15,12 @@ import com.facebook.react.uimanager.debug.NotThreadSafeViewHierarchyUpdateDebugL /** * Debug object that listens to bridge busy/idle events and UiManagerModule dispatches and uses it - * to calculate whether JS was able to update the UI during a given frame. After being installed - * on a {@link ReactBridge} and a {@link UIManagerModule}, - * {@link #getDidJSHitFrameAndCleanup} should be called once per frame via a - * {@link ChoreographerCompat.FrameCallback}. + * to calculate whether JS was able to update the UI during a given frame. After being installed on + * a {@link ReactBridge} and a {@link UIManagerModule}, {@link #getDidJSHitFrameAndCleanup} should + * be called once per frame via a {@link ChoreographerCompat.FrameCallback}. */ -public class DidJSUpdateUiDuringFrameDetector implements NotThreadSafeBridgeIdleDebugListener, - NotThreadSafeViewHierarchyUpdateDebugListener { +public class DidJSUpdateUiDuringFrameDetector + implements NotThreadSafeBridgeIdleDebugListener, NotThreadSafeViewHierarchyUpdateDebugListener { private final LongArray mTransitionToIdleEvents = LongArray.createWithInitialCapacity(20); private final LongArray mTransitionToBusyEvents = LongArray.createWithInitialCapacity(20); @@ -60,35 +58,33 @@ public class DidJSUpdateUiDuringFrameDetector implements NotThreadSafeBridgeIdle /** * Designed to be called from a {@link ChoreographerCompat.FrameCallback#doFrame} call. * - * There are two 'success' cases that will cause {@link #getDidJSHitFrameAndCleanup} to - * return true for a given frame: + *

There are two 'success' cases that will cause {@link #getDidJSHitFrameAndCleanup} to return + * true for a given frame: * - * 1) UIManagerModule finished dispatching a batched UI update on the UI thread during the frame. - * This means that during the next hierarchy traversal, new UI will be drawn if needed (good). - * 2) The bridge ended the frame idle (meaning there were no JS nor native module calls still in - * flight) AND there was no UiManagerModule update enqueued that didn't also finish. NB: if - * there was one enqueued that actually finished, we'd have case 1), so effectively we just - * look for whether one was enqueued. + *

1) UIManagerModule finished dispatching a batched UI update on the UI thread during the + * frame. This means that during the next hierarchy traversal, new UI will be drawn if needed + * (good). 2) The bridge ended the frame idle (meaning there were no JS nor native module calls + * still in flight) AND there was no UiManagerModule update enqueued that didn't also finish. NB: + * if there was one enqueued that actually finished, we'd have case 1), so effectively we just + * look for whether one was enqueued. * - * NB: This call can only be called once for a given frame time range because it cleans up + *

NB: This call can only be called once for a given frame time range because it cleans up * events it recorded for that frame. * - * NB2: This makes the assumption that onViewHierarchyUpdateEnqueued is called from the - * {@link UIManagerModule#onBatchComplete()}, e.g. while the bridge is still considered busy, - * which means there is no race condition where the bridge has gone idle but a hierarchy update is - * waiting to be enqueued. + *

NB2: This makes the assumption that onViewHierarchyUpdateEnqueued is called from the {@link + * UIManagerModule#onBatchComplete()}, e.g. while the bridge is still considered busy, which means + * there is no race condition where the bridge has gone idle but a hierarchy update is waiting to + * be enqueued. * * @param frameStartTimeNanos the time in nanos that the last frame started * @param frameEndTimeNanos the time in nanos that the last frame ended */ public synchronized boolean getDidJSHitFrameAndCleanup( - long frameStartTimeNanos, - long frameEndTimeNanos) { + long frameStartTimeNanos, long frameEndTimeNanos) { // Case 1: We dispatched a UI update - boolean finishedUiUpdate = hasEventBetweenTimestamps( - mViewHierarchyUpdateFinishedEvents, - frameStartTimeNanos, - frameEndTimeNanos); + boolean finishedUiUpdate = + hasEventBetweenTimestamps( + mViewHierarchyUpdateFinishedEvents, frameStartTimeNanos, frameEndTimeNanos); boolean didEndFrameIdle = didEndFrameIdle(frameStartTimeNanos, frameEndTimeNanos); boolean hitFrame; @@ -96,10 +92,10 @@ public class DidJSUpdateUiDuringFrameDetector implements NotThreadSafeBridgeIdle hitFrame = true; } else { // Case 2: Ended idle but no UI was enqueued during that frame - hitFrame = didEndFrameIdle && !hasEventBetweenTimestamps( - mViewHierarchyUpdateEnqueuedEvents, - frameStartTimeNanos, - frameEndTimeNanos); + hitFrame = + didEndFrameIdle + && !hasEventBetweenTimestamps( + mViewHierarchyUpdateEnqueuedEvents, frameStartTimeNanos, frameEndTimeNanos); } cleanUp(mTransitionToIdleEvents, frameEndTimeNanos); @@ -113,9 +109,7 @@ public class DidJSUpdateUiDuringFrameDetector implements NotThreadSafeBridgeIdle } private static boolean hasEventBetweenTimestamps( - LongArray eventArray, - long startTime, - long endTime) { + LongArray eventArray, long startTime, long endTime) { for (int i = 0; i < eventArray.size(); i++) { long time = eventArray.get(i); if (time >= startTime && time < endTime) { @@ -126,9 +120,7 @@ public class DidJSUpdateUiDuringFrameDetector implements NotThreadSafeBridgeIdle } private static long getLastEventBetweenTimestamps( - LongArray eventArray, - long startTime, - long endTime) { + LongArray eventArray, long startTime, long endTime) { long lastEvent = -1; for (int i = 0; i < eventArray.size(); i++) { long time = eventArray.get(i); @@ -142,14 +134,10 @@ public class DidJSUpdateUiDuringFrameDetector implements NotThreadSafeBridgeIdle } private boolean didEndFrameIdle(long startTime, long endTime) { - long lastIdleTransition = getLastEventBetweenTimestamps( - mTransitionToIdleEvents, - startTime, - endTime); - long lastBusyTransition = getLastEventBetweenTimestamps( - mTransitionToBusyEvents, - startTime, - endTime); + long lastIdleTransition = + getLastEventBetweenTimestamps(mTransitionToIdleEvents, startTime, endTime); + long lastBusyTransition = + getLastEventBetweenTimestamps(mTransitionToBusyEvents, startTime, endTime); if (lastIdleTransition == -1 && lastBusyTransition == -1) { return mWasIdleAtEndOfLastFrame; diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/debug/FpsDebugFrameCallback.java b/ReactAndroid/src/main/java/com/facebook/react/modules/debug/FpsDebugFrameCallback.java index eab166f2a66..00ae7549eb7 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/debug/FpsDebugFrameCallback.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/debug/FpsDebugFrameCallback.java @@ -1,30 +1,27 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.debug; -import com.facebook.react.bridge.UiThreadUtil; -import javax.annotation.Nullable; - -import java.util.Map; -import java.util.TreeMap; - +import com.facebook.infer.annotation.Assertions; import com.facebook.react.bridge.ReactContext; +import com.facebook.react.bridge.UiThreadUtil; import com.facebook.react.modules.core.ChoreographerCompat; import com.facebook.react.uimanager.UIManagerModule; -import com.facebook.infer.annotation.Assertions; +import java.util.Map; +import java.util.TreeMap; +import javax.annotation.Nullable; /** - * Each time a frame is drawn, records whether it should have expected any more callbacks since - * the last time a frame was drawn (i.e. was a frame skipped?). Uses this plus total elapsed time - * to determine FPS. Can also record total and expected frame counts, though NB, since the expected + * Each time a frame is drawn, records whether it should have expected any more callbacks since the + * last time a frame was drawn (i.e. was a frame skipped?). Uses this plus total elapsed time to + * determine FPS. Can also record total and expected frame counts, though NB, since the expected * frame rate is estimated, the expected frame count will lose accuracy over time. * - * Also records the JS FPS, i.e. the frames per second with which either JS updated the UI or was + *

Also records the JS FPS, i.e. the frames per second with which either JS updated the UI or was * idle and not trying to update the UI. This is different from the FPS above since JS rendering is * async. */ @@ -94,9 +91,7 @@ public class FpsDebugFrameCallback extends ChoreographerCompat.FrameCallback { long lastFrameStartTime = mLastFrameTime; mLastFrameTime = l; - if (mDidJSUpdateUiDuringFrameDetector.getDidJSHitFrameAndCleanup( - lastFrameStartTime, - l)) { + if (mDidJSUpdateUiDuringFrameDetector.getDidJSHitFrameAndCleanup(lastFrameStartTime, l)) { mNumFrameCallbacksWithBatchDispatches++; } @@ -109,14 +104,15 @@ public class FpsDebugFrameCallback extends ChoreographerCompat.FrameCallback { if (mIsRecordingFpsInfoAtEachFrame) { Assertions.assertNotNull(mTimeToFps); - FpsInfo info = new FpsInfo( - getNumFrames(), - getNumJSFrames(), - expectedNumFrames, - m4PlusFrameStutters, - getFPS(), - getJSFPS(), - getTotalTimeMS()); + FpsInfo info = + new FpsInfo( + getNumFrames(), + getNumJSFrames(), + expectedNumFrames, + m4PlusFrameStutters, + getFPS(), + getJSFPS(), + getTotalTimeMS()); mTimeToFps.put(System.currentTimeMillis(), info); } mExpectedNumFramesPrev = expectedNumFrames; @@ -127,17 +123,19 @@ public class FpsDebugFrameCallback extends ChoreographerCompat.FrameCallback { public void start() { mShouldStop = false; - mReactContext.getCatalystInstance().addBridgeIdleDebugListener( - mDidJSUpdateUiDuringFrameDetector); + mReactContext + .getCatalystInstance() + .addBridgeIdleDebugListener(mDidJSUpdateUiDuringFrameDetector); mUIManagerModule.setViewHierarchyUpdateDebugListener(mDidJSUpdateUiDuringFrameDetector); final FpsDebugFrameCallback fpsDebugFrameCallback = this; - UiThreadUtil.runOnUiThread(new Runnable() { - @Override - public void run() { - mChoreographer = ChoreographerCompat.getInstance(); - mChoreographer.postFrameCallback(fpsDebugFrameCallback); - } - }); + UiThreadUtil.runOnUiThread( + new Runnable() { + @Override + public void run() { + mChoreographer = ChoreographerCompat.getInstance(); + mChoreographer.postFrameCallback(fpsDebugFrameCallback); + } + }); } public void startAndRecordFpsAtEachFrame() { @@ -148,8 +146,9 @@ public class FpsDebugFrameCallback extends ChoreographerCompat.FrameCallback { public void stop() { mShouldStop = true; - mReactContext.getCatalystInstance().removeBridgeIdleDebugListener( - mDidJSUpdateUiDuringFrameDetector); + mReactContext + .getCatalystInstance() + .removeBridgeIdleDebugListener(mDidJSUpdateUiDuringFrameDetector); mUIManagerModule.setViewHierarchyUpdateDebugListener(null); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/debug/SourceCodeModule.java b/ReactAndroid/src/main/java/com/facebook/react/modules/debug/SourceCodeModule.java index b43061ea712..03ffb7de026 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/debug/SourceCodeModule.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/debug/SourceCodeModule.java @@ -1,21 +1,18 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.debug; -import javax.annotation.Nullable; - -import java.util.HashMap; -import java.util.Map; - import com.facebook.infer.annotation.Assertions; import com.facebook.react.bridge.BaseJavaModule; import com.facebook.react.bridge.ReactContext; import com.facebook.react.module.annotations.ReactModule; +import java.util.HashMap; +import java.util.Map; +import javax.annotation.Nullable; /** * Module that exposes the URL to the source code map (used for exception stack trace parsing) to JS @@ -41,9 +38,9 @@ public class SourceCodeModule extends BaseJavaModule { HashMap constants = new HashMap<>(); String sourceURL = - Assertions.assertNotNull( - mReactContext.getCatalystInstance().getSourceURL(), - "No source URL loaded, have you initialised the instance?"); + Assertions.assertNotNull( + mReactContext.getCatalystInstance().getSourceURL(), + "No source URL loaded, have you initialised the instance?"); constants.put("scriptURL", sourceURL); return constants; diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/debug/interfaces/DeveloperSettings.java b/ReactAndroid/src/main/java/com/facebook/react/modules/debug/interfaces/DeveloperSettings.java index 79254fdbff9..faa91e4f79a 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/debug/interfaces/DeveloperSettings.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/debug/interfaces/DeveloperSettings.java @@ -1,55 +1,35 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.debug.interfaces; -/** - * Provides access to React Native developers settings. - */ +/** Provides access to React Native developers settings. */ public interface DeveloperSettings { - /** - * @return whether an overlay showing current FPS should be shown. - */ + /** @return whether an overlay showing current FPS should be shown. */ boolean isFpsDebugEnabled(); - /** - * @return Whether debug information about transitions should be displayed. - */ + /** @return Whether debug information about transitions should be displayed. */ boolean isAnimationFpsDebugEnabled(); - /** - * @return Whether dev mode should be enabled in JS bundles. - */ + /** @return Whether dev mode should be enabled in JS bundles. */ boolean isJSDevModeEnabled(); - /** - * @return Whether JS bundle should be minified. - */ + /** @return Whether JS bundle should be minified. */ boolean isJSMinifyEnabled(); - /** - * @return Whether element inspector is enabled. - */ + /** @return Whether element inspector is enabled. */ boolean isElementInspectorEnabled(); - /** - * @return Whether Nuclide JS debugging is enabled. - */ + /** @return Whether Nuclide JS debugging is enabled. */ boolean isNuclideJSDebugEnabled(); - /** - * @return Whether remote JS debugging is enabled. - */ + /** @return Whether remote JS debugging is enabled. */ boolean isRemoteJSDebugEnabled(); - /** - * Enable/Disable remote JS debugging. - */ + /** Enable/Disable remote JS debugging. */ void setRemoteJSDebugEnabled(boolean remoteJSDebugEnabled); - } diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/deviceinfo/DeviceInfoModule.java b/ReactAndroid/src/main/java/com/facebook/react/modules/deviceinfo/DeviceInfoModule.java index 97629bf9048..ab7c80c4397 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/deviceinfo/DeviceInfoModule.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/deviceinfo/DeviceInfoModule.java @@ -1,19 +1,12 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.deviceinfo; -import javax.annotation.Nullable; - -import java.util.HashMap; -import java.util.Map; - import android.content.Context; - import com.facebook.react.bridge.BaseJavaModule; import com.facebook.react.bridge.LifecycleEventListener; import com.facebook.react.bridge.ReactApplicationContext; @@ -21,13 +14,14 @@ import com.facebook.react.module.annotations.ReactModule; import com.facebook.react.modules.core.DeviceEventManagerModule; import com.facebook.react.turbomodule.core.interfaces.TurboModule; import com.facebook.react.uimanager.DisplayMetricsHolder; +import java.util.HashMap; +import java.util.Map; +import javax.annotation.Nullable; -/** - * Module that exposes Android Constants to JS. - */ +/** Module that exposes Android Constants to JS. */ @ReactModule(name = DeviceInfoModule.NAME) -public class DeviceInfoModule extends BaseJavaModule implements - LifecycleEventListener, TurboModule { +public class DeviceInfoModule extends BaseJavaModule + implements LifecycleEventListener, TurboModule { public static final String NAME = "DeviceInfo"; @@ -54,9 +48,7 @@ public class DeviceInfoModule extends BaseJavaModule implements @Override public @Nullable Map getConstants() { HashMap constants = new HashMap<>(); - constants.put( - "Dimensions", - DisplayMetricsHolder.getDisplayMetricsMap(mFontScale)); + constants.put("Dimensions", DisplayMetricsHolder.getDisplayMetricsMap(mFontScale)); return constants; } @@ -74,12 +66,10 @@ public class DeviceInfoModule extends BaseJavaModule implements } @Override - public void onHostPause() { - } + public void onHostPause() {} @Override - public void onHostDestroy() { - } + public void onHostDestroy() {} public void emitUpdateDimensionsEvent() { if (mReactApplicationContext == null) { diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/dialog/AlertFragment.java b/ReactAndroid/src/main/java/com/facebook/react/modules/dialog/AlertFragment.java index a3bb7ca00d1..96ab234555f 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/dialog/AlertFragment.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/dialog/AlertFragment.java @@ -1,25 +1,21 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.dialog; -import javax.annotation.Nullable; - import android.annotation.SuppressLint; import android.app.AlertDialog; import android.app.Dialog; -import android.content.DialogInterface; import android.content.Context; +import android.content.DialogInterface; import android.os.Bundle; import androidx.fragment.app.DialogFragment; +import javax.annotation.Nullable; -/** - * A fragment used to display the dialog. - */ +/** A fragment used to display the dialog. */ public class AlertFragment extends DialogFragment implements DialogInterface.OnClickListener { /* package */ static final String ARG_TITLE = "title"; @@ -32,7 +28,7 @@ public class AlertFragment extends DialogFragment implements DialogInterface.OnC private final @Nullable DialogModule.AlertFragmentListener mListener; public AlertFragment() { - mListener = null; + mListener = null; } @SuppressLint("ValidFragment") @@ -43,8 +39,8 @@ public class AlertFragment extends DialogFragment implements DialogInterface.OnC public static Dialog createDialog( Context activityContext, Bundle arguments, DialogInterface.OnClickListener fragment) { - AlertDialog.Builder builder = new AlertDialog.Builder(activityContext) - .setTitle(arguments.getString(ARG_TITLE)); + AlertDialog.Builder builder = + new AlertDialog.Builder(activityContext).setTitle(arguments.getString(ARG_TITLE)); if (arguments.containsKey(ARG_BUTTON_POSITIVE)) { builder.setPositiveButton(arguments.getString(ARG_BUTTON_POSITIVE), fragment); diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/dialog/DialogModule.java b/ReactAndroid/src/main/java/com/facebook/react/modules/dialog/DialogModule.java index 2f7cfc487c0..4621f493669 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/dialog/DialogModule.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/dialog/DialogModule.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.dialog; import android.app.Activity; @@ -14,7 +13,6 @@ import android.content.DialogInterface.OnDismissListener; import android.os.Bundle; import androidx.fragment.app.FragmentActivity; import androidx.fragment.app.FragmentManager; - import com.facebook.common.logging.FLog; import com.facebook.react.bridge.Callback; import com.facebook.react.bridge.LifecycleEventListener; @@ -28,7 +26,6 @@ import com.facebook.react.bridge.UiThreadUtil; import com.facebook.react.common.MapBuilder; import com.facebook.react.module.annotations.ReactModule; import java.util.Map; - import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -50,12 +47,13 @@ public class DialogModule extends ReactContextBaseJavaModule implements Lifecycl /* package */ static final String KEY_ITEMS = "items"; /* package */ static final String KEY_CANCELABLE = "cancelable"; - /* package */ static final Map CONSTANTS = MapBuilder.of( - ACTION_BUTTON_CLICKED, ACTION_BUTTON_CLICKED, - ACTION_DISMISSED, ACTION_DISMISSED, - KEY_BUTTON_POSITIVE, DialogInterface.BUTTON_POSITIVE, - KEY_BUTTON_NEGATIVE, DialogInterface.BUTTON_NEGATIVE, - KEY_BUTTON_NEUTRAL, DialogInterface.BUTTON_NEUTRAL); + /* package */ static final Map CONSTANTS = + MapBuilder.of( + ACTION_BUTTON_CLICKED, ACTION_BUTTON_CLICKED, + ACTION_DISMISSED, ACTION_DISMISSED, + KEY_BUTTON_POSITIVE, DialogInterface.BUTTON_POSITIVE, + KEY_BUTTON_NEGATIVE, DialogInterface.BUTTON_NEGATIVE, + KEY_BUTTON_NEUTRAL, DialogInterface.BUTTON_NEUTRAL); private boolean mIsInForeground; @@ -93,8 +91,7 @@ public class DialogModule extends ReactContextBaseJavaModule implements Lifecycl if (!mIsInForeground) { return; } - AlertFragment oldFragment = - (AlertFragment) mFragmentManager.findFragmentByTag(FRAGMENT_TAG); + AlertFragment oldFragment = (AlertFragment) mFragmentManager.findFragmentByTag(FRAGMENT_TAG); if (oldFragment != null && oldFragment.isResumed()) { oldFragment.dismiss(); } @@ -167,8 +164,7 @@ public class DialogModule extends ReactContextBaseJavaModule implements Lifecycl } @Override - public void onHostDestroy() { - } + public void onHostDestroy() {} @Override public void onHostResume() { @@ -184,9 +180,7 @@ public class DialogModule extends ReactContextBaseJavaModule implements Lifecycl @ReactMethod public void showAlert( - ReadableMap options, - Callback errorCallback, - final Callback actionCallback) { + ReadableMap options, Callback errorCallback, final Callback actionCallback) { final FragmentManagerHelper fragmentManagerHelper = getFragmentManagerHelper(); if (fragmentManagerHelper == null) { errorCallback.invoke("Tried to show an alert while not attached to an Activity"); @@ -212,7 +206,7 @@ public class DialogModule extends ReactContextBaseJavaModule implements Lifecycl if (options.hasKey(KEY_ITEMS)) { ReadableArray items = options.getArray(KEY_ITEMS); CharSequence[] itemsArray = new CharSequence[items.size()]; - for (int i = 0; i < items.size(); i ++) { + for (int i = 0; i < items.size(); i++) { itemsArray[i] = items.getString(i); } args.putCharSequenceArray(AlertFragment.ARG_ITEMS, itemsArray); @@ -221,20 +215,20 @@ public class DialogModule extends ReactContextBaseJavaModule implements Lifecycl args.putBoolean(KEY_CANCELABLE, options.getBoolean(KEY_CANCELABLE)); } - UiThreadUtil.runOnUiThread(new Runnable() { - @Override - public void run() { - fragmentManagerHelper.showNewAlert(args, actionCallback); - } - }); - + UiThreadUtil.runOnUiThread( + new Runnable() { + @Override + public void run() { + fragmentManagerHelper.showNewAlert(args, actionCallback); + } + }); } /** - * Creates a new helper to work with FragmentManager. - * Returns null if we're not attached to an Activity. + * Creates a new helper to work with FragmentManager. Returns null if we're not attached to an + * Activity. * - * DO NOT HOLD LONG-LIVED REFERENCES TO THE OBJECT RETURNED BY THIS METHOD, AS THIS WILL CAUSE + *

DO NOT HOLD LONG-LIVED REFERENCES TO THE OBJECT RETURNED BY THIS METHOD, AS THIS WILL CAUSE * MEMORY LEAKS. */ private @Nullable FragmentManagerHelper getFragmentManagerHelper() { diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/fabric/ReactFabric.java b/ReactAndroid/src/main/java/com/facebook/react/modules/fabric/ReactFabric.java index fbf3233688b..5da3c22d192 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/fabric/ReactFabric.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/fabric/ReactFabric.java @@ -1,25 +1,24 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.fabric; import com.facebook.react.bridge.JavaScriptModule; /** - * JS module used to execute Fabric specific methods. - * Note: This is a temporary class that will be replaced when Fabric is fully integrated with the - * rest of the modules. + * JS module used to execute Fabric specific methods. Note: This is a temporary class that will be + * replaced when Fabric is fully integrated with the rest of the modules. */ public interface ReactFabric extends JavaScriptModule { /** * JS method used to unmount Fabric surfaces. - * @param rootTag {@link int} react tag of Root {@link com.facebook.react.uimanager.ReactShadowNode} + * + * @param rootTag {@link int} react tag of Root {@link + * com.facebook.react.uimanager.ReactShadowNode} */ void unmountComponentAtNode(int rootTag); - } diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/fresco/FrescoModule.java b/ReactAndroid/src/main/java/com/facebook/react/modules/fresco/FrescoModule.java index 4481cd42a4c..c972c0b616c 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/fresco/FrescoModule.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/fresco/FrescoModule.java @@ -1,17 +1,13 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.fresco; -import java.util.HashSet; - import android.content.Context; import androidx.annotation.Nullable; - import com.facebook.common.logging.FLog; import com.facebook.drawee.backends.pipeline.Fresco; import com.facebook.imagepipeline.backends.okhttp3.OkHttpImagePipelineConfigFactory; @@ -27,8 +23,7 @@ import com.facebook.react.modules.common.ModuleDataCleaner; import com.facebook.react.modules.network.CookieJarContainer; import com.facebook.react.modules.network.ForwardingCookieHandler; import com.facebook.react.modules.network.OkHttpClientProvider; -import com.facebook.soloader.SoLoader; - +import java.util.HashSet; import okhttp3.JavaNetCookieJar; import okhttp3.OkHttpClient; @@ -38,8 +33,8 @@ import okhttp3.OkHttpClient; *

Does not expose any methods to JavaScript code. For initialization and cleanup only. */ @ReactModule(name = FrescoModule.NAME, needsEagerInit = true) -public class FrescoModule extends ReactContextBaseJavaModule implements - ModuleDataCleaner.Cleanable, LifecycleEventListener { +public class FrescoModule extends ReactContextBaseJavaModule + implements ModuleDataCleaner.Cleanable, LifecycleEventListener { public static final String NAME = "FrescoModule"; private final boolean mClearOnDestroy; @@ -48,8 +43,8 @@ public class FrescoModule extends ReactContextBaseJavaModule implements private static boolean sHasBeenInitialized = false; /** - * Create a new Fresco module with a default configuration (or the previously given - * configuration via {@link #FrescoModule(ReactApplicationContext, boolean, ImagePipelineConfig)}. + * Create a new Fresco module with a default configuration (or the previously given configuration + * via {@link #FrescoModule(ReactApplicationContext, boolean, ImagePipelineConfig)}. * * @param reactContext the context to use */ @@ -58,36 +53,32 @@ public class FrescoModule extends ReactContextBaseJavaModule implements } /** - * Create a new Fresco module with a default configuration (or the previously given - * configuration via {@link #FrescoModule(ReactApplicationContext, boolean, ImagePipelineConfig)}. + * Create a new Fresco module with a default configuration (or the previously given configuration + * via {@link #FrescoModule(ReactApplicationContext, boolean, ImagePipelineConfig)}. * - * @param clearOnDestroy whether to clear the memory cache in onHostDestroy: this should be - * {@code true} for pure RN apps and {@code false} for apps that use Fresco outside of RN - * as well + * @param clearOnDestroy whether to clear the memory cache in onHostDestroy: this should be {@code + * true} for pure RN apps and {@code false} for apps that use Fresco outside of RN as well * @param reactContext the context to use - * */ public FrescoModule(ReactApplicationContext reactContext, boolean clearOnDestroy) { this(reactContext, clearOnDestroy, null); } /** - * Create a new Fresco module with a given ImagePipelineConfig. - * This should only be called when the module has not been initialized yet. - * You can use {@link #hasBeenInitialized()} to check this and call - * {@link #FrescoModule(ReactApplicationContext)} if it is already initialized. + * Create a new Fresco module with a given ImagePipelineConfig. This should only be called when + * the module has not been initialized yet. You can use {@link #hasBeenInitialized()} to check + * this and call {@link #FrescoModule(ReactApplicationContext)} if it is already initialized. * Otherwise, the given Fresco configuration will be ignored. * * @param reactContext the context to use - * @param clearOnDestroy whether to clear the memory cache in onHostDestroy: this should be - * {@code true} for pure RN apps and {@code false} for apps that use Fresco outside of RN - * as well + * @param clearOnDestroy whether to clear the memory cache in onHostDestroy: this should be {@code + * true} for pure RN apps and {@code false} for apps that use Fresco outside of RN as well * @param config the Fresco configuration, which will only be used for the first initialization */ public FrescoModule( - ReactApplicationContext reactContext, - boolean clearOnDestroy, - @Nullable ImagePipelineConfig config) { + ReactApplicationContext reactContext, + boolean clearOnDestroy, + @Nullable ImagePipelineConfig config) { super(reactContext); mClearOnDestroy = clearOnDestroy; mConfig = config; @@ -108,7 +99,7 @@ public class FrescoModule extends ReactContextBaseJavaModule implements FLog.w( ReactConstants.TAG, "Fresco has already been initialized with a different config. " - + "The new Fresco configuration will be ignored!"); + + "The new Fresco configuration will be ignored!"); } mConfig = null; } @@ -125,9 +116,9 @@ public class FrescoModule extends ReactContextBaseJavaModule implements } /** - * Check whether the FrescoModule has already been initialized. If this is the case, - * Calls to {@link #FrescoModule(ReactApplicationContext, ImagePipelineConfig)} will - * ignore the given configuration. + * Check whether the FrescoModule has already been initialized. If this is the case, Calls to + * {@link #FrescoModule(ReactApplicationContext, ImagePipelineConfig)} will ignore the given + * configuration. * * @return true if this module has already been initialized */ @@ -140,8 +131,8 @@ public class FrescoModule extends ReactContextBaseJavaModule implements } /** - * Get the default Fresco configuration builder. - * Allows adding of configuration options in addition to the default values. + * Get the default Fresco configuration builder. Allows adding of configuration options in + * addition to the default values. * * @return {@link ImagePipelineConfig.Builder} that has been initialized with default values */ @@ -157,20 +148,17 @@ public class FrescoModule extends ReactContextBaseJavaModule implements ForwardingCookieHandler handler = new ForwardingCookieHandler(context); container.setCookieJar(new JavaNetCookieJar(handler)); - return OkHttpImagePipelineConfigFactory - .newBuilder(context.getApplicationContext(), client) - .setNetworkFetcher(new ReactOkHttpNetworkFetcher(client)) - .setDownsampleEnabled(false) - .setRequestListeners(requestListeners); + return OkHttpImagePipelineConfigFactory.newBuilder(context.getApplicationContext(), client) + .setNetworkFetcher(new ReactOkHttpNetworkFetcher(client)) + .setDownsampleEnabled(false) + .setRequestListeners(requestListeners); } @Override - public void onHostResume() { - } + public void onHostResume() {} @Override - public void onHostPause() { - } + public void onHostPause() {} @Override public void onHostDestroy() { diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/fresco/ReactNetworkImageRequest.java b/ReactAndroid/src/main/java/com/facebook/react/modules/fresco/ReactNetworkImageRequest.java index 2b5dc2a5257..489980dc5db 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/fresco/ReactNetworkImageRequest.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/fresco/ReactNetworkImageRequest.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.fresco; import com.facebook.imagepipeline.request.ImageRequest; @@ -17,8 +16,8 @@ public class ReactNetworkImageRequest extends ImageRequest { /** Headers for the request */ private final ReadableMap mHeaders; - public static ReactNetworkImageRequest fromBuilderWithHeaders(ImageRequestBuilder builder, - ReadableMap headers) { + public static ReactNetworkImageRequest fromBuilderWithHeaders( + ImageRequestBuilder builder, ReadableMap headers) { return new ReactNetworkImageRequest(builder, headers); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/fresco/ReactOkHttpNetworkFetcher.java b/ReactAndroid/src/main/java/com/facebook/react/modules/fresco/ReactOkHttpNetworkFetcher.java index e14f97081a2..643128cbbd8 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/fresco/ReactOkHttpNetworkFetcher.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/fresco/ReactOkHttpNetworkFetcher.java @@ -1,26 +1,21 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.fresco; -import com.facebook.imagepipeline.producers.NetworkFetcher; -import com.facebook.imagepipeline.backends.okhttp3.OkHttpNetworkFetcher; import android.net.Uri; import android.os.SystemClock; - import com.facebook.imagepipeline.backends.okhttp3.OkHttpNetworkFetcher; +import com.facebook.imagepipeline.producers.NetworkFetcher; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.ReadableMapKeySetIterator; - import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Executor; - import okhttp3.CacheControl; import okhttp3.Headers; import okhttp3.OkHttpClient; @@ -33,9 +28,7 @@ class ReactOkHttpNetworkFetcher extends OkHttpNetworkFetcher { private final OkHttpClient mOkHttpClient; private final Executor mCancellationExecutor; - /** - * @param okHttpClient client to use - */ + /** @param okHttpClient client to use */ public ReactOkHttpNetworkFetcher(OkHttpClient okHttpClient) { super(okHttpClient); mOkHttpClient = okHttpClient; @@ -44,7 +37,7 @@ class ReactOkHttpNetworkFetcher extends OkHttpNetworkFetcher { private Map getHeaders(ReadableMap readableMap) { if (readableMap == null) { - return null; + return null; } ReadableMapKeySetIterator iterator = readableMap.keySetIterator(); Map map = new HashMap<>(); @@ -57,24 +50,27 @@ class ReactOkHttpNetworkFetcher extends OkHttpNetworkFetcher { } @Override - public void fetch(final OkHttpNetworkFetcher.OkHttpNetworkFetchState fetchState, final NetworkFetcher.Callback callback) { + public void fetch( + final OkHttpNetworkFetcher.OkHttpNetworkFetchState fetchState, + final NetworkFetcher.Callback callback) { fetchState.submitTime = SystemClock.elapsedRealtime(); final Uri uri = fetchState.getUri(); Map requestHeaders = null; if (fetchState.getContext().getImageRequest() instanceof ReactNetworkImageRequest) { - ReactNetworkImageRequest networkImageRequest = (ReactNetworkImageRequest) - fetchState.getContext().getImageRequest(); + ReactNetworkImageRequest networkImageRequest = + (ReactNetworkImageRequest) fetchState.getContext().getImageRequest(); requestHeaders = getHeaders(networkImageRequest.getHeaders()); } if (requestHeaders == null) { requestHeaders = Collections.emptyMap(); } - final Request request = new Request.Builder() - .cacheControl(new CacheControl.Builder().noStore().build()) - .url(uri.toString()) - .headers(Headers.of(requestHeaders)) - .get() - .build(); + final Request request = + new Request.Builder() + .cacheControl(new CacheControl.Builder().noStore().build()) + .url(uri.toString()) + .headers(Headers.of(requestHeaders)) + .get() + .build(); fetchWithRequest(fetchState, callback, request); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/fresco/SystraceRequestListener.java b/ReactAndroid/src/main/java/com/facebook/react/modules/fresco/SystraceRequestListener.java index 0ad43b0188c..7e433da7797 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/fresco/SystraceRequestListener.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/fresco/SystraceRequestListener.java @@ -5,23 +5,19 @@ package com.facebook.react.modules.fresco; -import java.util.HashMap; -import java.util.Map; - import android.util.Pair; - import com.facebook.imagepipeline.listener.BaseRequestListener; import com.facebook.imagepipeline.request.ImageRequest; import com.facebook.systrace.Systrace; +import java.util.HashMap; +import java.util.Map; -/** - * Logs requests to Systrace - */ +/** Logs requests to Systrace */ public class SystraceRequestListener extends BaseRequestListener { int mCurrentID = 0; - Map> mProducerID = new HashMap<>(); - Map> mRequestsID = new HashMap<>(); + Map> mProducerID = new HashMap<>(); + Map> mRequestsID = new HashMap<>(); @Override public void onProducerStart(String requestId, String producerName) { @@ -33,50 +29,36 @@ public class SystraceRequestListener extends BaseRequestListener { entryName.append("FRESCO_PRODUCER_"); entryName.append(producerName.replace(':', '_')); - Pair requestPair = Pair.create(mCurrentID, entryName.toString()); - Systrace.beginAsyncSection( - Systrace.TRACE_TAG_REACT_FRESCO, - requestPair.second, - mCurrentID); + Pair requestPair = Pair.create(mCurrentID, entryName.toString()); + Systrace.beginAsyncSection(Systrace.TRACE_TAG_REACT_FRESCO, requestPair.second, mCurrentID); mProducerID.put(requestId, requestPair); mCurrentID++; } @Override public void onProducerFinishWithSuccess( - String requestId, - String producerName, - Map extraMap) { + String requestId, String producerName, Map extraMap) { if (!Systrace.isTracing(Systrace.TRACE_TAG_REACT_FRESCO)) { return; } if (mProducerID.containsKey(requestId)) { Pair entry = mProducerID.get(requestId); - Systrace.endAsyncSection( - Systrace.TRACE_TAG_REACT_FRESCO, - entry.second, - entry.first); + Systrace.endAsyncSection(Systrace.TRACE_TAG_REACT_FRESCO, entry.second, entry.first); mProducerID.remove(requestId); } } @Override public void onProducerFinishWithFailure( - String requestId, - String producerName, - Throwable throwable, - Map extraMap) { + String requestId, String producerName, Throwable throwable, Map extraMap) { if (!Systrace.isTracing(Systrace.TRACE_TAG_REACT_FRESCO)) { return; } if (mProducerID.containsKey(requestId)) { Pair entry = mProducerID.get(requestId); - Systrace.endAsyncSection( - Systrace.TRACE_TAG_REACT_FRESCO, - entry.second, - entry.first); + Systrace.endAsyncSection(Systrace.TRACE_TAG_REACT_FRESCO, entry.second, entry.first); mProducerID.remove(requestId); } } @@ -90,10 +72,7 @@ public class SystraceRequestListener extends BaseRequestListener { if (mProducerID.containsKey(requestId)) { Pair entry = mProducerID.get(requestId); - Systrace.endAsyncSection( - Systrace.TRACE_TAG_REACT_FRESCO, - entry.second, - entry.first); + Systrace.endAsyncSection(Systrace.TRACE_TAG_REACT_FRESCO, entry.second, entry.first); mProducerID.remove(requestId); } } @@ -112,17 +91,12 @@ public class SystraceRequestListener extends BaseRequestListener { entryName.append("_"); entryName.append(producerEventName.replace(':', '_')); Systrace.traceInstant( - Systrace.TRACE_TAG_REACT_FRESCO, - entryName.toString(), - Systrace.EventScope.THREAD); + Systrace.TRACE_TAG_REACT_FRESCO, entryName.toString(), Systrace.EventScope.THREAD); } @Override public void onRequestStart( - ImageRequest request, - Object callerContext, - String requestId, - boolean isPrefetch) { + ImageRequest request, Object callerContext, String requestId, boolean isPrefetch) { if (!Systrace.isTracing(Systrace.TRACE_TAG_REACT_FRESCO)) { return; } @@ -131,11 +105,8 @@ public class SystraceRequestListener extends BaseRequestListener { entryName.append("FRESCO_REQUEST_"); entryName.append(request.getSourceUri().toString().replace(':', '_')); - Pair requestPair = Pair.create(mCurrentID, entryName.toString()); - Systrace.beginAsyncSection( - Systrace.TRACE_TAG_REACT_FRESCO, - requestPair.second, - mCurrentID); + Pair requestPair = Pair.create(mCurrentID, entryName.toString()); + Systrace.beginAsyncSection(Systrace.TRACE_TAG_REACT_FRESCO, requestPair.second, mCurrentID); mRequestsID.put(requestId, requestPair); mCurrentID++; } @@ -148,30 +119,21 @@ public class SystraceRequestListener extends BaseRequestListener { if (mRequestsID.containsKey(requestId)) { Pair entry = mRequestsID.get(requestId); - Systrace.endAsyncSection( - Systrace.TRACE_TAG_REACT_FRESCO, - entry.second, - entry.first); + Systrace.endAsyncSection(Systrace.TRACE_TAG_REACT_FRESCO, entry.second, entry.first); mRequestsID.remove(requestId); } } @Override public void onRequestFailure( - ImageRequest request, - String requestId, - Throwable throwable, - boolean isPrefetch) { + ImageRequest request, String requestId, Throwable throwable, boolean isPrefetch) { if (!Systrace.isTracing(Systrace.TRACE_TAG_REACT_FRESCO)) { return; } if (mRequestsID.containsKey(requestId)) { Pair entry = mRequestsID.get(requestId); - Systrace.endAsyncSection( - Systrace.TRACE_TAG_REACT_FRESCO, - entry.second, - entry.first); + Systrace.endAsyncSection(Systrace.TRACE_TAG_REACT_FRESCO, entry.second, entry.first); mRequestsID.remove(requestId); } } @@ -184,10 +146,7 @@ public class SystraceRequestListener extends BaseRequestListener { if (mRequestsID.containsKey(requestId)) { Pair entry = mRequestsID.get(requestId); - Systrace.endAsyncSection( - Systrace.TRACE_TAG_REACT_FRESCO, - entry.second, - entry.first); + Systrace.endAsyncSection(Systrace.TRACE_TAG_REACT_FRESCO, entry.second, entry.first); mRequestsID.remove(requestId); } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/i18nmanager/I18nManagerModule.java b/ReactAndroid/src/main/java/com/facebook/react/modules/i18nmanager/I18nManagerModule.java index 9e15606235c..5f827e0d86d 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/i18nmanager/I18nManagerModule.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/i18nmanager/I18nManagerModule.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.i18nmanager; import android.content.Context; @@ -16,9 +15,7 @@ import com.facebook.react.module.annotations.ReactModule; import java.util.Locale; import java.util.Map; -/** - * {@link NativeModule} that allows JS to set allowRTL and get isRTL status. - */ +/** {@link NativeModule} that allows JS to set allowRTL and get isRTL status. */ @ReactModule(name = I18nManagerModule.NAME) public class I18nManagerModule extends ContextBaseJavaModule { diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/i18nmanager/I18nUtil.java b/ReactAndroid/src/main/java/com/facebook/react/modules/i18nmanager/I18nUtil.java index 2d0bce0bb6d..6b6517d651e 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/i18nmanager/I18nUtil.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/i18nmanager/I18nUtil.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.i18nmanager; import android.content.Context; @@ -16,17 +15,14 @@ import java.util.Locale; public class I18nUtil { private static I18nUtil sharedI18nUtilInstance = null; - private static final String SHARED_PREFS_NAME = - "com.facebook.react.modules.i18nmanager.I18nUtil"; - private static final String KEY_FOR_PREFS_ALLOWRTL = - "RCTI18nUtil_allowRTL"; - private static final String KEY_FOR_PREFS_FORCERTL = - "RCTI18nUtil_forceRTL"; + private static final String SHARED_PREFS_NAME = "com.facebook.react.modules.i18nmanager.I18nUtil"; + private static final String KEY_FOR_PREFS_ALLOWRTL = "RCTI18nUtil_allowRTL"; + private static final String KEY_FOR_PREFS_FORCERTL = "RCTI18nUtil_forceRTL"; private static final String KEY_FOR_PERFS_MAKE_RTL_FLIP_LEFT_AND_RIGHT_STYLES = - "RCTI18nUtil_makeRTLFlipLeftAndRightStyles"; + "RCTI18nUtil_makeRTLFlipLeftAndRightStyles"; private I18nUtil() { - // Exists only to defeat instantiation. + // Exists only to defeat instantiation. } public static I18nUtil getInstance() { @@ -37,22 +33,20 @@ public class I18nUtil { } /** - * Check if the device is currently running on an RTL locale. - * This only happens when the app: - * - is forcing RTL layout, regardless of the active language (for development purpose) - * - allows RTL layout when using RTL locale + * Check if the device is currently running on an RTL locale. This only happens when the app: - is + * forcing RTL layout, regardless of the active language (for development purpose) - allows RTL + * layout when using RTL locale */ public boolean isRTL(Context context) { if (isRTLForced(context)) { return true; } - return isRTLAllowed(context) && - isDevicePreferredLanguageRTL(); + return isRTLAllowed(context) && isDevicePreferredLanguageRTL(); } /** - * Should be used very early during app start up - * Before the bridge is initialized + * Should be used very early during app start up Before the bridge is initialized + * * @return whether the app allows RTL layout, default is true */ private boolean isRTLAllowed(Context context) { @@ -71,10 +65,7 @@ public class I18nUtil { setPref(context, KEY_FOR_PERFS_MAKE_RTL_FLIP_LEFT_AND_RIGHT_STYLES, flip); } - /** - * Could be used to test RTL layout with English - * Used for development and testing purpose - */ + /** Could be used to test RTL layout with English Used for development and testing purpose */ private boolean isRTLForced(Context context) { return isPrefSet(context, KEY_FOR_PREFS_FORCERTL, false); } @@ -85,20 +76,18 @@ public class I18nUtil { // Check if the current device language is RTL private boolean isDevicePreferredLanguageRTL() { - final int directionality = - TextUtilsCompat.getLayoutDirectionFromLocale(Locale.getDefault()); + final int directionality = TextUtilsCompat.getLayoutDirectionFromLocale(Locale.getDefault()); return directionality == ViewCompat.LAYOUT_DIRECTION_RTL; - } + } private boolean isPrefSet(Context context, String key, boolean defaultValue) { - SharedPreferences prefs = - context.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE); + SharedPreferences prefs = context.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE); return prefs.getBoolean(key, defaultValue); } private void setPref(Context context, String key, boolean value) { SharedPreferences.Editor editor = - context.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE).edit(); + context.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE).edit(); editor.putBoolean(key, value); editor.apply(); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/image/ImageLoaderModule.java b/ReactAndroid/src/main/java/com/facebook/react/modules/image/ImageLoaderModule.java index 4f0f136da80..1818baa271b 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/image/ImageLoaderModule.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/image/ImageLoaderModule.java @@ -1,17 +1,13 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.image; -import javax.annotation.Nullable; - import android.net.Uri; import android.util.SparseArray; - import com.facebook.common.executors.CallerThreadExecutor; import com.facebook.common.references.CloseableReference; import com.facebook.datasource.BaseDataSubscriber; @@ -22,7 +18,6 @@ import com.facebook.imagepipeline.core.ImagePipeline; import com.facebook.imagepipeline.image.CloseableImage; import com.facebook.imagepipeline.request.ImageRequest; import com.facebook.imagepipeline.request.ImageRequestBuilder; -import com.facebook.react.modules.fresco.ReactNetworkImageRequest; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.GuardedAsyncTask; import com.facebook.react.bridge.LifecycleEventListener; @@ -34,11 +29,13 @@ import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.WritableMap; import com.facebook.react.module.annotations.ReactModule; +import com.facebook.react.modules.fresco.ReactNetworkImageRequest; import com.facebook.react.views.imagehelper.ImageSource; +import javax.annotation.Nullable; @ReactModule(name = ImageLoaderModule.NAME) -public class ImageLoaderModule extends ReactContextBaseJavaModule implements - LifecycleEventListener { +public class ImageLoaderModule extends ReactContextBaseJavaModule + implements LifecycleEventListener { private static final String ERROR_INVALID_URI = "E_INVALID_URI"; private static final String ERROR_PREFETCH_FAILURE = "E_PREFETCH_FAILURE"; @@ -68,13 +65,11 @@ public class ImageLoaderModule extends ReactContextBaseJavaModule implements * Fetch the width and height of the given image. * * @param uriString the URI of the remote image to prefetch - * @param promise the promise that is fulfilled when the image is successfully prefetched - * or rejected when there is an error + * @param promise the promise that is fulfilled when the image is successfully prefetched or + * rejected when there is an error */ @ReactMethod - public void getSize( - final String uriString, - final Promise promise) { + public void getSize(final String uriString, final Promise promise) { if (uriString == null || uriString.isEmpty()) { promise.reject(ERROR_INVALID_URI, "Cannot get the size of an image for an empty URI"); return; @@ -84,41 +79,41 @@ public class ImageLoaderModule extends ReactContextBaseJavaModule implements ImageRequest request = ImageRequestBuilder.newBuilderWithSource(source.getUri()).build(); DataSource> dataSource = - Fresco.getImagePipeline().fetchDecodedImage(request, mCallerContext); + Fresco.getImagePipeline().fetchDecodedImage(request, mCallerContext); DataSubscriber> dataSubscriber = - new BaseDataSubscriber>() { - @Override - protected void onNewResultImpl( - DataSource> dataSource) { - if (!dataSource.isFinished()) { - return; - } - CloseableReference ref = dataSource.getResult(); - if (ref != null) { - try { - CloseableImage image = ref.get(); - - WritableMap sizes = Arguments.createMap(); - sizes.putInt("width", image.getWidth()); - sizes.putInt("height", image.getHeight()); - - promise.resolve(sizes); - } catch (Exception e) { - promise.reject(ERROR_GET_SIZE_FAILURE, e); - } finally { - CloseableReference.closeSafely(ref); + new BaseDataSubscriber>() { + @Override + protected void onNewResultImpl( + DataSource> dataSource) { + if (!dataSource.isFinished()) { + return; } - } else { - promise.reject(ERROR_GET_SIZE_FAILURE); - } - } + CloseableReference ref = dataSource.getResult(); + if (ref != null) { + try { + CloseableImage image = ref.get(); - @Override - protected void onFailureImpl(DataSource> dataSource) { - promise.reject(ERROR_GET_SIZE_FAILURE, dataSource.getFailureCause()); - } - }; + WritableMap sizes = Arguments.createMap(); + sizes.putInt("width", image.getWidth()); + sizes.putInt("height", image.getHeight()); + + promise.resolve(sizes); + } catch (Exception e) { + promise.reject(ERROR_GET_SIZE_FAILURE, e); + } finally { + CloseableReference.closeSafely(ref); + } + } else { + promise.reject(ERROR_GET_SIZE_FAILURE); + } + } + + @Override + protected void onFailureImpl(DataSource> dataSource) { + promise.reject(ERROR_GET_SIZE_FAILURE, dataSource.getFailureCause()); + } + }; dataSource.subscribe(dataSubscriber, CallerThreadExecutor.getInstance()); } @@ -127,59 +122,59 @@ public class ImageLoaderModule extends ReactContextBaseJavaModule implements * * @param uriString the URI of the remote image to prefetch * @param headers headers send with the request - * @param promise the promise that is fulfilled when the image is successfully prefetched - * or rejected when there is an error + * @param promise the promise that is fulfilled when the image is successfully prefetched or + * rejected when there is an error */ @ReactMethod public void getSizeWithHeaders( - final String uriString, - final ReadableMap headers, - final Promise promise) { + final String uriString, final ReadableMap headers, final Promise promise) { if (uriString == null || uriString.isEmpty()) { promise.reject(ERROR_INVALID_URI, "Cannot get the size of an image for an empty URI"); return; } ImageSource source = new ImageSource(getReactApplicationContext(), uriString); - ImageRequestBuilder imageRequestBuilder = ImageRequestBuilder.newBuilderWithSource(source.getUri()); - ImageRequest request = ReactNetworkImageRequest.fromBuilderWithHeaders(imageRequestBuilder, headers); + ImageRequestBuilder imageRequestBuilder = + ImageRequestBuilder.newBuilderWithSource(source.getUri()); + ImageRequest request = + ReactNetworkImageRequest.fromBuilderWithHeaders(imageRequestBuilder, headers); DataSource> dataSource = - Fresco.getImagePipeline().fetchDecodedImage(request, mCallerContext); + Fresco.getImagePipeline().fetchDecodedImage(request, mCallerContext); DataSubscriber> dataSubscriber = - new BaseDataSubscriber>() { - @Override - protected void onNewResultImpl( - DataSource> dataSource) { - if (!dataSource.isFinished()) { - return; - } - CloseableReference ref = dataSource.getResult(); - if (ref != null) { - try { - CloseableImage image = ref.get(); - - WritableMap sizes = Arguments.createMap(); - sizes.putInt("width", image.getWidth()); - sizes.putInt("height", image.getHeight()); - - promise.resolve(sizes); - } catch (Exception e) { - promise.reject(ERROR_GET_SIZE_FAILURE, e); - } finally { - CloseableReference.closeSafely(ref); + new BaseDataSubscriber>() { + @Override + protected void onNewResultImpl( + DataSource> dataSource) { + if (!dataSource.isFinished()) { + return; } - } else { - promise.reject(ERROR_GET_SIZE_FAILURE); - } - } + CloseableReference ref = dataSource.getResult(); + if (ref != null) { + try { + CloseableImage image = ref.get(); - @Override - protected void onFailureImpl(DataSource> dataSource) { - promise.reject(ERROR_GET_SIZE_FAILURE, dataSource.getFailureCause()); - } - }; + WritableMap sizes = Arguments.createMap(); + sizes.putInt("width", image.getWidth()); + sizes.putInt("height", image.getHeight()); + + promise.resolve(sizes); + } catch (Exception e) { + promise.reject(ERROR_GET_SIZE_FAILURE, e); + } finally { + CloseableReference.closeSafely(ref); + } + } else { + promise.reject(ERROR_GET_SIZE_FAILURE); + } + } + + @Override + protected void onFailureImpl(DataSource> dataSource) { + promise.reject(ERROR_GET_SIZE_FAILURE, dataSource.getFailureCause()); + } + }; dataSource.subscribe(dataSubscriber, CallerThreadExecutor.getInstance()); } @@ -188,15 +183,11 @@ public class ImageLoaderModule extends ReactContextBaseJavaModule implements * * @param uriString the URI of the remote image to prefetch * @param requestId the client-supplied request ID used to identify this request - * @param promise the promise that is fulfilled when the image is successfully prefetched - * or rejected when there is an error + * @param promise the promise that is fulfilled when the image is successfully prefetched or + * rejected when there is an error */ @ReactMethod - public void prefetchImage( - final String uriString, - final int requestId, - final Promise promise) - { + public void prefetchImage(final String uriString, final int requestId, final Promise promise) { if (uriString == null || uriString.isEmpty()) { promise.reject(ERROR_INVALID_URI, "Cannot prefetch an image for an empty URI"); return; @@ -206,31 +197,32 @@ public class ImageLoaderModule extends ReactContextBaseJavaModule implements ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri).build(); DataSource prefetchSource = - Fresco.getImagePipeline().prefetchToDiskCache(request, mCallerContext); - DataSubscriber prefetchSubscriber = new BaseDataSubscriber() { - @Override - protected void onNewResultImpl(DataSource dataSource) { - if (!dataSource.isFinished()) { - return; - } - try { - removeRequest(requestId); - promise.resolve(true); - } finally { - dataSource.close(); - } - } + Fresco.getImagePipeline().prefetchToDiskCache(request, mCallerContext); + DataSubscriber prefetchSubscriber = + new BaseDataSubscriber() { + @Override + protected void onNewResultImpl(DataSource dataSource) { + if (!dataSource.isFinished()) { + return; + } + try { + removeRequest(requestId); + promise.resolve(true); + } finally { + dataSource.close(); + } + } - @Override - protected void onFailureImpl(DataSource dataSource) { - try { - removeRequest(requestId); - promise.reject(ERROR_PREFETCH_FAILURE, dataSource.getFailureCause()); - } finally { - dataSource.close(); - } - } - }; + @Override + protected void onFailureImpl(DataSource dataSource) { + try { + removeRequest(requestId); + promise.reject(ERROR_PREFETCH_FAILURE, dataSource.getFailureCause()); + } finally { + dataSource.close(); + } + } + }; registerRequest(requestId, prefetchSource); prefetchSource.subscribe(prefetchSubscriber, CallerThreadExecutor.getInstance()); } @@ -280,12 +272,10 @@ public class ImageLoaderModule extends ReactContextBaseJavaModule implements } @Override - public void onHostResume() { - } + public void onHostResume() {} @Override - public void onHostPause() { - } + public void onHostPause() {} @Override public void onHostDestroy() { diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/intent/IntentModule.java b/ReactAndroid/src/main/java/com/facebook/react/modules/intent/IntentModule.java index 9cf2a7e9473..fc5dc82ea11 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/intent/IntentModule.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/intent/IntentModule.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.intent; import android.app.Activity; @@ -14,7 +13,6 @@ import android.content.pm.PackageManager; import android.net.Uri; import android.nfc.NfcAdapter; import android.provider.Settings; - import com.facebook.react.bridge.JSApplicationIllegalArgumentException; import com.facebook.react.bridge.Promise; import com.facebook.react.bridge.ReactApplicationContext; @@ -24,12 +22,9 @@ import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.ReadableType; import com.facebook.react.module.annotations.ReactModule; - import javax.annotation.Nullable; -/** - * Intent module. Launch other activities or open URLs. - */ +/** Intent module. Launch other activities or open URLs. */ @ReactModule(name = IntentModule.NAME) public class IntentModule extends ReactContextBaseJavaModule { @@ -60,23 +55,26 @@ public class IntentModule extends ReactContextBaseJavaModule { String action = intent.getAction(); Uri uri = intent.getData(); - if (uri != null && (Intent.ACTION_VIEW.equals(action) || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action))) { + if (uri != null + && (Intent.ACTION_VIEW.equals(action) + || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action))) { initialURL = uri.toString(); } } promise.resolve(initialURL); } catch (Exception e) { - promise.reject(new JSApplicationIllegalArgumentException( - "Could not get the initial URL : " + e.getMessage())); + promise.reject( + new JSApplicationIllegalArgumentException( + "Could not get the initial URL : " + e.getMessage())); } } /** * Starts a corresponding external activity for the given URL. * - * For example, if the URL is "https://www.facebook.com", the system browser will be opened, - * or the "choose application" dialog will be shown. + *

For example, if the URL is "https://www.facebook.com", the system browser will be opened, or + * the "choose application" dialog will be shown. * * @param url the URL to open */ @@ -92,8 +90,8 @@ public class IntentModule extends ReactContextBaseJavaModule { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url).normalizeScheme()); String selfPackageName = getReactApplicationContext().getPackageName(); - ComponentName componentName = intent.resolveActivity( - getReactApplicationContext().getPackageManager()); + ComponentName componentName = + intent.resolveActivity(getReactApplicationContext().getPackageManager()); String otherPackageName = (componentName != null ? componentName.getPackageName() : ""); // If there is no currentActivity or we are launching to a different package we need to set @@ -110,8 +108,9 @@ public class IntentModule extends ReactContextBaseJavaModule { promise.resolve(true); } catch (Exception e) { - promise.reject(new JSApplicationIllegalArgumentException( - "Could not open URL '" + url + "': " + e.getMessage())); + promise.reject( + new JSApplicationIllegalArgumentException( + "Could not open URL '" + url + "': " + e.getMessage())); } } @@ -137,8 +136,9 @@ public class IntentModule extends ReactContextBaseJavaModule { intent.resolveActivity(getReactApplicationContext().getPackageManager()) != null; promise.resolve(canOpen); } catch (Exception e) { - promise.reject(new JSApplicationIllegalArgumentException( - "Could not check if URL '" + url + "' can be opened: " + e.getMessage())); + promise.reject( + new JSApplicationIllegalArgumentException( + "Could not check if URL '" + url + "' can be opened: " + e.getMessage())); } } @@ -164,20 +164,19 @@ public class IntentModule extends ReactContextBaseJavaModule { promise.resolve(true); } catch (Exception e) { - promise.reject(new JSApplicationIllegalArgumentException( - "Could not open the Settings: " + e.getMessage())); + promise.reject( + new JSApplicationIllegalArgumentException( + "Could not open the Settings: " + e.getMessage())); } } /** * Allows to send intents on Android * - * For example, you can open the Notification Category screen for a specific application - * passing action = 'android.settings.CHANNEL_NOTIFICATION_SETTINGS' - * and extras = [ - * { 'android.provider.extra.APP_PACKAGE': 'your.package.name.here' }, - * { 'android.provider.extra.CHANNEL_ID': 'your.channel.id.here } - * ] + *

For example, you can open the Notification Category screen for a specific application + * passing action = 'android.settings.CHANNEL_NOTIFICATION_SETTINGS' and extras = [ { + * 'android.provider.extra.APP_PACKAGE': 'your.package.name.here' }, { + * 'android.provider.extra.CHANNEL_ID': 'your.channel.id.here } ] * * @param action The general action to be performed * @param extras An array of extras [{ String, String | Number | Boolean }] @@ -193,7 +192,9 @@ public class IntentModule extends ReactContextBaseJavaModule { PackageManager packageManager = getReactApplicationContext().getPackageManager(); if (intent.resolveActivity(packageManager) == null) { - promise.reject(new JSApplicationIllegalArgumentException("Could not launch Intent with action " + action + ".")); + promise.reject( + new JSApplicationIllegalArgumentException( + "Could not launch Intent with action " + action + ".")); return; } @@ -204,27 +205,32 @@ public class IntentModule extends ReactContextBaseJavaModule { ReadableType type = map.getType(name); switch (type) { - case String: { - intent.putExtra(name, map.getString(name)); - break; - } - case Number: { - // We cannot know from JS if is an Integer or Double - // See: https://github.com/facebook/react-native/issues/4141 - // We might need to find a workaround if this is really an issue - Double number = map.getDouble(name); - intent.putExtra(name, number); - break; - } - case Boolean: { - intent.putExtra(name, map.getBoolean(name)); - break; - } - default: { - promise.reject(new JSApplicationIllegalArgumentException( - "Extra type for " + name + " not supported.")); - return; - } + case String: + { + intent.putExtra(name, map.getString(name)); + break; + } + case Number: + { + // We cannot know from JS if is an Integer or Double + // See: https://github.com/facebook/react-native/issues/4141 + // We might need to find a workaround if this is really an issue + Double number = map.getDouble(name); + intent.putExtra(name, number); + break; + } + case Boolean: + { + intent.putExtra(name, map.getBoolean(name)); + break; + } + default: + { + promise.reject( + new JSApplicationIllegalArgumentException( + "Extra type for " + name + " not supported.")); + return; + } } } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/network/CookieJarContainer.java b/ReactAndroid/src/main/java/com/facebook/react/modules/network/CookieJarContainer.java index 6e58b76e91c..0962edd2e9f 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/network/CookieJarContainer.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/network/CookieJarContainer.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.network; import okhttp3.CookieJar; @@ -14,5 +13,4 @@ public interface CookieJarContainer extends CookieJar { void setCookieJar(CookieJar cookieJar); void removeCookieJar(); - } diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/network/CountingOutputStream.java b/ReactAndroid/src/main/java/com/facebook/react/modules/network/CountingOutputStream.java index 623a1351c42..7d8afb33772 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/network/CountingOutputStream.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/network/CountingOutputStream.java @@ -31,8 +31,7 @@ public class CountingOutputStream extends FilterOutputStream { private long mCount; /** - * Constructs a new {@code FilterOutputStream} with {@code out} as its - * target stream. + * Constructs a new {@code FilterOutputStream} with {@code out} as its target stream. * * @param out the target stream that this stream writes to. */ @@ -41,9 +40,7 @@ public class CountingOutputStream extends FilterOutputStream { mCount = 0; } - /** - * Returns the number of bytes written. - */ + /** Returns the number of bytes written. */ public long getCount() { return mCount; } diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/network/ForwardingCookieHandler.java b/ReactAndroid/src/main/java/com/facebook/react/modules/network/ForwardingCookieHandler.java index 23304fe2f2d..dc7d4a457c2 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/network/ForwardingCookieHandler.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/network/ForwardingCookieHandler.java @@ -5,15 +5,6 @@ package com.facebook.react.modules.network; -import javax.annotation.Nullable; - -import java.io.IOException; -import java.net.CookieHandler; -import java.net.URI; -import java.util.Collections; -import java.util.List; -import java.util.Map; - import android.annotation.TargetApi; import android.content.Context; import android.os.Build; @@ -24,16 +15,22 @@ import android.text.TextUtils; import android.webkit.CookieManager; import android.webkit.CookieSyncManager; import android.webkit.ValueCallback; - import com.facebook.react.bridge.Callback; import com.facebook.react.bridge.GuardedAsyncTask; import com.facebook.react.bridge.GuardedResultAsyncTask; import com.facebook.react.bridge.ReactContext; +import java.io.IOException; +import java.net.CookieHandler; +import java.net.URI; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import javax.annotation.Nullable; /** * Cookie handler that forwards all cookies to the WebView CookieManager. * - * This class relies on CookieManager to persist cookies to disk so cookies may be lost if the + *

This class relies on CookieManager to persist cookies to disk so cookies may be lost if the * application is terminated before it syncs. */ public class ForwardingCookieHandler extends CookieHandler { @@ -171,14 +168,14 @@ public class ForwardingCookieHandler extends CookieHandler { } /** - * Instantiating CookieManager in KitKat+ will load the Chromium task taking a 100ish ms so we - * do it lazily to make sure it's done on a background thread as needed. + * Instantiating CookieManager in KitKat+ will load the Chromium task taking a 100ish ms so we do + * it lazily to make sure it's done on a background thread as needed. */ private @Nullable CookieManager getCookieManager() { if (mCookieManager == null) { possiblyWorkaroundSyncManager(mContext); try { - mCookieManager = CookieManager.getInstance(); + mCookieManager = CookieManager.getInstance(); } catch (IllegalArgumentException ex) { // https://bugs.chromium.org/p/chromium/issues/detail?id=559720 return null; @@ -225,17 +222,20 @@ public class ForwardingCookieHandler extends CookieHandler { private final Handler mHandler; public CookieSaver() { - mHandler = new Handler(Looper.getMainLooper(), new Handler.Callback() { - @Override - public boolean handleMessage(Message msg) { - if (msg.what == MSG_PERSIST_COOKIES) { - persistCookies(); - return true; - } else { - return false; - } - } - }); + mHandler = + new Handler( + Looper.getMainLooper(), + new Handler.Callback() { + @Override + public boolean handleMessage(Message msg) { + if (msg.what == MSG_PERSIST_COOKIES) { + persistCookies(); + return true; + } else { + return false; + } + } + }); } public void onCookiesModified() { diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/network/HeaderUtil.java b/ReactAndroid/src/main/java/com/facebook/react/modules/network/HeaderUtil.java index 2f2d72bb90c..f53bbc82b97 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/network/HeaderUtil.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/network/HeaderUtil.java @@ -1,47 +1,44 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.network; /** - * - * The class purpose is to weaken too strict OkHttp restriction on http headers. - * See: https://github.com/square/okhttp/issues/2016 - * Auth headers might have an Authentication information. It is better to get 401 from the - * server in this case, rather than non descriptive error as 401 could be handled to invalidate - * the wrong token in the client code. + * The class purpose is to weaken too strict OkHttp restriction on http headers. See: + * https://github.com/square/okhttp/issues/2016 Auth headers might have an Authentication + * information. It is better to get 401 from the server in this case, rather than non descriptive + * error as 401 could be handled to invalidate the wrong token in the client code. */ public class HeaderUtil { - public static String stripHeaderName(String name) { - StringBuilder builder = new StringBuilder(name.length()); - boolean modified = false; - for (int i = 0, length = name.length(); i < length; i++) { - char c = name.charAt(i); - if (c > '\u0020' && c < '\u007f') { - builder.append(c); - } else { - modified = true; - } - } - return modified ? builder.toString() : name; + public static String stripHeaderName(String name) { + StringBuilder builder = new StringBuilder(name.length()); + boolean modified = false; + for (int i = 0, length = name.length(); i < length; i++) { + char c = name.charAt(i); + if (c > '\u0020' && c < '\u007f') { + builder.append(c); + } else { + modified = true; + } } + return modified ? builder.toString() : name; + } - public static String stripHeaderValue(String value) { - StringBuilder builder = new StringBuilder(value.length()); - boolean modified = false; - for (int i = 0, length = value.length(); i < length; i++) { - char c = value.charAt(i); - if ((c > '\u001f' && c < '\u007f') || c == '\t' ) { - builder.append(c); - } else { - modified = true; - } - } - return modified ? builder.toString() : value; + public static String stripHeaderValue(String value) { + StringBuilder builder = new StringBuilder(value.length()); + boolean modified = false; + for (int i = 0, length = value.length(); i < length; i++) { + char c = value.charAt(i); + if ((c > '\u001f' && c < '\u007f') || c == '\t') { + builder.append(c); + } else { + modified = true; + } } + return modified ? builder.toString() : value; + } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/network/NetworkInterceptorCreator.java b/ReactAndroid/src/main/java/com/facebook/react/modules/network/NetworkInterceptorCreator.java index a4d51166447..eebd3f63ff4 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/network/NetworkInterceptorCreator.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/network/NetworkInterceptorCreator.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.network; import okhttp3.Interceptor; diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/network/NetworkingModule.java b/ReactAndroid/src/main/java/com/facebook/react/modules/network/NetworkingModule.java index 9c90084b929..22b1e5daf52 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/network/NetworkingModule.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/network/NetworkingModule.java @@ -1,14 +1,13 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ package com.facebook.react.modules.network; import android.net.Uri; import android.util.Base64; - import com.facebook.common.logging.FLog; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.GuardedAsyncTask; @@ -22,7 +21,6 @@ import com.facebook.react.common.StandardCharsets; import com.facebook.react.common.network.OkHttpCallUtil; import com.facebook.react.module.annotations.ReactModule; import com.facebook.react.modules.core.DeviceEventManagerModule.RCTDeviceEventEmitter; - import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; @@ -31,9 +29,7 @@ import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; - import javax.annotation.Nullable; - import okhttp3.Call; import okhttp3.Callback; import okhttp3.CookieJar; @@ -51,55 +47,37 @@ import okio.ByteString; import okio.GzipSource; import okio.Okio; -/** - * Implements the XMLHttpRequest JavaScript interface. - */ +/** Implements the XMLHttpRequest JavaScript interface. */ @ReactModule(name = NetworkingModule.NAME) public final class NetworkingModule extends ReactContextBaseJavaModule { /** - * Allows to implement a custom fetching process for specific URIs. It is the handler's job - * to fetch the URI and return the JS body payload. + * Allows to implement a custom fetching process for specific URIs. It is the handler's job to + * fetch the URI and return the JS body payload. */ public interface UriHandler { - /** - * Returns if the handler should be used for an URI. - */ + /** Returns if the handler should be used for an URI. */ boolean supports(Uri uri, String responseType); - /** - * Fetch the URI and return the JS body payload. - */ + /** Fetch the URI and return the JS body payload. */ WritableMap fetch(Uri uri) throws IOException; } - /** - * Allows adding custom handling to build the {@link RequestBody} from the JS body payload. - */ + /** Allows adding custom handling to build the {@link RequestBody} from the JS body payload. */ public interface RequestBodyHandler { - /** - * Returns if the handler should be used for a JS body payload. - */ + /** Returns if the handler should be used for a JS body payload. */ boolean supports(ReadableMap map); - /** - * Returns the {@link RequestBody} for the JS body payload. - */ + /** Returns the {@link RequestBody} for the JS body payload. */ RequestBody toRequestBody(ReadableMap map, String contentType); } - /** - * Allows adding custom handling to build the JS body payload from the {@link ResponseBody}. - */ + /** Allows adding custom handling to build the JS body payload from the {@link ResponseBody}. */ public interface ResponseHandler { - /** - * Returns if the handler should be used for a response type. - */ + /** Returns if the handler should be used for a response type. */ boolean supports(String responseType); - /** - * Returns the JS body payload for the {@link ResponseBody}. - */ + /** Returns the JS body payload for the {@link ResponseBody}. */ WritableMap toResponseData(ResponseBody body) throws IOException; } @@ -153,19 +131,15 @@ public final class NetworkingModule extends ReactContextBaseJavaModule { /** * @param context the ReactContext of the application * @param defaultUserAgent the User-Agent header that will be set for all requests where the - * caller does not provide one explicitly + * caller does not provide one explicitly * @param client the {@link OkHttpClient} to be used for networking */ /* package */ NetworkingModule( - ReactApplicationContext context, - @Nullable String defaultUserAgent, - OkHttpClient client) { + ReactApplicationContext context, @Nullable String defaultUserAgent, OkHttpClient client) { this(context, defaultUserAgent, client, null); } - /** - * @param context the ReactContext of the application - */ + /** @param context the ReactContext of the application */ public NetworkingModule(final ReactApplicationContext context) { this(context, null, OkHttpClientProvider.createClient(context), null); } @@ -173,18 +147,17 @@ public final class NetworkingModule extends ReactContextBaseJavaModule { /** * @param context the ReactContext of the application * @param networkInterceptorCreators list of {@link NetworkInterceptorCreator}'s whose create() - * methods would be called to attach the interceptors to the client. + * methods would be called to attach the interceptors to the client. */ public NetworkingModule( - ReactApplicationContext context, - List networkInterceptorCreators) { + ReactApplicationContext context, List networkInterceptorCreators) { this(context, null, OkHttpClientProvider.createClient(context), networkInterceptorCreators); } /** * @param context the ReactContext of the application * @param defaultUserAgent the User-Agent header that will be set for all requests where the - * caller does not provide one explicitly + * caller does not provide one explicitly */ public NetworkingModule(ReactApplicationContext context, String defaultUserAgent) { this(context, defaultUserAgent, OkHttpClientProvider.createClient(context), null); @@ -263,17 +236,23 @@ public final class NetworkingModule extends ReactContextBaseJavaModule { int timeout, boolean withCredentials) { try { - sendRequestInternal(method, url, requestId, headers, data, responseType, - useIncrementalUpdates, timeout, withCredentials); + sendRequestInternal( + method, + url, + requestId, + headers, + data, + responseType, + useIncrementalUpdates, + timeout, + withCredentials); } catch (Throwable th) { FLog.e(TAG, "Failed to send url request: " + url, th); ResponseUtil.onRequestError(getEventEmitter(), requestId, th.getMessage(), th); } } - /** - * @param timeout value of 0 results in no timeout - */ + /** @param timeout value of 0 results in no timeout */ public void sendRequestInternal( String method, String url, @@ -326,37 +305,38 @@ public final class NetworkingModule extends ReactContextBaseJavaModule { // If JS is listening for progress updates, install a ProgressResponseBody that intercepts the // response and counts bytes received. if (useIncrementalUpdates) { - clientBuilder.addNetworkInterceptor(new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - Response originalResponse = chain.proceed(chain.request()); - ProgressResponseBody responseBody = new ProgressResponseBody( - originalResponse.body(), - new ProgressListener() { - long last = System.nanoTime(); + clientBuilder.addNetworkInterceptor( + new Interceptor() { + @Override + public Response intercept(Interceptor.Chain chain) throws IOException { + Response originalResponse = chain.proceed(chain.request()); + ProgressResponseBody responseBody = + new ProgressResponseBody( + originalResponse.body(), + new ProgressListener() { + long last = System.nanoTime(); - @Override - public void onProgress(long bytesWritten, long contentLength, boolean done) { - long now = System.nanoTime(); - if (!done && !shouldDispatch(now, last)) { - return; - } - if (responseType.equals("text")) { - // For 'text' responses we continuously send response data with progress info to - // JS below, so no need to do anything here. - return; - } - ResponseUtil.onDataReceivedProgress( - eventEmitter, - requestId, - bytesWritten, - contentLength); - last = now; - } - }); - return originalResponse.newBuilder().body(responseBody).build(); - } - }); + @Override + public void onProgress( + long bytesWritten, long contentLength, boolean done) { + long now = System.nanoTime(); + if (!done && !shouldDispatch(now, last)) { + return; + } + if (responseType.equals("text")) { + // For 'text' responses we continuously send response data with progress + // info to + // JS below, so no need to do anything here. + return; + } + ResponseUtil.onDataReceivedProgress( + eventEmitter, requestId, bytesWritten, contentLength); + last = now; + } + }); + return originalResponse.newBuilder().body(responseBody).build(); + } + }); } // If the current timeout does not equal the passed in timeout, we need to clone the existing @@ -396,10 +376,7 @@ public final class NetworkingModule extends ReactContextBaseJavaModule { } else if (data.hasKey(REQUEST_BODY_KEY_STRING)) { if (contentType == null) { ResponseUtil.onRequestError( - eventEmitter, - requestId, - "Payload is set but no content-type header specified", - null); + eventEmitter, requestId, "Payload is set but no content-type header specified", null); return; } String body = data.getString(REQUEST_BODY_KEY_STRING); @@ -414,18 +391,16 @@ public final class NetworkingModule extends ReactContextBaseJavaModule { // Use getBytes() to convert the body into a byte[], preventing okhttp from // appending the character set to the Content-Type header when otherwise unspecified // https://github.com/facebook/react-native/issues/8237 - Charset charset = contentMediaType == null - ? StandardCharsets.UTF_8 - : contentMediaType.charset(StandardCharsets.UTF_8); + Charset charset = + contentMediaType == null + ? StandardCharsets.UTF_8 + : contentMediaType.charset(StandardCharsets.UTF_8); requestBody = RequestBody.create(contentMediaType, body.getBytes(charset)); } } else if (data.hasKey(REQUEST_BODY_KEY_BASE64)) { if (contentType == null) { ResponseUtil.onRequestError( - eventEmitter, - requestId, - "Payload is set but no content-type header specified", - null); + eventEmitter, requestId, "Payload is set but no content-type header specified", null); return; } String base64String = data.getString(REQUEST_BODY_KEY_BASE64); @@ -434,10 +409,7 @@ public final class NetworkingModule extends ReactContextBaseJavaModule { } else if (data.hasKey(REQUEST_BODY_KEY_URI)) { if (contentType == null) { ResponseUtil.onRequestError( - eventEmitter, - requestId, - "Payload is set but no content-type header specified", - null); + eventEmitter, requestId, "Payload is set but no content-type header specified", null); return; } String uri = data.getString(REQUEST_BODY_KEY_URI); @@ -445,10 +417,7 @@ public final class NetworkingModule extends ReactContextBaseJavaModule { RequestBodyUtil.getFileInputStream(getReactApplicationContext(), uri); if (fileInputStream == null) { ResponseUtil.onRequestError( - eventEmitter, - requestId, - "Could not retrieve file for uri " + uri, - null); + eventEmitter, requestId, "Could not retrieve file for uri " + uri, null); return; } requestBody = RequestBodyUtil.create(MediaType.parse(contentType), fileInputStream); @@ -469,131 +438,140 @@ public final class NetworkingModule extends ReactContextBaseJavaModule { } requestBuilder.method( - method, - wrapRequestBodyWithProgressEmitter(requestBody, eventEmitter, requestId)); + method, wrapRequestBodyWithProgressEmitter(requestBody, eventEmitter, requestId)); addRequest(requestId); - client.newCall(requestBuilder.build()).enqueue( - new Callback() { - @Override - public void onFailure(Call call, IOException e) { - if (mShuttingDown) { - return; - } - removeRequest(requestId); - String errorMessage = e.getMessage() != null - ? e.getMessage() - : "Error while executing request: " + e.getClass().getSimpleName(); - ResponseUtil.onRequestError(eventEmitter, requestId, errorMessage, e); - } - - @Override - public void onResponse(Call call, Response response) throws IOException { - if (mShuttingDown) { - return; - } - removeRequest(requestId); - // Before we touch the body send headers to JS - ResponseUtil.onResponseReceived( - eventEmitter, - requestId, - response.code(), - translateHeaders(response.headers()), - response.request().url().toString()); - - try { - // OkHttp implements something called transparent gzip, which mean that it will - // automatically add the Accept-Encoding gzip header and handle decoding internally. - // The issue is that it won't handle decoding if the user provides a Accept-Encoding - // header. This is also undesirable considering that iOS does handle the decoding even - // when the header is provided. To make sure this works in all cases, handle gzip body - // here also. This works fine since OKHttp will remove the Content-Encoding header if - // it used transparent gzip. - // See https://github.com/square/okhttp/blob/5b37cda9e00626f43acf354df145fd452c3031f1/okhttp/src/main/java/okhttp3/internal/http/BridgeInterceptor.java#L76-L111 - ResponseBody responseBody = response.body(); - if ("gzip".equalsIgnoreCase(response.header("Content-Encoding")) && - responseBody != null) { - GzipSource gzipSource = new GzipSource(responseBody.source()); - String contentType = response.header("Content-Type"); - responseBody = ResponseBody.create( - contentType != null ? MediaType.parse(contentType) : null, - -1L, - Okio.buffer(gzipSource)); - } - - // Check if a handler is registered - for (ResponseHandler handler : mResponseHandlers) { - if (handler.supports(responseType)) { - WritableMap res = handler.toResponseData(responseBody); - ResponseUtil.onDataReceived(eventEmitter, requestId, res); - ResponseUtil.onRequestSuccess(eventEmitter, requestId); + client + .newCall(requestBuilder.build()) + .enqueue( + new Callback() { + @Override + public void onFailure(Call call, IOException e) { + if (mShuttingDown) { return; } + removeRequest(requestId); + String errorMessage = + e.getMessage() != null + ? e.getMessage() + : "Error while executing request: " + e.getClass().getSimpleName(); + ResponseUtil.onRequestError(eventEmitter, requestId, errorMessage, e); } - // If JS wants progress updates during the download, and it requested a text response, - // periodically send response data updates to JS. - if (useIncrementalUpdates && responseType.equals("text")) { - readWithProgress(eventEmitter, requestId, responseBody); - ResponseUtil.onRequestSuccess(eventEmitter, requestId); - return; - } - - // Otherwise send the data in one big chunk, in the format that JS requested. - String responseString = ""; - if (responseType.equals("text")) { - try { - responseString = responseBody.string(); - } catch (IOException e) { - if (response.request().method().equalsIgnoreCase("HEAD")) { - // The request is an `HEAD` and the body is empty, - // the OkHttp will produce an exception. - // Ignore the exception to not invalidate the request in the - // Javascript layer. - // Introduced to fix issue #7463. - } else { - ResponseUtil.onRequestError(eventEmitter, requestId, e.getMessage(), e); - } + @Override + public void onResponse(Call call, Response response) throws IOException { + if (mShuttingDown) { + return; + } + removeRequest(requestId); + // Before we touch the body send headers to JS + ResponseUtil.onResponseReceived( + eventEmitter, + requestId, + response.code(), + translateHeaders(response.headers()), + response.request().url().toString()); + + try { + // OkHttp implements something called transparent gzip, which mean that it will + // automatically add the Accept-Encoding gzip header and handle decoding + // internally. + // The issue is that it won't handle decoding if the user provides a + // Accept-Encoding + // header. This is also undesirable considering that iOS does handle the decoding + // even + // when the header is provided. To make sure this works in all cases, handle gzip + // body + // here also. This works fine since OKHttp will remove the Content-Encoding header + // if + // it used transparent gzip. + // See + // https://github.com/square/okhttp/blob/5b37cda9e00626f43acf354df145fd452c3031f1/okhttp/src/main/java/okhttp3/internal/http/BridgeInterceptor.java#L76-L111 + ResponseBody responseBody = response.body(); + if ("gzip".equalsIgnoreCase(response.header("Content-Encoding")) + && responseBody != null) { + GzipSource gzipSource = new GzipSource(responseBody.source()); + String contentType = response.header("Content-Type"); + responseBody = + ResponseBody.create( + contentType != null ? MediaType.parse(contentType) : null, + -1L, + Okio.buffer(gzipSource)); + } + + // Check if a handler is registered + for (ResponseHandler handler : mResponseHandlers) { + if (handler.supports(responseType)) { + WritableMap res = handler.toResponseData(responseBody); + ResponseUtil.onDataReceived(eventEmitter, requestId, res); + ResponseUtil.onRequestSuccess(eventEmitter, requestId); + return; + } + } + + // If JS wants progress updates during the download, and it requested a text + // response, + // periodically send response data updates to JS. + if (useIncrementalUpdates && responseType.equals("text")) { + readWithProgress(eventEmitter, requestId, responseBody); + ResponseUtil.onRequestSuccess(eventEmitter, requestId); + return; + } + + // Otherwise send the data in one big chunk, in the format that JS requested. + String responseString = ""; + if (responseType.equals("text")) { + try { + responseString = responseBody.string(); + } catch (IOException e) { + if (response.request().method().equalsIgnoreCase("HEAD")) { + // The request is an `HEAD` and the body is empty, + // the OkHttp will produce an exception. + // Ignore the exception to not invalidate the request in the + // Javascript layer. + // Introduced to fix issue #7463. + } else { + ResponseUtil.onRequestError(eventEmitter, requestId, e.getMessage(), e); + } + } + } else if (responseType.equals("base64")) { + responseString = Base64.encodeToString(responseBody.bytes(), Base64.NO_WRAP); + } + ResponseUtil.onDataReceived(eventEmitter, requestId, responseString); + ResponseUtil.onRequestSuccess(eventEmitter, requestId); + } catch (IOException e) { + ResponseUtil.onRequestError(eventEmitter, requestId, e.getMessage(), e); } - } else if (responseType.equals("base64")) { - responseString = Base64.encodeToString(responseBody.bytes(), Base64.NO_WRAP); } - ResponseUtil.onDataReceived(eventEmitter, requestId, responseString); - ResponseUtil.onRequestSuccess(eventEmitter, requestId); - } catch (IOException e) { - ResponseUtil.onRequestError(eventEmitter, requestId, e.getMessage(), e); - } - } - }); + }); } private RequestBody wrapRequestBodyWithProgressEmitter( final RequestBody requestBody, final RCTDeviceEventEmitter eventEmitter, final int requestId) { - if(requestBody == null) { + if (requestBody == null) { return null; } return RequestBodyUtil.createProgressRequest( - requestBody, - new ProgressListener() { - long last = System.nanoTime(); + requestBody, + new ProgressListener() { + long last = System.nanoTime(); - @Override - public void onProgress(long bytesWritten, long contentLength, boolean done) { - long now = System.nanoTime(); - if (done || shouldDispatch(now, last)) { - ResponseUtil.onDataSend(eventEmitter, requestId, bytesWritten, contentLength); - last = now; + @Override + public void onProgress(long bytesWritten, long contentLength, boolean done) { + long now = System.nanoTime(); + if (done || shouldDispatch(now, last)) { + ResponseUtil.onDataSend(eventEmitter, requestId, bytesWritten, contentLength); + last = now; + } } - } - }); + }); } private void readWithProgress( - RCTDeviceEventEmitter eventEmitter, - int requestId, - ResponseBody responseBody) throws IOException { + RCTDeviceEventEmitter eventEmitter, int requestId, ResponseBody responseBody) + throws IOException { long totalBytesRead = -1; long contentLength = -1; try { @@ -604,8 +582,10 @@ public final class NetworkingModule extends ReactContextBaseJavaModule { // Ignore } - Charset charset = responseBody.contentType() == null ? StandardCharsets.UTF_8 : - responseBody.contentType().charset(StandardCharsets.UTF_8); + Charset charset = + responseBody.contentType() == null + ? StandardCharsets.UTF_8 + : responseBody.contentType().charset(StandardCharsets.UTF_8); ProgressiveStringDecoder streamDecoder = new ProgressiveStringDecoder(charset); InputStream inputStream = responseBody.byteStream(); @@ -614,11 +594,11 @@ public final class NetworkingModule extends ReactContextBaseJavaModule { int read; while ((read = inputStream.read(buffer)) != -1) { ResponseUtil.onIncrementalDataReceived( - eventEmitter, - requestId, - streamDecoder.decodeNext(buffer, read), - totalBytesRead, - contentLength); + eventEmitter, + requestId, + streamDecoder.decodeNext(buffer, read), + totalBytesRead, + contentLength); } } finally { inputStream.close(); @@ -651,8 +631,7 @@ public final class NetworkingModule extends ReactContextBaseJavaModule { // multiple values for the same header if (responseHeaders.hasKey(headerName)) { responseHeaders.putString( - headerName, - responseHeaders.getString(headerName) + ", " + headers.value(i)); + headerName, responseHeaders.getString(headerName) + ", " + headers.value(i)); } else { responseHeaders.putString(headerName, headers.value(i)); } @@ -683,9 +662,7 @@ public final class NetworkingModule extends ReactContextBaseJavaModule { } private @Nullable MultipartBody.Builder constructMultipartBody( - ReadableArray body, - String contentType, - int requestId) { + ReadableArray body, String contentType, int requestId) { RCTDeviceEventEmitter eventEmitter = getEventEmitter(); MultipartBody.Builder multipartBuilder = new MultipartBody.Builder(); multipartBuilder.setType(MediaType.parse(contentType)); @@ -698,10 +675,7 @@ public final class NetworkingModule extends ReactContextBaseJavaModule { Headers headers = extractHeaders(headersArray, null); if (headers == null) { ResponseUtil.onRequestError( - eventEmitter, - requestId, - "Missing or invalid header format for FormData part.", - null); + eventEmitter, requestId, "Missing or invalid header format for FormData part.", null); return null; } MediaType partContentType = null; @@ -719,10 +693,7 @@ public final class NetworkingModule extends ReactContextBaseJavaModule { } else if (bodyPart.hasKey(REQUEST_BODY_KEY_URI)) { if (partContentType == null) { ResponseUtil.onRequestError( - eventEmitter, - requestId, - "Binary FormData part needs a content-type header.", - null); + eventEmitter, requestId, "Binary FormData part needs a content-type header.", null); return null; } String fileContentUriStr = bodyPart.getString(REQUEST_BODY_KEY_URI); @@ -730,10 +701,10 @@ public final class NetworkingModule extends ReactContextBaseJavaModule { RequestBodyUtil.getFileInputStream(getReactApplicationContext(), fileContentUriStr); if (fileInputStream == null) { ResponseUtil.onRequestError( - eventEmitter, - requestId, - "Could not retrieve file for uri " + fileContentUriStr, - null); + eventEmitter, + requestId, + "Could not retrieve file for uri " + fileContentUriStr, + null); return null; } multipartBuilder.addPart(headers, RequestBodyUtil.create(partContentType, fileInputStream)); @@ -748,8 +719,7 @@ public final class NetworkingModule extends ReactContextBaseJavaModule { * Extracts the headers from the Array. If the format is invalid, this method will return null. */ private @Nullable Headers extractHeaders( - @Nullable ReadableArray headersArray, - @Nullable ReadableMap requestData) { + @Nullable ReadableArray headersArray, @Nullable ReadableMap requestData) { if (headersArray == null) { return null; } diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/network/OkHttpClientFactory.java b/ReactAndroid/src/main/java/com/facebook/react/modules/network/OkHttpClientFactory.java index 9baf4887799..b233a37a375 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/network/OkHttpClientFactory.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/network/OkHttpClientFactory.java @@ -1,14 +1,13 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.network; import okhttp3.OkHttpClient; public interface OkHttpClientFactory { - OkHttpClient createNewNetworkModuleClient(); + OkHttpClient createNewNetworkModuleClient(); }; diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/network/OkHttpClientProvider.java b/ReactAndroid/src/main/java/com/facebook/react/modules/network/OkHttpClientProvider.java index 34aefeabbb1..eb495c48368 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/network/OkHttpClientProvider.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/network/OkHttpClientProvider.java @@ -1,26 +1,21 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.network; import android.content.Context; import android.os.Build; - import com.facebook.common.logging.FLog; - import java.io.File; import java.security.Provider; import java.security.Security; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; - import javax.annotation.Nullable; - import okhttp3.Cache; import okhttp3.ConnectionSpec; import okhttp3.OkHttpClient; @@ -65,16 +60,16 @@ public class OkHttpClientProvider { public static OkHttpClient.Builder createClientBuilder() { // No timeouts by default - OkHttpClient.Builder client = new OkHttpClient.Builder() - .connectTimeout(0, TimeUnit.MILLISECONDS) - .readTimeout(0, TimeUnit.MILLISECONDS) - .writeTimeout(0, TimeUnit.MILLISECONDS) - .cookieJar(new ReactCookieJarContainer()); + OkHttpClient.Builder client = + new OkHttpClient.Builder() + .connectTimeout(0, TimeUnit.MILLISECONDS) + .readTimeout(0, TimeUnit.MILLISECONDS) + .writeTimeout(0, TimeUnit.MILLISECONDS) + .cookieJar(new ReactCookieJarContainer()); try { Class ConscryptProvider = Class.forName("org.conscrypt.OpenSSLProvider"); - Security.insertProviderAt( - (Provider) ConscryptProvider.newInstance(), 1); + Security.insertProviderAt((Provider) ConscryptProvider.newInstance(), 1); return client; } catch (Exception e) { return enableTls12OnPreLollipop(client); @@ -100,16 +95,17 @@ public class OkHttpClientProvider { } /* - On Android 4.1-4.4 (API level 16 to 19) TLS 1.1 and 1.2 are - available but not enabled by default. The following method - enables it. - */ + On Android 4.1-4.4 (API level 16 to 19) TLS 1.1 and 1.2 are + available but not enabled by default. The following method + enables it. + */ public static OkHttpClient.Builder enableTls12OnPreLollipop(OkHttpClient.Builder client) { if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) { try { client.sslSocketFactory(new TLSSocketFactory()); - ConnectionSpec cs = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS) + ConnectionSpec cs = + new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS) .tlsVersions(TlsVersion.TLS_1_2) .build(); @@ -126,5 +122,4 @@ public class OkHttpClientProvider { return client; } - } diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/network/ProgressListener.java b/ReactAndroid/src/main/java/com/facebook/react/modules/network/ProgressListener.java index cafbfba4f5c..886e39d8e17 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/network/ProgressListener.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/network/ProgressListener.java @@ -1,12 +1,11 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.network; public interface ProgressListener { - void onProgress(long bytesWritten, long contentLength, boolean done); + void onProgress(long bytesWritten, long contentLength, boolean done); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/network/ProgressRequestBody.java b/ReactAndroid/src/main/java/com/facebook/react/modules/network/ProgressRequestBody.java index e86a2c5e63b..b810dc0e573 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/network/ProgressRequestBody.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/network/ProgressRequestBody.java @@ -1,14 +1,12 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.network; import java.io.IOException; - import okhttp3.MediaType; import okhttp3.RequestBody; import okio.BufferedSink; @@ -55,25 +53,26 @@ public class ProgressRequestBody extends RequestBody { } private Sink outputStreamSink(BufferedSink sink) { - return Okio.sink(new CountingOutputStream(sink.outputStream()) { - @Override - public void write(byte[] data, int offset, int byteCount) throws IOException { - super.write(data, offset, byteCount); - sendProgressUpdate(); - } + return Okio.sink( + new CountingOutputStream(sink.outputStream()) { + @Override + public void write(byte[] data, int offset, int byteCount) throws IOException { + super.write(data, offset, byteCount); + sendProgressUpdate(); + } - @Override - public void write(int data) throws IOException { - super.write(data); - sendProgressUpdate(); - } + @Override + public void write(int data) throws IOException { + super.write(data); + sendProgressUpdate(); + } - private void sendProgressUpdate() throws IOException { - long bytesWritten = getCount(); - long contentLength = contentLength(); - mProgressListener.onProgress( - bytesWritten, contentLength, bytesWritten == contentLength); - } - }); + private void sendProgressUpdate() throws IOException { + long bytesWritten = getCount(); + long contentLength = contentLength(); + mProgressListener.onProgress( + bytesWritten, contentLength, bytesWritten == contentLength); + } + }); } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/network/ProgressResponseBody.java b/ReactAndroid/src/main/java/com/facebook/react/modules/network/ProgressResponseBody.java index 6075ec9d82e..6e219cfaa3f 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/network/ProgressResponseBody.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/network/ProgressResponseBody.java @@ -7,7 +7,6 @@ package com.facebook.react.modules.network; import java.io.IOException; import javax.annotation.Nullable; - import okhttp3.MediaType; import okhttp3.ResponseBody; import okio.Buffer; @@ -18,48 +17,50 @@ import okio.Source; public class ProgressResponseBody extends ResponseBody { - private final ResponseBody mResponseBody; - private final ProgressListener mProgressListener; - private @Nullable BufferedSource mBufferedSource; - private long mTotalBytesRead; + private final ResponseBody mResponseBody; + private final ProgressListener mProgressListener; + private @Nullable BufferedSource mBufferedSource; + private long mTotalBytesRead; - public ProgressResponseBody(ResponseBody responseBody, ProgressListener progressListener) { - this.mResponseBody = responseBody; - this.mProgressListener = progressListener; - mTotalBytesRead = 0L; - } + public ProgressResponseBody(ResponseBody responseBody, ProgressListener progressListener) { + this.mResponseBody = responseBody; + this.mProgressListener = progressListener; + mTotalBytesRead = 0L; + } - @Override - public MediaType contentType() { - return mResponseBody.contentType(); - } + @Override + public MediaType contentType() { + return mResponseBody.contentType(); + } - @Override - public long contentLength() { - return mResponseBody.contentLength(); - } + @Override + public long contentLength() { + return mResponseBody.contentLength(); + } - public long totalBytesRead() { - return mTotalBytesRead; - } + public long totalBytesRead() { + return mTotalBytesRead; + } - @Override public BufferedSource source() { - if (mBufferedSource == null) { - mBufferedSource = Okio.buffer(source(mResponseBody.source())); - } - return mBufferedSource; + @Override + public BufferedSource source() { + if (mBufferedSource == null) { + mBufferedSource = Okio.buffer(source(mResponseBody.source())); } + return mBufferedSource; + } - private Source source(Source source) { - return new ForwardingSource(source) { - @Override public long read(Buffer sink, long byteCount) throws IOException { - long bytesRead = super.read(sink, byteCount); - // read() returns the number of bytes read, or -1 if this source is exhausted. - mTotalBytesRead += bytesRead != -1 ? bytesRead : 0; - mProgressListener.onProgress( - mTotalBytesRead, mResponseBody.contentLength(), bytesRead == -1); - return bytesRead; - } - }; - } + private Source source(Source source) { + return new ForwardingSource(source) { + @Override + public long read(Buffer sink, long byteCount) throws IOException { + long bytesRead = super.read(sink, byteCount); + // read() returns the number of bytes read, or -1 if this source is exhausted. + mTotalBytesRead += bytesRead != -1 ? bytesRead : 0; + mProgressListener.onProgress( + mTotalBytesRead, mResponseBody.contentLength(), bytesRead == -1); + return bytesRead; + } + }; + } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/network/ProgressiveStringDecoder.java b/ReactAndroid/src/main/java/com/facebook/react/modules/network/ProgressiveStringDecoder.java index 45a1fe298a5..93f81d7010f 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/network/ProgressiveStringDecoder.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/network/ProgressiveStringDecoder.java @@ -1,14 +1,13 @@ /** -* Copyright (c) Facebook, Inc. and its affiliates. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + * Copyright (c) Facebook, Inc. and its affiliates. + * + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. + */ package com.facebook.react.modules.network; import com.facebook.common.logging.FLog; import com.facebook.react.common.ReactConstants; - import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.CharacterCodingException; @@ -16,13 +15,12 @@ import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; /** - * Class to decode encoded strings from byte array chunks. - * As in different encodings single character could take up to 4 characters byte array passed to - * decode could have parts of the characters which can't be correctly decoded. - * - * This class is designed in assumption that original byte stream is correctly formatted string in - * given encoding. Otherwise some parts of the data won't be decoded. + * Class to decode encoded strings from byte array chunks. As in different encodings single + * character could take up to 4 characters byte array passed to decode could have parts of the + * characters which can't be correctly decoded. * + *

This class is designed in assumption that original byte stream is correctly formatted string + * in given encoding. Otherwise some parts of the data won't be decoded. */ public class ProgressiveStringDecoder { @@ -32,17 +30,15 @@ public class ProgressiveStringDecoder { private byte[] remainder = null; - /** - * @param charset expected charset of the data - */ + /** @param charset expected charset of the data */ public ProgressiveStringDecoder(Charset charset) { mDecoder = charset.newDecoder(); } /** - * Parses data to String - * If there is a partial multi-byte symbol on the edge of the String it get saved to the - * reminder and added to the string on the decodeNext call. + * Parses data to String If there is a partial multi-byte symbol on the edge of the String it get + * saved to the reminder and added to the string on the decodeNext call. + * * @param data * @return */ diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/network/ReactCookieJarContainer.java b/ReactAndroid/src/main/java/com/facebook/react/modules/network/ReactCookieJarContainer.java index 0589bfd1705..ffca72e91d4 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/network/ReactCookieJarContainer.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/network/ReactCookieJarContainer.java @@ -1,30 +1,24 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.network; import java.util.ArrayList; import java.util.Collections; import java.util.List; - import javax.annotation.Nullable; - import okhttp3.Cookie; import okhttp3.CookieJar; import okhttp3.Headers; import okhttp3.HttpUrl; -/** - * Basic okhttp3 CookieJar container - */ +/** Basic okhttp3 CookieJar container */ public class ReactCookieJarContainer implements CookieJarContainer { - @Nullable - private CookieJar cookieJar = null; + @Nullable private CookieJar cookieJar = null; @Override public void setCookieJar(CookieJar cookieJar) { diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/network/RequestBodyUtil.java b/ReactAndroid/src/main/java/com/facebook/react/modules/network/RequestBodyUtil.java index f3eeb389548..26b409bc41b 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/network/RequestBodyUtil.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/network/RequestBodyUtil.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.network; import android.content.Context; @@ -41,9 +40,7 @@ import okio.Source; private static final String NAME = "RequestBodyUtil"; private static final String TEMP_FILE_SUFFIX = "temp"; - /** - * Returns whether encode type indicates the body needs to be gzip-ed. - */ + /** Returns whether encode type indicates the body needs to be gzip-ed. */ public static boolean isGzipEncoding(@Nullable final String encodingType) { return CONTENT_ENCODING_GZIP.equalsIgnoreCase(encodingType); } @@ -53,8 +50,7 @@ import okio.Source; * been found or if an error as occurred. */ public static @Nullable InputStream getFileInputStream( - Context context, - String fileContentUriStr) { + Context context, String fileContentUriStr) { try { Uri fileContentUri = Uri.parse(fileContentUriStr); @@ -63,10 +59,7 @@ import okio.Source; } return context.getContentResolver().openInputStream(fileContentUri); } catch (Exception e) { - FLog.e( - ReactConstants.TAG, - "Could not retrieve file for contentUri " + fileContentUriStr, - e); + FLog.e(ReactConstants.TAG, "Could not retrieve file for contentUri " + fileContentUriStr, e); return null; } } @@ -114,9 +107,7 @@ import okio.Source; return RequestBody.create(mediaType, gzipByteArrayOutputStream.toByteArray()); } - /** - * Creates a RequestBody from a mediaType and inputStream given. - */ + /** Creates a RequestBody from a mediaType and inputStream given. */ public static RequestBody create(final MediaType mediaType, final InputStream inputStream) { return new RequestBody() { @Override @@ -146,18 +137,13 @@ import okio.Source; }; } - /** - * Creates a ProgressRequestBody that can be used for showing uploading progress - */ + /** Creates a ProgressRequestBody that can be used for showing uploading progress */ public static ProgressRequestBody createProgressRequest( - RequestBody requestBody, - ProgressListener listener) { + RequestBody requestBody, ProgressListener listener) { return new ProgressRequestBody(requestBody, listener); } - /** - * Creates a empty RequestBody if required by the http method spec, otherwise use null - */ + /** Creates a empty RequestBody if required by the http method spec, otherwise use null */ public static RequestBody getEmptyBody(String method) { if (method.equals("POST") || method.equals("PUT") || method.equals("PATCH")) { return RequestBody.create(null, ByteString.EMPTY); diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/network/ResponseUtil.java b/ReactAndroid/src/main/java/com/facebook/react/modules/network/ResponseUtil.java index 9ad7bffdac0..7c81a09b184 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/network/ResponseUtil.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/network/ResponseUtil.java @@ -1,29 +1,21 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.network; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.WritableArray; import com.facebook.react.bridge.WritableMap; import com.facebook.react.modules.core.DeviceEventManagerModule.RCTDeviceEventEmitter; - -import java.io.IOException; import java.net.SocketTimeoutException; -/** - * Util methods to send network responses to JS. - */ +/** Util methods to send network responses to JS. */ public class ResponseUtil { public static void onDataSend( - RCTDeviceEventEmitter eventEmitter, - int requestId, - long progress, - long total) { + RCTDeviceEventEmitter eventEmitter, int requestId, long progress, long total) { WritableArray args = Arguments.createArray(); args.pushInt(requestId); args.pushInt((int) progress); @@ -32,11 +24,7 @@ public class ResponseUtil { } public static void onIncrementalDataReceived( - RCTDeviceEventEmitter eventEmitter, - int requestId, - String data, - long progress, - long total) { + RCTDeviceEventEmitter eventEmitter, int requestId, String data, long progress, long total) { WritableArray args = Arguments.createArray(); args.pushInt(requestId); args.pushString(data); @@ -47,10 +35,7 @@ public class ResponseUtil { } public static void onDataReceivedProgress( - RCTDeviceEventEmitter eventEmitter, - int requestId, - long progress, - long total) { + RCTDeviceEventEmitter eventEmitter, int requestId, long progress, long total) { WritableArray args = Arguments.createArray(); args.pushInt(requestId); args.pushInt((int) progress); @@ -60,9 +45,7 @@ public class ResponseUtil { } public static void onDataReceived( - RCTDeviceEventEmitter eventEmitter, - int requestId, - String data) { + RCTDeviceEventEmitter eventEmitter, int requestId, String data) { WritableArray args = Arguments.createArray(); args.pushInt(requestId); args.pushString(data); @@ -71,9 +54,7 @@ public class ResponseUtil { } public static void onDataReceived( - RCTDeviceEventEmitter eventEmitter, - int requestId, - WritableMap data) { + RCTDeviceEventEmitter eventEmitter, int requestId, WritableMap data) { WritableArray args = Arguments.createArray(); args.pushInt(requestId); args.pushMap(data); @@ -82,10 +63,7 @@ public class ResponseUtil { } public static void onRequestError( - RCTDeviceEventEmitter eventEmitter, - int requestId, - String error, - Throwable e) { + RCTDeviceEventEmitter eventEmitter, int requestId, String error, Throwable e) { WritableArray args = Arguments.createArray(); args.pushInt(requestId); args.pushString(error); @@ -106,11 +84,11 @@ public class ResponseUtil { } public static void onResponseReceived( - RCTDeviceEventEmitter eventEmitter, - int requestId, - int statusCode, - WritableMap headers, - String url) { + RCTDeviceEventEmitter eventEmitter, + int requestId, + int statusCode, + WritableMap headers, + String url) { WritableArray args = Arguments.createArray(); args.pushInt(requestId); args.pushInt(statusCode); diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/network/TLSSocketFactory.java b/ReactAndroid/src/main/java/com/facebook/react/modules/network/TLSSocketFactory.java index 9c603742622..5a3098d5956 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/network/TLSSocketFactory.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/network/TLSSocketFactory.java @@ -1,8 +1,8 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ package com.facebook.react.modules.network; @@ -12,65 +12,66 @@ import java.net.Socket; import java.net.UnknownHostException; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; - import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; /** - * * This class is needed for TLS 1.2 support on Android 4.x * - * Source: http://blog.dev-area.net/2015/08/13/android-4-1-enable-tls-1-1-and-tls-1-2/ + *

Source: http://blog.dev-area.net/2015/08/13/android-4-1-enable-tls-1-1-and-tls-1-2/ */ public class TLSSocketFactory extends SSLSocketFactory { - private SSLSocketFactory delegate; + private SSLSocketFactory delegate; - public TLSSocketFactory() throws KeyManagementException, NoSuchAlgorithmException { - SSLContext context = SSLContext.getInstance("TLS"); - context.init(null, null, null); - delegate = context.getSocketFactory(); - } + public TLSSocketFactory() throws KeyManagementException, NoSuchAlgorithmException { + SSLContext context = SSLContext.getInstance("TLS"); + context.init(null, null, null); + delegate = context.getSocketFactory(); + } - @Override - public String[] getDefaultCipherSuites() { - return delegate.getDefaultCipherSuites(); - } + @Override + public String[] getDefaultCipherSuites() { + return delegate.getDefaultCipherSuites(); + } - @Override - public String[] getSupportedCipherSuites() { - return delegate.getSupportedCipherSuites(); - } + @Override + public String[] getSupportedCipherSuites() { + return delegate.getSupportedCipherSuites(); + } - @Override - public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException { - return enableTLSOnSocket(delegate.createSocket(s, host, port, autoClose)); - } + @Override + public Socket createSocket(Socket s, String host, int port, boolean autoClose) + throws IOException { + return enableTLSOnSocket(delegate.createSocket(s, host, port, autoClose)); + } - @Override - public Socket createSocket(String host, int port) throws IOException, UnknownHostException { - return enableTLSOnSocket(delegate.createSocket(host, port)); - } + @Override + public Socket createSocket(String host, int port) throws IOException, UnknownHostException { + return enableTLSOnSocket(delegate.createSocket(host, port)); + } - @Override - public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException { - return enableTLSOnSocket(delegate.createSocket(host, port, localHost, localPort)); - } + @Override + public Socket createSocket(String host, int port, InetAddress localHost, int localPort) + throws IOException, UnknownHostException { + return enableTLSOnSocket(delegate.createSocket(host, port, localHost, localPort)); + } - @Override - public Socket createSocket(InetAddress host, int port) throws IOException { - return enableTLSOnSocket(delegate.createSocket(host, port)); - } + @Override + public Socket createSocket(InetAddress host, int port) throws IOException { + return enableTLSOnSocket(delegate.createSocket(host, port)); + } - @Override - public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException { - return enableTLSOnSocket(delegate.createSocket(address, port, localAddress, localPort)); - } + @Override + public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) + throws IOException { + return enableTLSOnSocket(delegate.createSocket(address, port, localAddress, localPort)); + } - private Socket enableTLSOnSocket(Socket socket) { - if(socket != null && (socket instanceof SSLSocket)) { - ((SSLSocket)socket).setEnabledProtocols(new String[] {"TLSv1", "TLSv1.1", "TLSv1.2"}); - } - return socket; + private Socket enableTLSOnSocket(Socket socket) { + if (socket != null && (socket instanceof SSLSocket)) { + ((SSLSocket) socket).setEnabledProtocols(new String[] {"TLSv1", "TLSv1.1", "TLSv1.2"}); } + return socket; + } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/permissions/PermissionsModule.java b/ReactAndroid/src/main/java/com/facebook/react/modules/permissions/PermissionsModule.java index dd7c1237695..6172df1eca7 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/permissions/PermissionsModule.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/permissions/PermissionsModule.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.permissions; import android.app.Activity; @@ -26,9 +25,7 @@ import com.facebook.react.modules.core.PermissionAwareActivity; import com.facebook.react.modules.core.PermissionListener; import java.util.ArrayList; -/** - * Module that exposes the Android M Permission system to JS. - */ +/** Module that exposes the Android M Permission system to JS. */ @ReactModule(name = PermissionsModule.NAME) public class PermissionsModule extends ReactContextBaseJavaModule implements PermissionListener { @@ -58,8 +55,9 @@ public class PermissionsModule extends ReactContextBaseJavaModule implements Per public void checkPermission(final String permission, final Promise promise) { Context context = getReactApplicationContext().getBaseContext(); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { - promise.resolve(context.checkPermission(permission, Process.myPid(), Process.myUid()) == - PackageManager.PERMISSION_GRANTED); + promise.resolve( + context.checkPermission(permission, Process.myPid(), Process.myUid()) + == PackageManager.PERMISSION_GRANTED); return; } promise.resolve(context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED); @@ -67,11 +65,11 @@ public class PermissionsModule extends ReactContextBaseJavaModule implements Per /** * Check whether the app should display a message explaining why a certain permission is needed. - * successCallback is called with true if the app should display a message, false otherwise. - * This message is only displayed if the user has revoked this permission once before, and if the + * successCallback is called with true if the app should display a message, false otherwise. This + * message is only displayed if the user has revoked this permission once before, and if the * permission dialog will be shown to the user (the user can choose to not be shown that dialog - * again). For devices before Android M, this always returns false. - * See {@link Activity#shouldShowRequestPermissionRationale}. + * again). For devices before Android M, this always returns false. See {@link + * Activity#shouldShowRequestPermissionRationale}. */ @ReactMethod public void shouldShowRequestPermissionRationale(final String permission, final Promise promise) { @@ -80,7 +78,8 @@ public class PermissionsModule extends ReactContextBaseJavaModule implements Per return; } try { - promise.resolve(getPermissionAwareActivity().shouldShowRequestPermissionRationale(permission)); + promise.resolve( + getPermissionAwareActivity().shouldShowRequestPermissionRationale(permission)); } catch (IllegalStateException e) { promise.reject(ERROR_INVALID_ACTIVITY, e); } @@ -88,16 +87,19 @@ public class PermissionsModule extends ReactContextBaseJavaModule implements Per /** * Request the given permission. successCallback is called with GRANTED if the permission had been - * granted, DENIED or NEVER_ASK_AGAIN otherwise. For devices before Android M, this checks if the user has - * the permission given or not and resolves with GRANTED or DENIED. - * See {@link Activity#checkSelfPermission}. + * granted, DENIED or NEVER_ASK_AGAIN otherwise. For devices before Android M, this checks if the + * user has the permission given or not and resolves with GRANTED or DENIED. See {@link + * Activity#checkSelfPermission}. */ @ReactMethod public void requestPermission(final String permission, final Promise promise) { Context context = getReactApplicationContext().getBaseContext(); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { - promise.resolve(context.checkPermission(permission, Process.myPid(), Process.myUid()) == - PackageManager.PERMISSION_GRANTED ? GRANTED : DENIED); + promise.resolve( + context.checkPermission(permission, Process.myPid(), Process.myUid()) + == PackageManager.PERMISSION_GRANTED + ? GRANTED + : DENIED); return; } if (context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED) { @@ -109,25 +111,25 @@ public class PermissionsModule extends ReactContextBaseJavaModule implements Per PermissionAwareActivity activity = getPermissionAwareActivity(); mCallbacks.put( - mRequestCode, new Callback() { - @Override - public void invoke(Object... args) { - int[] results = (int[]) args[0]; - if (results.length > 0 && results[0] == PackageManager.PERMISSION_GRANTED) { - promise.resolve(GRANTED); - } else { - PermissionAwareActivity activity = (PermissionAwareActivity) args[1]; - if (activity.shouldShowRequestPermissionRationale(permission)) { - promise.resolve(DENIED); + mRequestCode, + new Callback() { + @Override + public void invoke(Object... args) { + int[] results = (int[]) args[0]; + if (results.length > 0 && results[0] == PackageManager.PERMISSION_GRANTED) { + promise.resolve(GRANTED); } else { - promise.resolve(NEVER_ASK_AGAIN); + PermissionAwareActivity activity = (PermissionAwareActivity) args[1]; + if (activity.shouldShowRequestPermissionRationale(permission)) { + promise.resolve(DENIED); + } else { + promise.resolve(NEVER_ASK_AGAIN); + } } } - } - } - ); + }); - activity.requestPermissions(new String[]{permission}, mRequestCode, this); + activity.requestPermissions(new String[] {permission}, mRequestCode, this); mRequestCode++; } catch (IllegalStateException e) { promise.reject(ERROR_INVALID_ACTIVITY, e); @@ -146,8 +148,12 @@ public class PermissionsModule extends ReactContextBaseJavaModule implements Per String perm = permissions.getString(i); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { - grantedPermissions.putString(perm, context.checkPermission(perm, Process.myPid(), Process.myUid()) == - PackageManager.PERMISSION_GRANTED ? GRANTED : DENIED); + grantedPermissions.putString( + perm, + context.checkPermission(perm, Process.myPid(), Process.myUid()) + == PackageManager.PERMISSION_GRANTED + ? GRANTED + : DENIED); checkedPermissionsCount++; } else if (context.checkSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) { grantedPermissions.putString(perm, GRANTED); @@ -165,26 +171,27 @@ public class PermissionsModule extends ReactContextBaseJavaModule implements Per PermissionAwareActivity activity = getPermissionAwareActivity(); mCallbacks.put( - mRequestCode, new Callback() { - @Override - public void invoke(Object... args) { - int[] results = (int[]) args[0]; - PermissionAwareActivity activity = (PermissionAwareActivity) args[1]; - for (int j = 0; j < permissionsToCheck.size(); j++) { - String permission = permissionsToCheck.get(j); - if (results.length > 0 && results[j] == PackageManager.PERMISSION_GRANTED) { - grantedPermissions.putString(permission, GRANTED); - } else { - if (activity.shouldShowRequestPermissionRationale(permission)) { - grantedPermissions.putString(permission, DENIED); - } else { - grantedPermissions.putString(permission, NEVER_ASK_AGAIN); + mRequestCode, + new Callback() { + @Override + public void invoke(Object... args) { + int[] results = (int[]) args[0]; + PermissionAwareActivity activity = (PermissionAwareActivity) args[1]; + for (int j = 0; j < permissionsToCheck.size(); j++) { + String permission = permissionsToCheck.get(j); + if (results.length > 0 && results[j] == PackageManager.PERMISSION_GRANTED) { + grantedPermissions.putString(permission, GRANTED); + } else { + if (activity.shouldShowRequestPermissionRationale(permission)) { + grantedPermissions.putString(permission, DENIED); + } else { + grantedPermissions.putString(permission, NEVER_ASK_AGAIN); + } + } } + promise.resolve(grantedPermissions); } - } - promise.resolve(grantedPermissions); - } - }); + }); activity.requestPermissions(permissionsToCheck.toArray(new String[0]), mRequestCode, this); mRequestCode++; @@ -193,27 +200,24 @@ public class PermissionsModule extends ReactContextBaseJavaModule implements Per } } - /** - * Method called by the activity with the result of the permission request. - */ + /** Method called by the activity with the result of the permission request. */ @Override public boolean onRequestPermissionsResult( - int requestCode, - String[] permissions, - int[] grantResults) { - mCallbacks.get(requestCode).invoke(grantResults, getPermissionAwareActivity()); - mCallbacks.remove(requestCode); - return mCallbacks.size() == 0; + int requestCode, String[] permissions, int[] grantResults) { + mCallbacks.get(requestCode).invoke(grantResults, getPermissionAwareActivity()); + mCallbacks.remove(requestCode); + return mCallbacks.size() == 0; } private PermissionAwareActivity getPermissionAwareActivity() { Activity activity = getCurrentActivity(); if (activity == null) { - throw new IllegalStateException("Tried to use permissions API while not attached to an " + - "Activity."); + throw new IllegalStateException( + "Tried to use permissions API while not attached to an " + "Activity."); } else if (!(activity instanceof PermissionAwareActivity)) { - throw new IllegalStateException("Tried to use permissions API but the host Activity doesn't" + - " implement PermissionAwareActivity."); + throw new IllegalStateException( + "Tried to use permissions API but the host Activity doesn't" + + " implement PermissionAwareActivity."); } return (PermissionAwareActivity) activity; } diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/share/ShareModule.java b/ReactAndroid/src/main/java/com/facebook/react/modules/share/ShareModule.java index 4db2c4ae608..d6b91febeaa 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/share/ShareModule.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/share/ShareModule.java @@ -1,15 +1,13 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.share; import android.app.Activity; import android.content.Intent; - import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.Promise; import com.facebook.react.bridge.ReactApplicationContext; @@ -19,9 +17,7 @@ import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.WritableMap; import com.facebook.react.module.annotations.ReactModule; -/** - * Intent module. Launch other activities or open URLs. - */ +/** Intent module. Launch other activities or open URLs. */ @ReactModule(name = ShareModule.NAME) public class ShareModule extends ReactContextBaseJavaModule { @@ -42,7 +38,7 @@ public class ShareModule extends ReactContextBaseJavaModule { /** * Open a chooser dialog to send text content to other apps. * - * Refer http://developer.android.com/intl/ko/training/sharing/send.html + *

Refer http://developer.android.com/intl/ko/training/sharing/send.html * * @param content the data to send * @param dialogTitle the title of the chooser dialog diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/statusbar/StatusBarModule.java b/ReactAndroid/src/main/java/com/facebook/react/modules/statusbar/StatusBarModule.java index 8d7de95bd03..046db432185 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/statusbar/StatusBarModule.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/statusbar/StatusBarModule.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.statusbar; import android.animation.ArgbEvaluator; @@ -13,10 +12,10 @@ import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.os.Build; -import androidx.core.view.ViewCompat; import android.view.View; import android.view.WindowInsets; import android.view.WindowManager; +import androidx.core.view.ViewCompat; import com.facebook.common.logging.FLog; import com.facebook.react.bridge.GuardedRunnable; import com.facebook.react.bridge.NativeModule; @@ -31,9 +30,7 @@ import com.facebook.react.uimanager.PixelUtil; import java.util.Map; import javax.annotation.Nullable; -/** - * {@link NativeModule} that allows changing the appearance of the status bar. - */ +/** {@link NativeModule} that allows changing the appearance of the status bar. */ @ReactModule(name = StatusBarModule.NAME) public class StatusBarModule extends ReactContextBaseJavaModule { @@ -55,11 +52,12 @@ public class StatusBarModule extends ReactContextBaseJavaModule { final Context context = getReactApplicationContext(); final Activity activity = getCurrentActivity(); - final int heightResId = context.getResources() - .getIdentifier("status_bar_height", "dimen", "android"); - final float height = heightResId > 0 ? - PixelUtil.toDIPFromPixel(context.getResources().getDimensionPixelSize(heightResId)) : - 0; + final int heightResId = + context.getResources().getIdentifier("status_bar_height", "dimen", "android"); + final float height = + heightResId > 0 + ? PixelUtil.toDIPFromPixel(context.getResources().getDimensionPixelSize(heightResId)) + : 0; String statusBarColorString = "black"; if (activity != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { @@ -68,14 +66,16 @@ public class StatusBarModule extends ReactContextBaseJavaModule { } return MapBuilder.of( - HEIGHT_KEY, height, DEFAULT_BACKGROUND_COLOR_KEY, statusBarColorString); + HEIGHT_KEY, height, DEFAULT_BACKGROUND_COLOR_KEY, statusBarColorString); } @ReactMethod public void setColor(final int color, final boolean animated) { final Activity activity = getCurrentActivity(); if (activity == null) { - FLog.w(ReactConstants.TAG, "StatusBarModule: Ignored status bar change, current activity is null."); + FLog.w( + ReactConstants.TAG, + "StatusBarModule: Ignored status bar change, current activity is null."); return; } @@ -117,38 +117,41 @@ public class StatusBarModule extends ReactContextBaseJavaModule { public void setTranslucent(final boolean translucent) { final Activity activity = getCurrentActivity(); if (activity == null) { - FLog.w(ReactConstants.TAG, "StatusBarModule: Ignored status bar change, current activity is null."); + FLog.w( + ReactConstants.TAG, + "StatusBarModule: Ignored status bar change, current activity is null."); return; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { UiThreadUtil.runOnUiThread( - new GuardedRunnable(getReactApplicationContext()) { - @TargetApi(Build.VERSION_CODES.LOLLIPOP) - @Override - public void runGuarded() { - // If the status bar is translucent hook into the window insets calculations - // and consume all the top insets so no padding will be added under the status bar. - View decorView = activity.getWindow().getDecorView(); - if (translucent) { - decorView.setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() { - @Override - public WindowInsets onApplyWindowInsets(View v, WindowInsets insets) { - WindowInsets defaultInsets = v.onApplyWindowInsets(insets); - return defaultInsets.replaceSystemWindowInsets( - defaultInsets.getSystemWindowInsetLeft(), - 0, - defaultInsets.getSystemWindowInsetRight(), - defaultInsets.getSystemWindowInsetBottom()); - } - }); - } else { - decorView.setOnApplyWindowInsetsListener(null); - } + new GuardedRunnable(getReactApplicationContext()) { + @TargetApi(Build.VERSION_CODES.LOLLIPOP) + @Override + public void runGuarded() { + // If the status bar is translucent hook into the window insets calculations + // and consume all the top insets so no padding will be added under the status bar. + View decorView = activity.getWindow().getDecorView(); + if (translucent) { + decorView.setOnApplyWindowInsetsListener( + new View.OnApplyWindowInsetsListener() { + @Override + public WindowInsets onApplyWindowInsets(View v, WindowInsets insets) { + WindowInsets defaultInsets = v.onApplyWindowInsets(insets); + return defaultInsets.replaceSystemWindowInsets( + defaultInsets.getSystemWindowInsetLeft(), + 0, + defaultInsets.getSystemWindowInsetRight(), + defaultInsets.getSystemWindowInsetBottom()); + } + }); + } else { + decorView.setOnApplyWindowInsetsListener(null); + } - ViewCompat.requestApplyInsets(decorView); - } - }); + ViewCompat.requestApplyInsets(decorView); + } + }); } } @@ -156,49 +159,52 @@ public class StatusBarModule extends ReactContextBaseJavaModule { public void setHidden(final boolean hidden) { final Activity activity = getCurrentActivity(); if (activity == null) { - FLog.w(ReactConstants.TAG, "StatusBarModule: Ignored status bar change, current activity is null."); + FLog.w( + ReactConstants.TAG, + "StatusBarModule: Ignored status bar change, current activity is null."); return; } UiThreadUtil.runOnUiThread( - new Runnable() { - @Override - public void run() { - if (hidden) { - activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); - activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); - } else { - activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); - activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); + new Runnable() { + @Override + public void run() { + if (hidden) { + activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); + activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); + } else { + activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); + activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); + } } - } - }); + }); } @ReactMethod public void setStyle(@Nullable final String style) { final Activity activity = getCurrentActivity(); if (activity == null) { - FLog.w(ReactConstants.TAG, "StatusBarModule: Ignored status bar change, current activity is null."); + FLog.w( + ReactConstants.TAG, + "StatusBarModule: Ignored status bar change, current activity is null."); return; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { UiThreadUtil.runOnUiThread( - new Runnable() { - @TargetApi(Build.VERSION_CODES.M) - @Override - public void run() { - View decorView = activity.getWindow().getDecorView(); - int systemUiVisibilityFlags = decorView.getSystemUiVisibility(); - if ("dark-content".equals(style)) { - systemUiVisibilityFlags |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR; - } else { - systemUiVisibilityFlags &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR; + new Runnable() { + @TargetApi(Build.VERSION_CODES.M) + @Override + public void run() { + View decorView = activity.getWindow().getDecorView(); + int systemUiVisibilityFlags = decorView.getSystemUiVisibility(); + if ("dark-content".equals(style)) { + systemUiVisibilityFlags |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR; + } else { + systemUiVisibilityFlags &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR; + } + decorView.setSystemUiVisibility(systemUiVisibilityFlags); } - decorView.setSystemUiVisibility(systemUiVisibilityFlags); - } - } - ); + }); } } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/storage/AsyncLocalStorageUtil.java b/ReactAndroid/src/main/java/com/facebook/react/modules/storage/AsyncLocalStorageUtil.java index 9efcad64167..5c150eb902e 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/storage/AsyncLocalStorageUtil.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/storage/AsyncLocalStorageUtil.java @@ -1,40 +1,32 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.storage; -import javax.annotation.Nullable; - -import java.util.Arrays; -import java.util.Iterator; - -import android.content.ContentValues; -import android.database.Cursor; -import android.database.sqlite.SQLiteDatabase; -import android.text.TextUtils; - -import com.facebook.react.bridge.ReadableArray; - -import org.json.JSONException; -import org.json.JSONObject; - import static com.facebook.react.modules.storage.ReactDatabaseSupplier.KEY_COLUMN; import static com.facebook.react.modules.storage.ReactDatabaseSupplier.TABLE_CATALYST; import static com.facebook.react.modules.storage.ReactDatabaseSupplier.VALUE_COLUMN; -/** - * Helper for database operations. - */ +import android.content.ContentValues; +import android.database.Cursor; +import android.database.sqlite.SQLiteDatabase; +import android.text.TextUtils; +import com.facebook.react.bridge.ReadableArray; +import java.util.Arrays; +import java.util.Iterator; +import javax.annotation.Nullable; +import org.json.JSONException; +import org.json.JSONObject; + +/** Helper for database operations. */ public class AsyncLocalStorageUtil { /** - * Build the String required for an SQL select statement: - * WHERE key IN (?, ?, ..., ?) - * without 'WHERE' and with selectionCount '?' + * Build the String required for an SQL select statement: WHERE key IN (?, ?, ..., ?) without + * 'WHERE' and with selectionCount '?' */ /* package */ static String buildKeySelection(int selectionCount) { String[] list = new String[selectionCount]; @@ -43,9 +35,8 @@ public class AsyncLocalStorageUtil { } /** - * Build the String[] arguments needed for an SQL selection, i.e.: - * {a, b, c} - * to be used in the SQL select statement: WHERE key in (?, ?, ?) + * Build the String[] arguments needed for an SQL selection, i.e.: {a, b, c} to be used in the SQL + * select statement: WHERE key in (?, ?, ?) */ /* package */ static String[] buildKeySelectionArgs(ReadableArray keys, int start, int count) { String[] selectionArgs = new String[count]; @@ -55,21 +46,13 @@ public class AsyncLocalStorageUtil { return selectionArgs; } - /** - * Returns the value of the given key, or null if not found. - */ + /** Returns the value of the given key, or null if not found. */ public static @Nullable String getItemImpl(SQLiteDatabase db, String key) { String[] columns = {VALUE_COLUMN}; String[] selectionArgs = {key}; - Cursor cursor = db.query( - TABLE_CATALYST, - columns, - KEY_COLUMN + "=?", - selectionArgs, - null, - null, - null); + Cursor cursor = + db.query(TABLE_CATALYST, columns, KEY_COLUMN + "=?", selectionArgs, null, null, null); try { if (!cursor.moveToFirst()) { @@ -82,26 +65,23 @@ public class AsyncLocalStorageUtil { } } - /** - * Sets the value for the key given, returns true if successful, false otherwise. - */ + /** Sets the value for the key given, returns true if successful, false otherwise. */ /* package */ static boolean setItemImpl(SQLiteDatabase db, String key, String value) { ContentValues contentValues = new ContentValues(); contentValues.put(KEY_COLUMN, key); contentValues.put(VALUE_COLUMN, value); - long inserted = db.insertWithOnConflict( - TABLE_CATALYST, - null, - contentValues, - SQLiteDatabase.CONFLICT_REPLACE); + long inserted = + db.insertWithOnConflict( + TABLE_CATALYST, null, contentValues, SQLiteDatabase.CONFLICT_REPLACE); return (-1 != inserted); } /** - * Does the actual merge of the (key, value) pair with the value stored in the database. - * NB: This assumes that a database lock is already in effect! + * Does the actual merge of the (key, value) pair with the value stored in the database. NB: This + * assumes that a database lock is already in effect! + * * @return the errorCode of the operation */ /* package */ static boolean mergeImpl(SQLiteDatabase db, String key, String value) @@ -126,8 +106,7 @@ public class AsyncLocalStorageUtil { * either overriding its values, or merging them (if the values of the same key in both objects * are of type {@link JSONObject}). oldJSON will contain the result of this merge. */ - private static void deepMergeInto(JSONObject oldJSON, JSONObject newJSON) - throws JSONException { + private static void deepMergeInto(JSONObject oldJSON, JSONObject newJSON) throws JSONException { Iterator keys = newJSON.keys(); while (keys.hasNext()) { String key = (String) keys.next(); diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/storage/AsyncStorageErrorUtil.java b/ReactAndroid/src/main/java/com/facebook/react/modules/storage/AsyncStorageErrorUtil.java index fa5436ce009..a979f8a0b62 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/storage/AsyncStorageErrorUtil.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/storage/AsyncStorageErrorUtil.java @@ -1,25 +1,19 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.storage; -import javax.annotation.Nullable; - import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.WritableMap; +import javax.annotation.Nullable; -/** - * Helper class for database errors. - */ +/** Helper class for database errors. */ public class AsyncStorageErrorUtil { - /** - * Create Error object to be passed back to the JS callback. - */ + /** Create Error object to be passed back to the JS callback. */ /* package */ static WritableMap getError(@Nullable String key, String errorMessage) { WritableMap errorMap = Arguments.createMap(); errorMap.putString("message", errorMessage); @@ -40,6 +34,4 @@ public class AsyncStorageErrorUtil { /* package */ static WritableMap getDBError(@Nullable String key) { return getError(key, "Database Error"); } - - } diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/storage/AsyncStorageModule.java b/ReactAndroid/src/main/java/com/facebook/react/modules/storage/AsyncStorageModule.java index ad3bed5cdf4..628acfdf71e 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/storage/AsyncStorageModule.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/storage/AsyncStorageModule.java @@ -1,20 +1,18 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.storage; -import java.util.ArrayDeque; -import java.util.HashSet; -import java.util.concurrent.Executor; +import static com.facebook.react.modules.storage.ReactDatabaseSupplier.KEY_COLUMN; +import static com.facebook.react.modules.storage.ReactDatabaseSupplier.TABLE_CATALYST; +import static com.facebook.react.modules.storage.ReactDatabaseSupplier.VALUE_COLUMN; import android.database.Cursor; import android.database.sqlite.SQLiteStatement; import android.os.AsyncTask; - import com.facebook.common.logging.FLog; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.Callback; @@ -29,14 +27,13 @@ import com.facebook.react.common.ReactConstants; import com.facebook.react.common.annotations.VisibleForTesting; import com.facebook.react.module.annotations.ReactModule; import com.facebook.react.modules.common.ModuleDataCleaner; - -import static com.facebook.react.modules.storage.ReactDatabaseSupplier.KEY_COLUMN; -import static com.facebook.react.modules.storage.ReactDatabaseSupplier.TABLE_CATALYST; -import static com.facebook.react.modules.storage.ReactDatabaseSupplier.VALUE_COLUMN; +import java.util.ArrayDeque; +import java.util.HashSet; +import java.util.concurrent.Executor; @ReactModule(name = AsyncStorageModule.NAME) -public final class AsyncStorageModule - extends ReactContextBaseJavaModule implements ModuleDataCleaner.Cleanable { +public final class AsyncStorageModule extends ReactContextBaseJavaModule + implements ModuleDataCleaner.Cleanable { public static final String NAME = "AsyncSQLiteDBStorage"; @@ -47,7 +44,8 @@ public final class AsyncStorageModule private ReactDatabaseSupplier mReactDatabaseSupplier; private boolean mShuttingDown = false; - // Adapted from https://android.googlesource.com/platform/frameworks/base.git/+/1488a3a19d4681a41fb45570c15e14d99db1cb66/core/java/android/os/AsyncTask.java#237 + // Adapted from + // https://android.googlesource.com/platform/frameworks/base.git/+/1488a3a19d4681a41fb45570c15e14d99db1cb66/core/java/android/os/AsyncTask.java#237 private class SerialExecutor implements Executor { private final ArrayDeque mTasks = new ArrayDeque(); private Runnable mActive; @@ -58,19 +56,21 @@ public final class AsyncStorageModule } public synchronized void execute(final Runnable r) { - mTasks.offer(new Runnable() { - public void run() { - try { - r.run(); - } finally { - scheduleNext(); - } - } - }); + mTasks.offer( + new Runnable() { + public void run() { + try { + r.run(); + } finally { + scheduleNext(); + } + } + }); if (mActive == null) { scheduleNext(); } } + synchronized void scheduleNext() { if ((mActive = mTasks.poll()) != null) { executor.execute(mActive); @@ -79,7 +79,7 @@ public final class AsyncStorageModule } private final SerialExecutor executor; - + public AsyncStorageModule(ReactApplicationContext reactContext) { this(reactContext, AsyncTask.THREAD_POOL_EXECUTOR); } @@ -116,8 +116,8 @@ public final class AsyncStorageModule } /** - * Given an array of keys, this returns a map of (key, value) pairs for the keys found, and - * (key, null) for the keys that haven't been found. + * Given an array of keys, this returns a map of (key, value) pairs for the keys found, and (key, + * null) for the keys that haven't been found. */ @ReactMethod public void multiGet(final ReadableArray keys, final Callback callback) { @@ -139,14 +139,17 @@ public final class AsyncStorageModule WritableArray data = Arguments.createArray(); for (int keyStart = 0; keyStart < keys.size(); keyStart += MAX_SQL_KEYS) { int keyCount = Math.min(keys.size() - keyStart, MAX_SQL_KEYS); - Cursor cursor = mReactDatabaseSupplier.get().query( - TABLE_CATALYST, - columns, - AsyncLocalStorageUtil.buildKeySelection(keyCount), - AsyncLocalStorageUtil.buildKeySelectionArgs(keys, keyStart, keyCount), - null, - null, - null); + Cursor cursor = + mReactDatabaseSupplier + .get() + .query( + TABLE_CATALYST, + columns, + AsyncLocalStorageUtil.buildKeySelection(keyCount), + AsyncLocalStorageUtil.buildKeySelectionArgs(keys, keyStart, keyCount), + null, + null, + null); keysRemaining.clear(); try { if (cursor.getCount() != keys.size()) { @@ -189,8 +192,8 @@ public final class AsyncStorageModule /** * Inserts multiple (key, value) pairs. If one or more of the pairs cannot be inserted, this will - * return AsyncLocalStorageFailure, but all other pairs will have been inserted. - * The insertion will replace conflicting (key, value) pairs. + * return AsyncLocalStorageFailure, but all other pairs will have been inserted. The insertion + * will replace conflicting (key, value) pairs. */ @ReactMethod public void multiSet(final ReadableArray keyValueArray, final Callback callback) { @@ -212,7 +215,7 @@ public final class AsyncStorageModule WritableMap error = null; try { mReactDatabaseSupplier.get().beginTransaction(); - for (int idx=0; idx < keyValueArray.size(); idx++) { + for (int idx = 0; idx < keyValueArray.size(); idx++) { if (keyValueArray.getArray(idx).size() != 2) { error = AsyncStorageErrorUtil.getInvalidValueError(null); return; @@ -254,9 +257,7 @@ public final class AsyncStorageModule }.executeOnExecutor(executor); } - /** - * Removes all rows of the keys given. - */ + /** Removes all rows of the keys given. */ @ReactMethod public void multiRemove(final ReadableArray keys, final Callback callback) { if (keys.size() == 0) { @@ -277,10 +278,12 @@ public final class AsyncStorageModule mReactDatabaseSupplier.get().beginTransaction(); for (int keyStart = 0; keyStart < keys.size(); keyStart += MAX_SQL_KEYS) { int keyCount = Math.min(keys.size() - keyStart, MAX_SQL_KEYS); - mReactDatabaseSupplier.get().delete( - TABLE_CATALYST, - AsyncLocalStorageUtil.buildKeySelection(keyCount), - AsyncLocalStorageUtil.buildKeySelectionArgs(keys, keyStart, keyCount)); + mReactDatabaseSupplier + .get() + .delete( + TABLE_CATALYST, + AsyncLocalStorageUtil.buildKeySelection(keyCount), + AsyncLocalStorageUtil.buildKeySelectionArgs(keys, keyStart, keyCount)); } mReactDatabaseSupplier.get().setTransactionSuccessful(); } catch (Exception e) { @@ -288,7 +291,7 @@ public final class AsyncStorageModule error = AsyncStorageErrorUtil.getError(null, e.getMessage()); } finally { try { - mReactDatabaseSupplier.get().endTransaction(); + mReactDatabaseSupplier.get().endTransaction(); } catch (Exception e) { FLog.w(ReactConstants.TAG, e.getMessage(), e); if (error == null) { @@ -368,9 +371,7 @@ public final class AsyncStorageModule }.executeOnExecutor(executor); } - /** - * Clears the database. - */ + /** Clears the database. */ @ReactMethod public void clear(final Callback callback) { new GuardedAsyncTask(getReactApplicationContext()) { @@ -391,9 +392,7 @@ public final class AsyncStorageModule }.executeOnExecutor(executor); } - /** - * Returns an array with all keys from the database. - */ + /** Returns an array with all keys from the database. */ @ReactMethod public void getAllKeys(final Callback callback) { new GuardedAsyncTask(getReactApplicationContext()) { @@ -405,8 +404,10 @@ public final class AsyncStorageModule } WritableArray data = Arguments.createArray(); String[] columns = {KEY_COLUMN}; - Cursor cursor = mReactDatabaseSupplier.get() - .query(TABLE_CATALYST, columns, null, null, null, null, null); + Cursor cursor = + mReactDatabaseSupplier + .get() + .query(TABLE_CATALYST, columns, null, null, null, null, null); try { if (cursor.moveToFirst()) { do { @@ -425,9 +426,7 @@ public final class AsyncStorageModule }.executeOnExecutor(executor); } - /** - * Verify the database is open for reads and writes. - */ + /** Verify the database is open for reads and writes. */ private boolean ensureDatabase() { return !mShuttingDown && mReactDatabaseSupplier.ensureDatabase(); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/storage/ReactDatabaseSupplier.java b/ReactAndroid/src/main/java/com/facebook/react/modules/storage/ReactDatabaseSupplier.java index bcbb7f270d9..1f539bbc411 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/storage/ReactDatabaseSupplier.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/storage/ReactDatabaseSupplier.java @@ -1,21 +1,18 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.storage; -import javax.annotation.Nullable; - import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; - import com.facebook.common.logging.FLog; import com.facebook.react.common.ReactConstants; +import javax.annotation.Nullable; /** * Database supplier of the database used by react native. This creates, opens and deletes the @@ -34,16 +31,20 @@ public class ReactDatabaseSupplier extends SQLiteOpenHelper { static final String VALUE_COLUMN = "value"; static final String VERSION_TABLE_CREATE = - "CREATE TABLE " + TABLE_CATALYST + " (" + - KEY_COLUMN + " TEXT PRIMARY KEY, " + - VALUE_COLUMN + " TEXT NOT NULL" + - ")"; + "CREATE TABLE " + + TABLE_CATALYST + + " (" + + KEY_COLUMN + + " TEXT PRIMARY KEY, " + + VALUE_COLUMN + + " TEXT NOT NULL" + + ")"; private static @Nullable ReactDatabaseSupplier sReactDatabaseSupplierInstance; private Context mContext; private @Nullable SQLiteDatabase mDb; - private long mMaximumDatabaseSize = 6L * 1024L * 1024L; // 6 MB in bytes + private long mMaximumDatabaseSize = 6L * 1024L * 1024L; // 6 MB in bytes private ReactDatabaseSupplier(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); @@ -70,9 +71,7 @@ public class ReactDatabaseSupplier extends SQLiteOpenHelper { } } - /** - * Verify the database exists and is open. - */ + /** Verify the database exists and is open. */ /* package */ synchronized boolean ensureDatabase() { if (mDb != null && mDb.isOpen()) { return true; @@ -107,9 +106,7 @@ public class ReactDatabaseSupplier extends SQLiteOpenHelper { return true; } - /** - * Create and/or open the database. - */ + /** Create and/or open the database. */ public synchronized SQLiteDatabase get() { ensureDatabase(); return mDb; @@ -136,8 +133,8 @@ public class ReactDatabaseSupplier extends SQLiteOpenHelper { } /** - * Sets the maximum size the database will grow to. The maximum size cannot - * be set below the current size. + * Sets the maximum size the database will grow to. The maximum size cannot be set below the + * current size. */ public synchronized void setMaximumSize(long size) { mMaximumDatabaseSize = size; diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/systeminfo/AndroidInfoHelpers.java b/ReactAndroid/src/main/java/com/facebook/react/modules/systeminfo/AndroidInfoHelpers.java index 3659abaccc0..e35a2ad9175 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/systeminfo/AndroidInfoHelpers.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/systeminfo/AndroidInfoHelpers.java @@ -5,18 +5,16 @@ package com.facebook.react.modules.systeminfo; +import android.content.Context; +import android.content.res.Resources; +import android.os.Build; +import com.facebook.common.logging.FLog; +import com.facebook.react.R; import java.io.BufferedReader; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.util.Locale; -import android.content.Context; -import android.content.res.Resources; -import android.os.Build; - -import com.facebook.common.logging.FLog; -import com.facebook.react.R; - public class AndroidInfoHelpers { public static final String EMULATOR_LOCALHOST = "10.0.2.2"; @@ -55,7 +53,8 @@ public class AndroidInfoHelpers { return getServerIpAddress(getInspectorProxyPort(context)); } - // WARNING(festevezga): This RN helper method has been copied to another FB-only target. Any changes should be applied to both. + // WARNING(festevezga): This RN helper method has been copied to another FB-only target. Any + // changes should be applied to both. public static String getFriendlyDeviceName() { if (isRunningOnGenymotion()) { // Genymotion already has a friendly name by default @@ -95,6 +94,7 @@ public class AndroidInfoHelpers { } private static String metroHostPropValue = null; + private static synchronized String getMetroHostPropValue() { if (metroHostPropValue != null) { return metroHostPropValue; diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/systeminfo/AndroidInfoModule.java b/ReactAndroid/src/main/java/com/facebook/react/modules/systeminfo/AndroidInfoModule.java index 6e2d61a3f34..1d53f6987b5 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/systeminfo/AndroidInfoModule.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/systeminfo/AndroidInfoModule.java @@ -1,51 +1,48 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.systeminfo; +import static android.content.Context.UI_MODE_SERVICE; + import android.annotation.SuppressLint; import android.app.UiModeManager; -import android.content.Context; import android.content.res.Configuration; import android.content.res.Resources; import android.os.Build; import android.provider.Settings.Secure; - import com.facebook.react.R; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; -import com.facebook.react.common.build.ReactBuildConfig; import com.facebook.react.bridge.ReactMethod; +import com.facebook.react.common.build.ReactBuildConfig; import com.facebook.react.module.annotations.ReactModule; import com.facebook.react.turbomodule.core.interfaces.TurboModule; - import java.util.HashMap; import java.util.Map; - import javax.annotation.Nullable; -import static android.content.Context.UI_MODE_SERVICE; - -/** - * Module that exposes Android Constants to JS. - */ +/** Module that exposes Android Constants to JS. */ @ReactModule(name = AndroidInfoModule.NAME) @SuppressLint("HardwareIds") public class AndroidInfoModule extends ReactContextBaseJavaModule implements TurboModule { public static final String NAME = "PlatformConstants"; private static final String IS_TESTING = "IS_TESTING"; - public AndroidInfoModule(ReactApplicationContext reactContext) { super(reactContext); } + public AndroidInfoModule(ReactApplicationContext reactContext) { + super(reactContext); + } /** - * See: https://developer.android.com/reference/android/app/UiModeManager.html#getCurrentModeType() + * See: + * https://developer.android.com/reference/android/app/UiModeManager.html#getCurrentModeType() */ private String uiMode() { - UiModeManager uiModeManager = (UiModeManager) getReactApplicationContext().getSystemService(UI_MODE_SERVICE); + UiModeManager uiModeManager = + (UiModeManager) getReactApplicationContext().getSystemService(UI_MODE_SERVICE); switch (uiModeManager.getCurrentModeType()) { case Configuration.UI_MODE_TYPE_TELEVISION: return "tv"; @@ -78,16 +75,16 @@ public class AndroidInfoModule extends ReactContextBaseJavaModule implements Tur if (ReactBuildConfig.DEBUG) { constants.put("ServerHost", getServerHost()); } - constants.put("isTesting", "true".equals(System.getProperty(IS_TESTING)) - || isRunningScreenshotTest()); + constants.put( + "isTesting", "true".equals(System.getProperty(IS_TESTING)) || isRunningScreenshotTest()); constants.put("reactNativeVersion", ReactNativeVersion.VERSION); constants.put("uiMode", uiMode()); return constants; } @ReactMethod(isBlockingSynchronousMethod = true) - public String getAndroidID(){ - return Secure.getString(getReactApplicationContext().getContentResolver(),Secure.ANDROID_ID); + public String getAndroidID() { + return Secure.getString(getReactApplicationContext().getContentResolver(), Secure.ANDROID_ID); } @Override diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/timepicker/DismissableTimePickerDialog.java b/ReactAndroid/src/main/java/com/facebook/react/modules/timepicker/DismissableTimePickerDialog.java index 3a4d215b4b0..f1216965730 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/timepicker/DismissableTimePickerDialog.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/timepicker/DismissableTimePickerDialog.java @@ -1,30 +1,23 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.timepicker; -import android.app.TimePickerDialog; -import javax.annotation.Nullable; - import android.app.TimePickerDialog; import android.content.Context; import android.os.Build; +import javax.annotation.Nullable; /** - *

- * Certain versions of Android (Jellybean-KitKat) have a bug where when dismissed, the - * {@link TimePickerDialog} still calls the OnTimeSetListener. This class works around that issue - * by *not* calling super.onStop on KitKat on lower, as that would erroneously call the - * OnTimeSetListener when the dialog is dismissed, or call it twice when "OK" is pressed. - *

+ * Certain versions of Android (Jellybean-KitKat) have a bug where when dismissed, the {@link + * TimePickerDialog} still calls the OnTimeSetListener. This class works around that issue by *not* + * calling super.onStop on KitKat on lower, as that would erroneously call the OnTimeSetListener + * when the dialog is dismissed, or call it twice when "OK" is pressed. * - *

- * See: Issue 34833 - *

+ *

See: Issue 34833 */ public class DismissableTimePickerDialog extends TimePickerDialog { @@ -53,5 +46,4 @@ public class DismissableTimePickerDialog extends TimePickerDialog { super.onStop(); } } - } diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/timepicker/TimePickerDialogFragment.java b/ReactAndroid/src/main/java/com/facebook/react/modules/timepicker/TimePickerDialogFragment.java index c2f359b49fc..5e7e1b18823 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/timepicker/TimePickerDialogFragment.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/timepicker/TimePickerDialogFragment.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.timepicker; import android.app.Dialog; @@ -14,21 +13,17 @@ import android.content.DialogInterface; import android.content.DialogInterface.OnDismissListener; import android.os.Build; import android.os.Bundle; -import androidx.fragment.app.DialogFragment; import android.text.format.DateFormat; - +import androidx.fragment.app.DialogFragment; import java.util.Calendar; import java.util.Locale; - import javax.annotation.Nullable; @SuppressWarnings("ValidFragment") public class TimePickerDialogFragment extends DialogFragment { - @Nullable - private OnTimeSetListener mOnTimeSetListener; - @Nullable - private OnDismissListener mOnDismissListener; + @Nullable private OnTimeSetListener mOnTimeSetListener; + @Nullable private OnDismissListener mOnDismissListener; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { @@ -37,8 +32,7 @@ public class TimePickerDialogFragment extends DialogFragment { } /*package*/ static Dialog createDialog( - Bundle args, Context activityContext, @Nullable OnTimeSetListener onTimeSetListener - ) { + Bundle args, Context activityContext, @Nullable OnTimeSetListener onTimeSetListener) { final Calendar now = Calendar.getInstance(); int hour = now.get(Calendar.HOUR_OF_DAY); int minute = now.get(Calendar.MINUTE); @@ -46,53 +40,45 @@ public class TimePickerDialogFragment extends DialogFragment { TimePickerMode mode = TimePickerMode.DEFAULT; if (args != null && args.getString(TimePickerDialogModule.ARG_MODE, null) != null) { - mode = TimePickerMode.valueOf(args.getString(TimePickerDialogModule.ARG_MODE).toUpperCase(Locale.US)); + mode = + TimePickerMode.valueOf( + args.getString(TimePickerDialogModule.ARG_MODE).toUpperCase(Locale.US)); } if (args != null) { hour = args.getInt(TimePickerDialogModule.ARG_HOUR, now.get(Calendar.HOUR_OF_DAY)); minute = args.getInt(TimePickerDialogModule.ARG_MINUTE, now.get(Calendar.MINUTE)); - is24hour = args.getBoolean( - TimePickerDialogModule.ARG_IS24HOUR, - DateFormat.is24HourFormat(activityContext)); + is24hour = + args.getBoolean( + TimePickerDialogModule.ARG_IS24HOUR, DateFormat.is24HourFormat(activityContext)); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { if (mode == TimePickerMode.CLOCK) { return new DismissableTimePickerDialog( - activityContext, - activityContext.getResources().getIdentifier( - "ClockTimePickerDialog", - "style", - activityContext.getPackageName() - ), - onTimeSetListener, - hour, - minute, - is24hour - ); - } else if (mode == TimePickerMode.SPINNER) { - return new DismissableTimePickerDialog( - activityContext, - activityContext.getResources().getIdentifier( - "SpinnerTimePickerDialog", - "style", - activityContext.getPackageName() - ), - onTimeSetListener, - hour, - minute, - is24hour - ); - } - } - return new DismissableTimePickerDialog( activityContext, + activityContext + .getResources() + .getIdentifier("ClockTimePickerDialog", "style", activityContext.getPackageName()), onTimeSetListener, hour, minute, - is24hour - ); + is24hour); + } else if (mode == TimePickerMode.SPINNER) { + return new DismissableTimePickerDialog( + activityContext, + activityContext + .getResources() + .getIdentifier( + "SpinnerTimePickerDialog", "style", activityContext.getPackageName()), + onTimeSetListener, + hour, + minute, + is24hour); + } + } + return new DismissableTimePickerDialog( + activityContext, onTimeSetListener, hour, minute, is24hour); } @Override diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/timepicker/TimePickerDialogModule.java b/ReactAndroid/src/main/java/com/facebook/react/modules/timepicker/TimePickerDialogModule.java index 7b346881297..52ae9ddddbd 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/timepicker/TimePickerDialogModule.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/timepicker/TimePickerDialogModule.java @@ -1,21 +1,19 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.timepicker; import android.app.TimePickerDialog.OnTimeSetListener; import android.content.DialogInterface; import android.content.DialogInterface.OnDismissListener; import android.os.Bundle; +import android.widget.TimePicker; import androidx.fragment.app.DialogFragment; import androidx.fragment.app.FragmentActivity; import androidx.fragment.app.FragmentManager; -import android.widget.TimePicker; - import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.Promise; import com.facebook.react.bridge.ReactApplicationContext; @@ -26,7 +24,6 @@ import com.facebook.react.bridge.WritableMap; import com.facebook.react.bridge.WritableNativeMap; import com.facebook.react.common.annotations.VisibleForTesting; import com.facebook.react.module.annotations.ReactModule; - import javax.annotation.Nullable; /** @@ -36,8 +33,7 @@ import javax.annotation.Nullable; @ReactModule(name = TimePickerDialogModule.FRAGMENT_TAG) public class TimePickerDialogModule extends ReactContextBaseJavaModule { - @VisibleForTesting - public static final String FRAGMENT_TAG = "TimePickerAndroid"; + @VisibleForTesting public static final String FRAGMENT_TAG = "TimePickerAndroid"; private static final String ERROR_NO_ACTIVITY = "E_NO_ACTIVITY"; @@ -95,8 +91,7 @@ public class TimePickerDialogModule extends ReactContextBaseJavaModule { FragmentActivity activity = (FragmentActivity) getCurrentActivity(); if (activity == null) { promise.reject( - ERROR_NO_ACTIVITY, - "Tried to open a TimePicker dialog while not attached to an Activity"); + ERROR_NO_ACTIVITY, "Tried to open a TimePicker dialog while not attached to an Activity"); return; } // We want to support both android.app.Activity and the pre-Honeycomb FragmentActivity diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/timepicker/TimePickerMode.java b/ReactAndroid/src/main/java/com/facebook/react/modules/timepicker/TimePickerMode.java index 2b8243ef8ab..28d36d62efe 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/timepicker/TimePickerMode.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/timepicker/TimePickerMode.java @@ -1,13 +1,11 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.timepicker; - public enum TimePickerMode { CLOCK, SPINNER, diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/toast/ToastModule.java b/ReactAndroid/src/main/java/com/facebook/react/modules/toast/ToastModule.java index 057c5771884..db1f560a65a 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/toast/ToastModule.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/toast/ToastModule.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.toast; import android.view.Gravity; @@ -18,9 +17,7 @@ import com.facebook.react.common.MapBuilder; import com.facebook.react.module.annotations.ReactModule; import java.util.Map; -/** - * {@link NativeModule} that allows JS to show an Android Toast. - */ +/** {@link NativeModule} that allows JS to show an Android Toast. */ @ReactModule(name = ToastModule.NAME) public class ToastModule extends ReactContextBaseJavaModule { @@ -54,24 +51,26 @@ public class ToastModule extends ReactContextBaseJavaModule { @ReactMethod public void show(final String message, final int duration) { - UiThreadUtil.runOnUiThread(new Runnable() { - @Override - public void run() { - Toast.makeText(getReactApplicationContext(), message, duration).show(); - } - }); + UiThreadUtil.runOnUiThread( + new Runnable() { + @Override + public void run() { + Toast.makeText(getReactApplicationContext(), message, duration).show(); + } + }); } @ReactMethod public void showWithGravity(final String message, final int duration, final int gravity) { - UiThreadUtil.runOnUiThread(new Runnable() { - @Override - public void run() { - Toast toast = Toast.makeText(getReactApplicationContext(), message, duration); - toast.setGravity(gravity, 0, 0); - toast.show(); - } - }); + UiThreadUtil.runOnUiThread( + new Runnable() { + @Override + public void run() { + Toast toast = Toast.makeText(getReactApplicationContext(), message, duration); + toast.setGravity(gravity, 0, 0); + toast.show(); + } + }); } @ReactMethod diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/vibration/VibrationModule.java b/ReactAndroid/src/main/java/com/facebook/react/modules/vibration/VibrationModule.java index 161a7cc19cc..d0d79994a54 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/vibration/VibrationModule.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/vibration/VibrationModule.java @@ -1,16 +1,14 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.vibration; import android.annotation.SuppressLint; import android.content.Context; import android.os.Vibrator; - import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; @@ -47,7 +45,7 @@ public class VibrationModule extends ReactContextBaseJavaModule { long[] patternLong = new long[pattern.size()]; for (int i = 0; i < pattern.size(); i++) { patternLong[i] = pattern.getInt(i); - } + } v.vibrate(patternLong, repeat); } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/websocket/WebSocketModule.java b/ReactAndroid/src/main/java/com/facebook/react/modules/websocket/WebSocketModule.java index 7c776cadef6..ed263573069 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/websocket/WebSocketModule.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/websocket/WebSocketModule.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.websocket; import com.facebook.common.logging.FLog; @@ -40,7 +39,8 @@ import okio.ByteString; @ReactModule(name = WebSocketModule.NAME, hasConstants = false) public final class WebSocketModule extends ReactContextBaseJavaModule { - public static final String NAME="WebSocketModule"; + public static final String NAME = "WebSocketModule"; + public interface ContentHandler { void onMessage(String text, WritableMap params); @@ -61,8 +61,8 @@ public final class WebSocketModule extends ReactContextBaseJavaModule { private void sendEvent(String eventName, WritableMap params) { mReactContext - .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) - .emit(eventName, params); + .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) + .emit(eventName, params); } @Override @@ -80,15 +80,16 @@ public final class WebSocketModule extends ReactContextBaseJavaModule { @ReactMethod public void connect( - final String url, - @Nullable final ReadableArray protocols, - @Nullable final ReadableMap options, - final int id) { - OkHttpClient client = new OkHttpClient.Builder() - .connectTimeout(10, TimeUnit.SECONDS) - .writeTimeout(10, TimeUnit.SECONDS) - .readTimeout(0, TimeUnit.MINUTES) // Disable timeouts for read - .build(); + final String url, + @Nullable final ReadableArray protocols, + @Nullable final ReadableMap options, + final int id) { + OkHttpClient client = + new OkHttpClient.Builder() + .connectTimeout(10, TimeUnit.SECONDS) + .writeTimeout(10, TimeUnit.SECONDS) + .readTimeout(0, TimeUnit.MINUTES) // Disable timeouts for read + .build(); Request.Builder builder = new Request.Builder().tag(id).url(url); @@ -97,7 +98,9 @@ public final class WebSocketModule extends ReactContextBaseJavaModule { builder.addHeader("Cookie", cookie); } - if (options != null && options.hasKey("headers") && options.getType("headers").equals(ReadableType.Map)) { + if (options != null + && options.hasKey("headers") + && options.getType("headers").equals(ReadableType.Map)) { ReadableMap headers = options.getMap("headers"); ReadableMapKeySetIterator iterator = headers.keySetIterator(); @@ -111,9 +114,7 @@ public final class WebSocketModule extends ReactContextBaseJavaModule { if (ReadableType.String.equals(headers.getType(key))) { builder.addHeader(key, headers.getString(key)); } else { - FLog.w( - ReactConstants.TAG, - "Ignoring: requested " + key + ", value not a string"); + FLog.w(ReactConstants.TAG, "Ignoring: requested " + key + ", value not a string"); } } } else { @@ -218,10 +219,7 @@ public final class WebSocketModule extends ReactContextBaseJavaModule { mWebSocketConnections.remove(id); mContentHandlers.remove(id); } catch (Exception e) { - FLog.e( - ReactConstants.TAG, - "Could not close WebSocket connection for id " + id, - e); + FLog.e(ReactConstants.TAG, "Could not close WebSocket connection for id " + id, e); } } @@ -359,11 +357,8 @@ public final class WebSocketModule extends ReactContextBaseJavaModule { } if (requestURI.getPort() != -1) { - defaultOrigin = String.format( - "%s://%s:%s", - scheme, - requestURI.getHost(), - requestURI.getPort()); + defaultOrigin = + String.format("%s://%s:%s", scheme, requestURI.getHost(), requestURI.getPort()); } else { defaultOrigin = String.format("%s://%s", scheme, requestURI.getHost()); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/packagerconnection/FileIoHandler.java b/ReactAndroid/src/main/java/com/facebook/react/packagerconnection/FileIoHandler.java index 44c910bee5c..4f7b6defa06 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/packagerconnection/FileIoHandler.java +++ b/ReactAndroid/src/main/java/com/facebook/react/packagerconnection/FileIoHandler.java @@ -1,27 +1,22 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.packagerconnection; -import javax.annotation.Nullable; - +import android.os.Handler; +import android.os.Looper; +import android.util.Base64; +import com.facebook.common.logging.FLog; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; - -import android.os.Handler; -import android.os.Looper; -import android.util.Base64; - -import com.facebook.common.logging.FLog; - +import javax.annotation.Nullable; import org.json.JSONObject; public class FileIoHandler implements Runnable { @@ -67,88 +62,92 @@ public class FileIoHandler implements Runnable { mHandler = new Handler(Looper.getMainLooper()); mOpenFiles = new HashMap<>(); mRequestHandlers = new HashMap<>(); - mRequestHandlers.put("fopen", new RequestOnlyHandler() { - @Override - public void onRequest( - @Nullable Object params, Responder responder) { - synchronized (mOpenFiles) { - try { - JSONObject paramsObj = (JSONObject)params; - if (paramsObj == null) { - throw new Exception("params must be an object { mode: string, filename: string }"); - } - String mode = paramsObj.optString("mode"); - if (mode == null) { - throw new Exception("missing params.mode"); - } - String filename = paramsObj.optString("filename"); - if (filename == null) { - throw new Exception("missing params.filename"); - } - if (!mode.equals("r")) { - throw new IllegalArgumentException("unsupported mode: " + mode); - } + mRequestHandlers.put( + "fopen", + new RequestOnlyHandler() { + @Override + public void onRequest(@Nullable Object params, Responder responder) { + synchronized (mOpenFiles) { + try { + JSONObject paramsObj = (JSONObject) params; + if (paramsObj == null) { + throw new Exception( + "params must be an object { mode: string, filename: string }"); + } + String mode = paramsObj.optString("mode"); + if (mode == null) { + throw new Exception("missing params.mode"); + } + String filename = paramsObj.optString("filename"); + if (filename == null) { + throw new Exception("missing params.filename"); + } + if (!mode.equals("r")) { + throw new IllegalArgumentException("unsupported mode: " + mode); + } - responder.respond(addOpenFile(filename)); - } catch (Exception e) { - responder.error(e.toString()); + responder.respond(addOpenFile(filename)); + } catch (Exception e) { + responder.error(e.toString()); + } + } } - } - } - }); - mRequestHandlers.put("fclose", new RequestOnlyHandler() { - @Override - public void onRequest( - @Nullable Object params, Responder responder) { - synchronized (mOpenFiles) { - try { - if (!(params instanceof Number)) { - throw new Exception("params must be a file handle"); - } - TtlFileInputStream stream = mOpenFiles.get((int)params); - if (stream == null) { - throw new Exception("invalid file handle, it might have timed out"); - } + }); + mRequestHandlers.put( + "fclose", + new RequestOnlyHandler() { + @Override + public void onRequest(@Nullable Object params, Responder responder) { + synchronized (mOpenFiles) { + try { + if (!(params instanceof Number)) { + throw new Exception("params must be a file handle"); + } + TtlFileInputStream stream = mOpenFiles.get((int) params); + if (stream == null) { + throw new Exception("invalid file handle, it might have timed out"); + } - mOpenFiles.remove((int)params); - stream.close(); - responder.respond(""); - } catch (Exception e) { - responder.error(e.toString()); + mOpenFiles.remove((int) params); + stream.close(); + responder.respond(""); + } catch (Exception e) { + responder.error(e.toString()); + } + } } - } - } - }); - mRequestHandlers.put("fread", new RequestOnlyHandler() { - @Override - public void onRequest( - @Nullable Object params, Responder responder) { - synchronized (mOpenFiles) { - try { - JSONObject paramsObj = (JSONObject)params; - if (paramsObj == null) { - throw new Exception("params must be an object { file: handle, size: number }"); - } - int file = paramsObj.optInt("file"); - if (file == 0) { - throw new Exception("invalid or missing file handle"); - } - int size = paramsObj.optInt("size"); - if (size == 0) { - throw new Exception("invalid or missing read size"); - } - TtlFileInputStream stream = mOpenFiles.get(file); - if (stream == null) { - throw new Exception("invalid file handle, it might have timed out"); - } + }); + mRequestHandlers.put( + "fread", + new RequestOnlyHandler() { + @Override + public void onRequest(@Nullable Object params, Responder responder) { + synchronized (mOpenFiles) { + try { + JSONObject paramsObj = (JSONObject) params; + if (paramsObj == null) { + throw new Exception("params must be an object { file: handle, size: number }"); + } + int file = paramsObj.optInt("file"); + if (file == 0) { + throw new Exception("invalid or missing file handle"); + } + int size = paramsObj.optInt("size"); + if (size == 0) { + throw new Exception("invalid or missing read size"); + } + TtlFileInputStream stream = mOpenFiles.get(file); + if (stream == null) { + throw new Exception("invalid file handle, it might have timed out"); + } - responder.respond(stream.read(size)); - } catch (Exception e) { - responder.error(e.toString()); + responder.respond(stream.read(size)); + } catch (Exception e) { + responder.error(e.toString()); + } + } } - } - } - }); + }); } public Map handlers() { @@ -176,9 +175,7 @@ public class FileIoHandler implements Runnable { try { stream.close(); } catch (IOException e) { - FLog.e( - TAG, - "closing expired file failed: " + e.toString()); + FLog.e(TAG, "closing expired file failed: " + e.toString()); } } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/packagerconnection/JSPackagerClient.java b/ReactAndroid/src/main/java/com/facebook/react/packagerconnection/JSPackagerClient.java index d7ddfe667e6..7b2cd502885 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/packagerconnection/JSPackagerClient.java +++ b/ReactAndroid/src/main/java/com/facebook/react/packagerconnection/JSPackagerClient.java @@ -1,30 +1,24 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.packagerconnection; -import java.util.Map; -import javax.annotation.Nullable; - import android.net.Uri; - import com.facebook.common.logging.FLog; import com.facebook.react.modules.systeminfo.AndroidInfoHelpers; - +import java.util.Map; +import javax.annotation.Nullable; import okio.ByteString; - import org.json.JSONObject; -/** - * A client for packager that uses WebSocket connection. - */ -final public class JSPackagerClient implements ReconnectingWebSocket.MessageCallback { +/** A client for packager that uses WebSocket connection. */ +public final class JSPackagerClient implements ReconnectingWebSocket.MessageCallback { private static final String TAG = JSPackagerClient.class.getSimpleName(); - private static final String PACKAGER_CONNECTION_URL_FORMAT = "ws://%s/message?device=%s&app=%s&context=%s"; + private static final String PACKAGER_CONNECTION_URL_FORMAT = + "ws://%s/message?device=%s&app=%s&context=%s"; private static final int PROTOCOL_VERSION = 2; private class ResponderImpl implements Responder { @@ -62,23 +56,28 @@ final public class JSPackagerClient implements ReconnectingWebSocket.MessageCall private ReconnectingWebSocket mWebSocket; private Map mRequestHandlers; - public JSPackagerClient(String clientId, PackagerConnectionSettings settings, Map requestHandlers) { + public JSPackagerClient( + String clientId, + PackagerConnectionSettings settings, + Map requestHandlers) { this(clientId, settings, requestHandlers, null); } public JSPackagerClient( - String clientId, PackagerConnectionSettings settings, + String clientId, + PackagerConnectionSettings settings, Map requestHandlers, @Nullable ReconnectingWebSocket.ConnectionCallback connectionCallback) { super(); Uri.Builder builder = new Uri.Builder(); - builder.scheme("ws") - .encodedAuthority(settings.getDebugServerHost()) - .appendPath("message") - .appendQueryParameter("device", AndroidInfoHelpers.getFriendlyDeviceName()) - .appendQueryParameter("app", settings.getPackageName()) - .appendQueryParameter("clientid", clientId); + builder + .scheme("ws") + .encodedAuthority(settings.getDebugServerHost()) + .appendPath("message") + .appendQueryParameter("device", AndroidInfoHelpers.getFriendlyDeviceName()) + .appendQueryParameter("app", settings.getPackageName()) + .appendQueryParameter("clientid", clientId); String url = builder.build().toString(); mWebSocket = new ReconnectingWebSocket(url, this, connectionCallback); @@ -105,8 +104,7 @@ final public class JSPackagerClient implements ReconnectingWebSocket.MessageCall if (version != PROTOCOL_VERSION) { FLog.e( - TAG, - "Message with incompatible or missing version of protocol received: " + version); + TAG, "Message with incompatible or missing version of protocol received: " + version); return; } diff --git a/ReactAndroid/src/main/java/com/facebook/react/packagerconnection/NotificationOnlyHandler.java b/ReactAndroid/src/main/java/com/facebook/react/packagerconnection/NotificationOnlyHandler.java index c88f04ff183..0a89532116b 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/packagerconnection/NotificationOnlyHandler.java +++ b/ReactAndroid/src/main/java/com/facebook/react/packagerconnection/NotificationOnlyHandler.java @@ -1,22 +1,21 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.packagerconnection; -import javax.annotation.Nullable; - import com.facebook.common.logging.FLog; +import javax.annotation.Nullable; public abstract class NotificationOnlyHandler implements RequestHandler { private static final String TAG = JSPackagerClient.class.getSimpleName(); - final public void onRequest(@Nullable Object params, Responder responder) { + public final void onRequest(@Nullable Object params, Responder responder) { responder.error("Request is not supported"); FLog.e(TAG, "Request is not supported"); } - abstract public void onNotification(@Nullable Object params); + + public abstract void onNotification(@Nullable Object params); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/packagerconnection/PackagerConnectionSettings.java b/ReactAndroid/src/main/java/com/facebook/react/packagerconnection/PackagerConnectionSettings.java index a154553f0d0..c0e65e373d8 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/packagerconnection/PackagerConnectionSettings.java +++ b/ReactAndroid/src/main/java/com/facebook/react/packagerconnection/PackagerConnectionSettings.java @@ -1,22 +1,19 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.packagerconnection; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.text.TextUtils; - -import javax.annotation.Nullable; - import com.facebook.common.logging.FLog; import com.facebook.infer.annotation.Assertions; import com.facebook.react.modules.systeminfo.AndroidInfoHelpers; +import javax.annotation.Nullable; public class PackagerConnectionSettings { private static final String TAG = PackagerConnectionSettings.class.getSimpleName(); @@ -45,9 +42,11 @@ public class PackagerConnectionSettings { if (host.equals(AndroidInfoHelpers.DEVICE_LOCALHOST)) { FLog.w( - TAG, - "You seem to be running on device. Run '" + AndroidInfoHelpers.getAdbReverseTcpCommand(mAppContext) + "' " + - "to forward the debug server's port to the device."); + TAG, + "You seem to be running on device. Run '" + + AndroidInfoHelpers.getAdbReverseTcpCommand(mAppContext) + + "' " + + "to forward the debug server's port to the device."); } return host; diff --git a/ReactAndroid/src/main/java/com/facebook/react/packagerconnection/ReconnectingWebSocket.java b/ReactAndroid/src/main/java/com/facebook/react/packagerconnection/ReconnectingWebSocket.java index daef24c9f9b..79781ea0784 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/packagerconnection/ReconnectingWebSocket.java +++ b/ReactAndroid/src/main/java/com/facebook/react/packagerconnection/ReconnectingWebSocket.java @@ -1,23 +1,18 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.packagerconnection; -import javax.annotation.Nullable; - -import java.io.IOException; -import java.nio.channels.ClosedChannelException; -import java.util.concurrent.TimeUnit; - import android.os.Handler; import android.os.Looper; - import com.facebook.common.logging.FLog; - +import java.io.IOException; +import java.nio.channels.ClosedChannelException; +import java.util.concurrent.TimeUnit; +import javax.annotation.Nullable; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; @@ -25,21 +20,21 @@ import okhttp3.WebSocket; import okhttp3.WebSocketListener; import okio.ByteString; -/** - * A wrapper around WebSocketClient that reconnects automatically - */ -final public class ReconnectingWebSocket extends WebSocketListener { +/** A wrapper around WebSocketClient that reconnects automatically */ +public final class ReconnectingWebSocket extends WebSocketListener { private static final String TAG = ReconnectingWebSocket.class.getSimpleName(); private static final int RECONNECT_DELAY_MS = 2000; public interface MessageCallback { void onMessage(String text); + void onMessage(ByteString bytes); } public interface ConnectionCallback { void onConnected(); + void onDisconnected(); } @@ -52,9 +47,7 @@ final public class ReconnectingWebSocket extends WebSocketListener { private @Nullable ConnectionCallback mConnectionCallback; public ReconnectingWebSocket( - String url, - MessageCallback messageCallback, - ConnectionCallback connectionCallback) { + String url, MessageCallback messageCallback, ConnectionCallback connectionCallback) { super(); mUrl = url; mMessageCallback = messageCallback; @@ -67,11 +60,12 @@ final public class ReconnectingWebSocket extends WebSocketListener { throw new IllegalStateException("Can't connect closed client"); } - OkHttpClient httpClient = new OkHttpClient.Builder() - .connectTimeout(10, TimeUnit.SECONDS) - .writeTimeout(10, TimeUnit.SECONDS) - .readTimeout(0, TimeUnit.MINUTES) // Disable timeouts for read - .build(); + OkHttpClient httpClient = + new OkHttpClient.Builder() + .connectTimeout(10, TimeUnit.SECONDS) + .writeTimeout(10, TimeUnit.SECONDS) + .readTimeout(0, TimeUnit.MINUTES) // Disable timeouts for read + .build(); Request request = new Request.Builder().url(mUrl).build(); httpClient.newWebSocket(request, this); @@ -95,13 +89,13 @@ final public class ReconnectingWebSocket extends WebSocketListener { } mHandler.postDelayed( - new Runnable() { - @Override - public void run() { - delayedReconnect(); - } - }, - RECONNECT_DELAY_MS); + new Runnable() { + @Override + public void run() { + delayedReconnect(); + } + }, + RECONNECT_DELAY_MS); } public void closeQuietly() { diff --git a/ReactAndroid/src/main/java/com/facebook/react/packagerconnection/RequestHandler.java b/ReactAndroid/src/main/java/com/facebook/react/packagerconnection/RequestHandler.java index 52504ded260..bd6012f6b53 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/packagerconnection/RequestHandler.java +++ b/ReactAndroid/src/main/java/com/facebook/react/packagerconnection/RequestHandler.java @@ -1,15 +1,15 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.packagerconnection; import javax.annotation.Nullable; public interface RequestHandler { void onRequest(@Nullable Object params, Responder responder); + void onNotification(@Nullable Object params); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/packagerconnection/RequestOnlyHandler.java b/ReactAndroid/src/main/java/com/facebook/react/packagerconnection/RequestOnlyHandler.java index 05520d54156..7e7ef505fe3 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/packagerconnection/RequestOnlyHandler.java +++ b/ReactAndroid/src/main/java/com/facebook/react/packagerconnection/RequestOnlyHandler.java @@ -1,21 +1,20 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.packagerconnection; -import javax.annotation.Nullable; - import com.facebook.common.logging.FLog; +import javax.annotation.Nullable; public abstract class RequestOnlyHandler implements RequestHandler { private static final String TAG = JSPackagerClient.class.getSimpleName(); - abstract public void onRequest(@Nullable Object params, Responder responder); - final public void onNotification(@Nullable Object params) { + public abstract void onRequest(@Nullable Object params, Responder responder); + + public final void onNotification(@Nullable Object params) { FLog.e(TAG, "Notification is not supported"); } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/packagerconnection/Responder.java b/ReactAndroid/src/main/java/com/facebook/react/packagerconnection/Responder.java index 870508c2ad5..50c74dd65d0 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/packagerconnection/Responder.java +++ b/ReactAndroid/src/main/java/com/facebook/react/packagerconnection/Responder.java @@ -1,13 +1,13 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.packagerconnection; public interface Responder { void respond(Object result); + void error(Object error); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/shell/MainPackageConfig.java b/ReactAndroid/src/main/java/com/facebook/react/shell/MainPackageConfig.java index 62c20cfc433..b688e51c71d 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/shell/MainPackageConfig.java +++ b/ReactAndroid/src/main/java/com/facebook/react/shell/MainPackageConfig.java @@ -1,17 +1,14 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.shell; import com.facebook.imagepipeline.core.ImagePipelineConfig; -/** - * Configuration for {@link MainReactPackage} - */ +/** Configuration for {@link MainReactPackage} */ public class MainPackageConfig { private ImagePipelineConfig mFrescoConfig; diff --git a/ReactAndroid/src/main/java/com/facebook/react/shell/MainReactPackage.java b/ReactAndroid/src/main/java/com/facebook/react/shell/MainReactPackage.java index bb0d8ee52e1..00761508e39 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/shell/MainReactPackage.java +++ b/ReactAndroid/src/main/java/com/facebook/react/shell/MainReactPackage.java @@ -1,18 +1,18 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.shell; -import com.facebook.react.LazyReactPackage; +import com.facebook.react.TurboReactPackage; import com.facebook.react.animated.NativeAnimatedModule; -import com.facebook.react.bridge.ModuleSpec; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; +import com.facebook.react.module.annotations.ReactModule; import com.facebook.react.module.annotations.ReactModuleList; +import com.facebook.react.module.model.ReactModuleInfo; import com.facebook.react.module.model.ReactModuleInfoProvider; import com.facebook.react.modules.accessibilityinfo.AccessibilityInfoModule; import com.facebook.react.modules.appstate.AppStateModule; @@ -61,56 +61,46 @@ import com.facebook.react.views.textinput.ReactTextInputManager; import com.facebook.react.views.view.ReactViewManager; import com.facebook.react.views.viewpager.ReactViewPagerManager; import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import javax.annotation.Nullable; -import javax.inject.Provider; -import com.facebook.react.TurboReactPackage; -import com.facebook.react.ViewManagerOnDemandReactPackage; -import java.util.Map; -import com.facebook.react.module.model.ReactModuleInfo; -import com.facebook.react.module.annotations.ReactModule; import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.annotation.Nullable; -/** - * Package defining basic modules and view managers. - */ -@ReactModuleList(nativeModules = { - AccessibilityInfoModule.class, - AppStateModule.class, - BlobModule.class, - FileReaderModule.class, - AsyncStorageModule.class, - CameraRollManager.class, - ClipboardModule.class, - DatePickerDialogModule.class, - DialogModule.class, - FrescoModule.class, - I18nManagerModule.class, - ImageEditingManager.class, - ImageLoaderModule.class, - ImageStoreManager.class, - IntentModule.class, - NativeAnimatedModule.class, - NetworkingModule.class, - PermissionsModule.class, - ShareModule.class, - StatusBarModule.class, - TimePickerDialogModule.class, - ToastModule.class, - VibrationModule.class, - WebSocketModule.class, -}) +/** Package defining basic modules and view managers. */ +@ReactModuleList( + nativeModules = { + AccessibilityInfoModule.class, + AppStateModule.class, + BlobModule.class, + FileReaderModule.class, + AsyncStorageModule.class, + CameraRollManager.class, + ClipboardModule.class, + DatePickerDialogModule.class, + DialogModule.class, + FrescoModule.class, + I18nManagerModule.class, + ImageEditingManager.class, + ImageLoaderModule.class, + ImageStoreManager.class, + IntentModule.class, + NativeAnimatedModule.class, + NetworkingModule.class, + PermissionsModule.class, + ShareModule.class, + StatusBarModule.class, + TimePickerDialogModule.class, + ToastModule.class, + VibrationModule.class, + WebSocketModule.class, + }) public class MainReactPackage extends TurboReactPackage { private MainPackageConfig mConfig; - public MainReactPackage() { - } + public MainReactPackage() {} - /** - * Create a new package with configuration - */ + /** Create a new package with configuration */ public MainReactPackage(MainPackageConfig config) { mConfig = config; } @@ -137,8 +127,7 @@ public class MainReactPackage extends TurboReactPackage { case DialogModule.NAME: return new DialogModule(context); case FrescoModule.NAME: - return new FrescoModule( - context, true, mConfig != null ? mConfig.getFrescoConfig() : null); + return new FrescoModule(context, true, mConfig != null ? mConfig.getFrescoConfig() : null); case I18nManagerModule.NAME: return new I18nManagerModule(context); case ImageEditingManager.NAME: diff --git a/ReactAndroid/src/main/java/com/facebook/react/surface/ReactStage.java b/ReactAndroid/src/main/java/com/facebook/react/surface/ReactStage.java index 637aa8c87dd..8e58e018b3d 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/surface/ReactStage.java +++ b/ReactAndroid/src/main/java/com/facebook/react/surface/ReactStage.java @@ -5,9 +5,7 @@ import static java.lang.annotation.RetentionPolicy.SOURCE; import androidx.annotation.IntDef; import java.lang.annotation.Retention; -/** - * The stage of the Surface - */ +/** The stage of the Surface */ @Retention(SOURCE) @IntDef({ ReactStage.SURFACE_DID_INITIALIZE, diff --git a/ReactAndroid/src/main/java/com/facebook/react/touch/JSResponderHandler.java b/ReactAndroid/src/main/java/com/facebook/react/touch/JSResponderHandler.java index b6c79d4fa64..e051d46816f 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/touch/JSResponderHandler.java +++ b/ReactAndroid/src/main/java/com/facebook/react/touch/JSResponderHandler.java @@ -1,27 +1,24 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.touch; -import javax.annotation.Nullable; - import android.view.MotionEvent; import android.view.ViewGroup; import android.view.ViewParent; +import javax.annotation.Nullable; /** * This class coordinates JSResponder commands for {@link UIManagerModule}. It should be set as - * OnInterceptTouchEventListener for all newly created native views that implements - * {@link ReactInterceptingViewGroup} and thanks to the information whether JSResponder is set - * and to which view it will correctly coordinate the return values of - * {@link OnInterceptTouchEventListener} such that touch events will be dispatched to the view - * selected by JS gesture recognizer. + * OnInterceptTouchEventListener for all newly created native views that implements {@link + * ReactInterceptingViewGroup} and thanks to the information whether JSResponder is set and to which + * view it will correctly coordinate the return values of {@link OnInterceptTouchEventListener} such + * that touch events will be dispatched to the view selected by JS gesture recognizer. * - * Single {@link CatalystInstance} should reuse same instance of this class. + *

Single {@link CatalystInstance} should reuse same instance of this class. */ public class JSResponderHandler implements OnInterceptTouchEventListener { diff --git a/ReactAndroid/src/main/java/com/facebook/react/touch/OnInterceptTouchEventListener.java b/ReactAndroid/src/main/java/com/facebook/react/touch/OnInterceptTouchEventListener.java index 46ee341d86c..8aff9ef0d09 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/touch/OnInterceptTouchEventListener.java +++ b/ReactAndroid/src/main/java/com/facebook/react/touch/OnInterceptTouchEventListener.java @@ -1,28 +1,27 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.touch; import android.view.MotionEvent; import android.view.ViewGroup; /** - * Interface definition for a callback to be invoked when a onInterceptTouch is called on a - * {@link ViewGroup}. + * Interface definition for a callback to be invoked when a onInterceptTouch is called on a {@link + * ViewGroup}. */ public interface OnInterceptTouchEventListener { /** * Called when a onInterceptTouch is invoked on a view group + * * @param v The view group the onInterceptTouch has been called on * @param event The motion event being dispatched down the hierarchy. * @return Return true to steal motion event from the children and have the dispatched to this - * view, or return false to allow motion event to be delivered to children view + * view, or return false to allow motion event to be delivered to children view */ public boolean onInterceptTouchEvent(ViewGroup v, MotionEvent event); - } diff --git a/ReactAndroid/src/main/java/com/facebook/react/touch/ReactHitSlopView.java b/ReactAndroid/src/main/java/com/facebook/react/touch/ReactHitSlopView.java index 296768fbd68..30a7c1b3855 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/touch/ReactHitSlopView.java +++ b/ReactAndroid/src/main/java/com/facebook/react/touch/ReactHitSlopView.java @@ -1,26 +1,24 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.touch; import android.graphics.Rect; - import javax.annotation.Nullable; /** - * This interface should be implemented by all {@link View} subclasses that want to use the - * hitSlop prop to extend their touch areas. + * This interface should be implemented by all {@link View} subclasses that want to use the hitSlop + * prop to extend their touch areas. */ public interface ReactHitSlopView { /** * Called when determining the touch area of a view. + * * @return A {@link Rect} representing how far to extend the touch area in each direction. */ public @Nullable Rect getHitSlopRect(); - } diff --git a/ReactAndroid/src/main/java/com/facebook/react/touch/ReactInterceptingViewGroup.java b/ReactAndroid/src/main/java/com/facebook/react/touch/ReactInterceptingViewGroup.java index 58063f4dca9..e294d10d046 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/touch/ReactInterceptingViewGroup.java +++ b/ReactAndroid/src/main/java/com/facebook/react/touch/ReactInterceptingViewGroup.java @@ -1,13 +1,11 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.touch; - /** * This interface should be implemented by all {@link ViewGroup} subviews that can be instantiating * by {@link NativeViewHierarchyManager}. It is used to configure onInterceptTouch event listener @@ -18,15 +16,14 @@ public interface ReactInterceptingViewGroup { /** * A {@link ViewGroup} instance that implement this interface is responsible for storing the - * listener passed as an argument and then calling - * {@link OnInterceptTouchEventListener#onInterceptTouchEvent} from - * {@link ViewGroup#onInterceptTouchEvent} and returning the result. If some custom handling of - * this method apply for the view, it should be called after the listener returns and only in - * a case when it returns false. + * listener passed as an argument and then calling {@link + * OnInterceptTouchEventListener#onInterceptTouchEvent} from {@link + * ViewGroup#onInterceptTouchEvent} and returning the result. If some custom handling of this + * method apply for the view, it should be called after the listener returns and only in a case + * when it returns false. * - * @param listener A callback that {@link ViewGroup} should delegate calls for - * {@link ViewGroup#onInterceptTouchEvent} to + * @param listener A callback that {@link ViewGroup} should delegate calls for {@link + * ViewGroup#onInterceptTouchEvent} to */ public void setOnInterceptTouchEventListener(OnInterceptTouchEventListener listener); - } diff --git a/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/JSCallInvokerHolderImpl.java b/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/JSCallInvokerHolderImpl.java index e5f0ed58748..cf26f53cb1c 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/JSCallInvokerHolderImpl.java +++ b/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/JSCallInvokerHolderImpl.java @@ -1,21 +1,19 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.turbomodule.core; import com.facebook.jni.HybridData; -import com.facebook.soloader.SoLoader; import com.facebook.react.turbomodule.core.interfaces.JSCallInvokerHolder; +import com.facebook.soloader.SoLoader; /** - * JSCallInvoker is created at a different time/place (i.e: in CatalystInstance) - * than TurboModuleManager. Therefore, we need to wrap JSCallInvoker - * within a hybrid class so that we may pass it from CatalystInstance, through - * Java, to TurboMoudleManager::initHybrid. + * JSCallInvoker is created at a different time/place (i.e: in CatalystInstance) than + * TurboModuleManager. Therefore, we need to wrap JSCallInvoker within a hybrid class so that we may + * pass it from CatalystInstance, through Java, to TurboMoudleManager::initHybrid. */ public class JSCallInvokerHolderImpl implements JSCallInvokerHolder { static { diff --git a/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/ReactPackageTurboModuleManagerDelegate.java b/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/ReactPackageTurboModuleManagerDelegate.java index 19b7a8ccdfa..3ac9c2c2809 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/ReactPackageTurboModuleManagerDelegate.java +++ b/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/ReactPackageTurboModuleManagerDelegate.java @@ -12,21 +12,22 @@ import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.turbomodule.core.interfaces.TurboModule; import java.util.ArrayList; import java.util.HashMap; +import java.util.List; import java.util.Map; import javax.annotation.Nullable; -import java.util.List; public abstract class ReactPackageTurboModuleManagerDelegate extends TurboModuleManagerDelegate { private final List mPackages = new ArrayList<>(); private final Map mModules = new HashMap<>(); private final ReactApplicationContext mReactApplicationContext; - protected ReactPackageTurboModuleManagerDelegate(ReactApplicationContext reactApplicationContext, List packages) { + protected ReactPackageTurboModuleManagerDelegate( + ReactApplicationContext reactApplicationContext, List packages) { super(); mReactApplicationContext = reactApplicationContext; for (ReactPackage reactPackage : packages) { if (reactPackage instanceof TurboReactPackage) { - mPackages.add((TurboReactPackage)reactPackage); + mPackages.add((TurboReactPackage) reactPackage); } } } @@ -44,7 +45,6 @@ public abstract class ReactPackageTurboModuleManagerDelegate extends TurboModule return null; } - return module; } @@ -60,8 +60,7 @@ public abstract class ReactPackageTurboModuleManagerDelegate extends TurboModule return null; } - - return (CxxModuleWrapper)module; + return (CxxModuleWrapper) module; } private TurboModule resolveModule(String moduleName) { @@ -79,25 +78,23 @@ public abstract class ReactPackageTurboModuleManagerDelegate extends TurboModule } } catch (IllegalArgumentException ex) { /** - * TurboReactPackages can throw an IllegalArgumentException when a module - * isn't found. If this happens, it's safe to ignore the exception because - * a later TurboReactPackage could provide the module. + * TurboReactPackages can throw an IllegalArgumentException when a module isn't found. If + * this happens, it's safe to ignore the exception because a later TurboReactPackage could + * provide the module. */ } } if (resolvedModule instanceof TurboModule) { - mModules.put(moduleName, (TurboModule)resolvedModule); + mModules.put(moduleName, (TurboModule) resolvedModule); } else { /** - * 1. The list of TurboReactPackages doesn't change. - * 2. TurboReactPackage.getModule is deterministic. Therefore, any two - * invocations of TurboReactPackage.getModule will return the same result - * given that they're provided the same arguments. + * 1. The list of TurboReactPackages doesn't change. 2. TurboReactPackage.getModule is + * deterministic. Therefore, any two invocations of TurboReactPackage.getModule will return + * the same result given that they're provided the same arguments. * - * Hence, if module lookup fails once, we know it'll fail every time. - * Therefore, we can write null to the mModules Map and avoid doing this - * extra work. + *

Hence, if module lookup fails once, we know it'll fail every time. Therefore, we can + * write null to the mModules Map and avoid doing this extra work. */ mModules.put(moduleName, null); } @@ -105,7 +102,7 @@ public abstract class ReactPackageTurboModuleManagerDelegate extends TurboModule return mModules.get(moduleName); } - public static abstract class Builder { + public abstract static class Builder { private @Nullable List mPackages; private @Nullable ReactApplicationContext mContext; @@ -119,11 +116,16 @@ public abstract class ReactPackageTurboModuleManagerDelegate extends TurboModule return this; } - protected abstract ReactPackageTurboModuleManagerDelegate build(ReactApplicationContext context, List packages); + protected abstract ReactPackageTurboModuleManagerDelegate build( + ReactApplicationContext context, List packages); public ReactPackageTurboModuleManagerDelegate build() { - Assertions.assertNotNull(mContext, "The ReactApplicationContext must be provided to create ReactPackageTurboModuleManagerDelegate"); - Assertions.assertNotNull(mPackages, "A set of ReactPackages must be provided to create ReactPackageTurboModuleManagerDelegate"); + Assertions.assertNotNull( + mContext, + "The ReactApplicationContext must be provided to create ReactPackageTurboModuleManagerDelegate"); + Assertions.assertNotNull( + mPackages, + "A set of ReactPackages must be provided to create ReactPackageTurboModuleManagerDelegate"); return build(mContext, mPackages); } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/TurboModuleManager.java b/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/TurboModuleManager.java index b3bcbe47e9f..5a8b64cb89f 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/TurboModuleManager.java +++ b/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/TurboModuleManager.java @@ -1,20 +1,16 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.turbomodule.core; import com.facebook.jni.HybridData; import com.facebook.proguard.annotations.DoNotStrip; -import com.facebook.react.bridge.CatalystInstance; import com.facebook.react.bridge.JSIModule; import com.facebook.react.bridge.JavaScriptContextHolder; import com.facebook.react.bridge.NativeModule; -import com.facebook.react.bridge.ReactApplicationContext; -import com.facebook.react.bridge.queue.MessageQueueThread; import com.facebook.react.turbomodule.core.interfaces.JSCallInvokerHolder; import com.facebook.react.turbomodule.core.interfaces.TurboModule; import com.facebook.react.turbomodule.core.interfaces.TurboModuleRegistry; @@ -23,10 +19,10 @@ import java.util.*; import javax.annotation.Nullable; /** -* This is the main class and entry point for TurboModules. -* Note that this is a hybrid class, and has a C++ counterpart -* This class installs the JSI bindings. It also implements the method to get a Java module, that the C++ counterpart calls. -*/ + * This is the main class and entry point for TurboModules. Note that this is a hybrid class, and + * has a C++ counterpart This class installs the JSI bindings. It also implements the method to get + * a Java module, that the C++ counterpart calls. + */ public class TurboModuleManager implements JSIModule, TurboModuleRegistry { static { SoLoader.loadLibrary("turbomodulejsijni"); @@ -40,10 +36,15 @@ public class TurboModuleManager implements JSIModule, TurboModuleRegistry { @SuppressWarnings("unused") private final HybridData mHybridData; - public TurboModuleManager(JavaScriptContextHolder jsContext, TurboModuleManagerDelegate tmmDelegate, JSCallInvokerHolder instanceHolder) { - mHybridData = initHybrid(jsContext.get(), (JSCallInvokerHolderImpl) instanceHolder, tmmDelegate); + public TurboModuleManager( + JavaScriptContextHolder jsContext, + TurboModuleManagerDelegate tmmDelegate, + JSCallInvokerHolder instanceHolder) { + mHybridData = + initHybrid(jsContext.get(), (JSCallInvokerHolderImpl) instanceHolder, tmmDelegate); mTurbomoduleManagerDelegate = tmmDelegate; } + @DoNotStrip @Nullable protected TurboModule getJavaModule(String name) { @@ -55,7 +56,7 @@ public class TurboModuleManager implements JSIModule, TurboModuleRegistry { * TurboModuleManager is initialized after ReactApplicationContext has been setup. * Therefore, it's safe to call initialize on the TurboModule. */ - ((NativeModule)turboModule).initialize(); + ((NativeModule) turboModule).initialize(); mTurboModules.put(name, turboModule); } @@ -77,7 +78,8 @@ public class TurboModuleManager implements JSIModule, TurboModuleRegistry { return mTurboModules.containsKey(name); } - private native HybridData initHybrid(long jsContext, JSCallInvokerHolderImpl jsQueue, TurboModuleManagerDelegate tmmDelegate); + private native HybridData initHybrid( + long jsContext, JSCallInvokerHolderImpl jsQueue, TurboModuleManagerDelegate tmmDelegate); private native void installJSIBindings(); diff --git a/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/TurboModuleManagerDelegate.java b/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/TurboModuleManagerDelegate.java index fda66b65a36..a28710a2888 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/TurboModuleManagerDelegate.java +++ b/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/TurboModuleManagerDelegate.java @@ -1,15 +1,13 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.turbomodule.core; import com.facebook.jni.HybridData; import com.facebook.react.bridge.CxxModuleWrapper; -import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.turbomodule.core.interfaces.TurboModule; import com.facebook.soloader.SoLoader; import javax.annotation.Nullable; @@ -28,15 +26,15 @@ public abstract class TurboModuleManagerDelegate { } /** - * Create and return a TurboModule Java object with name `moduleName`. - * If `moduleName` isn't a TurboModule, return null. + * Create and return a TurboModule Java object with name `moduleName`. If `moduleName` isn't a + * TurboModule, return null. */ @Nullable public abstract TurboModule getModule(String moduleName); /** - * Create an return a CxxModuleWrapper NativeModule with name `moduleName`. - * If `moduleName` isn't a CxxModule, return null. + * Create an return a CxxModuleWrapper NativeModule with name `moduleName`. If `moduleName` isn't + * a CxxModule, return null. */ @Nullable public abstract CxxModuleWrapper getLegacyCxxModule(String moduleName); diff --git a/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/interfaces/JSCallInvokerHolder.java b/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/interfaces/JSCallInvokerHolder.java index beba6d77ac5..3f39ff60e75 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/interfaces/JSCallInvokerHolder.java +++ b/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/interfaces/JSCallInvokerHolder.java @@ -1,21 +1,17 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.turbomodule.core.interfaces; /** - * JSCallInvoker is created by CatalystInstance.cpp, but used by - * TurboModuleManager.cpp. Both C++ classes are instantiated at different - * times/places. Therefore, to pass the JSCallInvoker instance from - * CatalystInstance to TurboModuleManager, we make it take a trip through - * Java. + * JSCallInvoker is created by CatalystInstance.cpp, but used by TurboModuleManager.cpp. Both C++ + * classes are instantiated at different times/places. Therefore, to pass the JSCallInvoker instance + * from CatalystInstance to TurboModuleManager, we make it take a trip through Java. * - * This interface represents the opaque Java object that contains a pointer to - * and instance of JSCallInvoker. + *

This interface represents the opaque Java object that contains a pointer to and instance of + * JSCallInvoker. */ -public interface JSCallInvokerHolder { -} +public interface JSCallInvokerHolder {} diff --git a/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/interfaces/TurboModule.java b/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/interfaces/TurboModule.java index 180c45d964b..bb310f6eadb 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/interfaces/TurboModule.java +++ b/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/interfaces/TurboModule.java @@ -1,16 +1,16 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.turbomodule.core.interfaces; -/** - * All turbo modules should inherit from this interface - */ +/** All turbo modules should inherit from this interface */ public interface TurboModule { - /** When CatalystInstance is destroyed, this method will be called. All implementing TurboModules can perform cleanup here. */ + /** + * When CatalystInstance is destroyed, this method will be called. All implementing TurboModules + * can perform cleanup here. + */ void invalidate(); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/interfaces/TurboModuleRegistry.java b/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/interfaces/TurboModuleRegistry.java index 85794679bb4..4a4507e4d43 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/interfaces/TurboModuleRegistry.java +++ b/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/interfaces/TurboModuleRegistry.java @@ -1,35 +1,28 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.turbomodule.core.interfaces; import java.util.Collection; import javax.annotation.Nullable; -/** - * Interface to allow for creating and retrieving TurboModuels. - */ +/** Interface to allow for creating and retrieving TurboModuels. */ public interface TurboModuleRegistry { /** - * Return the TurboModule instance that has that name `moduleName`. - * If the `moduleName` TurboModule hasn't been instantiated, instantiate it. - * If no TurboModule is registered under `moduleName`, return null. + * Return the TurboModule instance that has that name `moduleName`. If the `moduleName` + * TurboModule hasn't been instantiated, instantiate it. If no TurboModule is registered under + * `moduleName`, return null. */ @Nullable TurboModule getModule(String moduleName); - /** - * Get all instantiated TurboModules. - */ + /** Get all instantiated TurboModules. */ Collection getModules(); - /** - * Has the TurboModule with name `moduleName` been instantiated? - */ + /** Has the TurboModule with name `moduleName` been instantiated? */ boolean hasModule(String moduleName); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/BaseViewManager.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/BaseViewManager.java index 5775bb5a8bd..4abdb9b29a9 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/BaseViewManager.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/BaseViewManager.java @@ -9,12 +9,7 @@ import android.graphics.Color; import android.text.TextUtils; import android.view.View; import android.view.ViewParent; - import androidx.core.view.ViewCompat; - -import java.util.ArrayList; -import java.util.HashMap; - import com.facebook.react.R; import com.facebook.react.bridge.Dynamic; import com.facebook.react.bridge.ReadableArray; @@ -22,14 +17,13 @@ import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.ReadableMapKeySetIterator; import com.facebook.react.bridge.ReadableType; import com.facebook.react.common.MapBuilder; -import com.facebook.react.uimanager.ReactAccessibilityDelegate; import com.facebook.react.uimanager.ReactAccessibilityDelegate.AccessibilityRole; import com.facebook.react.uimanager.annotations.ReactProp; import com.facebook.react.uimanager.util.ReactFindViewUtil; - -import javax.annotation.Nonnull; import java.util.ArrayList; +import java.util.HashMap; import java.util.Map; +import javax.annotation.Nonnull; import javax.annotation.Nullable; /** @@ -88,7 +82,7 @@ public abstract class BaseViewManager contentDescription = new ArrayList(); @@ -233,12 +230,21 @@ public abstract class BaseViewManagerThis source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; -import javax.annotation.Nullable; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.HashMap; -import java.util.Map; - import android.content.Context; import android.os.Build; import android.util.DisplayMetrics; import android.view.Display; import android.view.WindowManager; - import com.facebook.infer.annotation.Assertions; import com.facebook.react.bridge.WritableNativeMap; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; +import javax.annotation.Nullable; /** * Holds an instance of the current DisplayMetrics so we don't have to thread it through all the - * classes that need it. - * Note: windowDisplayMetrics are deprecated in favor of ScreenDisplayMetrics: window metrics - * are supposed to return the drawable area but there's no guarantee that they correspond to the - * actual size of the {@link ReactRootView}. Moreover, they are not consistent with what iOS - * returns. Screen metrics returns the metrics of the entire screen, is consistent with iOS and - * should be used instead. + * classes that need it. Note: windowDisplayMetrics are deprecated in favor of ScreenDisplayMetrics: + * window metrics are supposed to return the drawable area but there's no guarantee that they + * correspond to the actual size of the {@link ReactRootView}. Moreover, they are not consistent + * with what iOS returns. Screen metrics returns the metrics of the entire screen, is consistent + * with iOS and should be used instead. */ public class DisplayMetricsHolder { @@ -39,7 +34,7 @@ public class DisplayMetricsHolder { /** * @deprecated Use {@link #setScreenDisplayMetrics(DisplayMetrics)} instead. See comment above as - * to why this is not correct to use. + * to why this is not correct to use. */ public static void setWindowDisplayMetrics(DisplayMetrics displayMetrics) { sWindowDisplayMetrics = displayMetrics; @@ -59,24 +54,25 @@ public class DisplayMetricsHolder { DisplayMetrics screenDisplayMetrics = new DisplayMetrics(); screenDisplayMetrics.setTo(displayMetrics); WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); - Assertions.assertNotNull( - wm, - "WindowManager is null!"); + Assertions.assertNotNull(wm, "WindowManager is null!"); Display display = wm.getDefaultDisplay(); // Get the real display metrics if we are using API level 17 or higher. // The real metrics include system decor elements (e.g. soft menu bar). // - // See: http://developer.android.com/reference/android/view/Display.html#getRealMetrics(android.util.DisplayMetrics) + // See: + // http://developer.android.com/reference/android/view/Display.html#getRealMetrics(android.util.DisplayMetrics) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { display.getRealMetrics(screenDisplayMetrics); } else { - // For 14 <= API level <= 16, we need to invoke getRawHeight and getRawWidth to get the real dimensions. + // For 14 <= API level <= 16, we need to invoke getRawHeight and getRawWidth to get the real + // dimensions. // Since react-native only supports API level 16+ we don't have to worry about other cases. // // Reflection exceptions are rethrown at runtime. // - // See: http://stackoverflow.com/questions/14341041/how-to-get-real-screen-height-and-width/23861333#23861333 + // See: + // http://stackoverflow.com/questions/14341041/how-to-get-real-screen-height-and-width/23861333#23861333 try { Method mGetRawH = Display.class.getMethod("getRawHeight"); Method mGetRawW = Display.class.getMethod("getRawWidth"); @@ -90,8 +86,8 @@ public class DisplayMetricsHolder { } /** - * @deprecated Use {@link #getScreenDisplayMetrics()} instead. See comment above as to why this - * is not correct to use. + * @deprecated Use {@link #getScreenDisplayMetrics()} instead. See comment above as to why this is + * not correct to use. */ @Deprecated public static DisplayMetrics getWindowDisplayMetrics() { @@ -121,12 +117,15 @@ public class DisplayMetricsHolder { sWindowDisplayMetrics != null || sScreenDisplayMetrics != null, "DisplayMetricsHolder must be initialized with initDisplayMetricsIfNotInitialized or initDisplayMetrics"); final WritableNativeMap result = new WritableNativeMap(); - result.putMap("windowPhysicalPixels", getPhysicalPixelsNativeMap(sWindowDisplayMetrics, fontScale)); - result.putMap("screenPhysicalPixels", getPhysicalPixelsNativeMap(sScreenDisplayMetrics, fontScale)); + result.putMap( + "windowPhysicalPixels", getPhysicalPixelsNativeMap(sWindowDisplayMetrics, fontScale)); + result.putMap( + "screenPhysicalPixels", getPhysicalPixelsNativeMap(sScreenDisplayMetrics, fontScale)); return result; } - private static Map getPhysicalPixelsMap(DisplayMetrics displayMetrics, double fontScale) { + private static Map getPhysicalPixelsMap( + DisplayMetrics displayMetrics, double fontScale) { final Map result = new HashMap<>(); result.put("width", displayMetrics.widthPixels); result.put("height", displayMetrics.heightPixels); @@ -136,7 +135,8 @@ public class DisplayMetricsHolder { return result; } - private static WritableNativeMap getPhysicalPixelsNativeMap(DisplayMetrics displayMetrics, double fontScale) { + private static WritableNativeMap getPhysicalPixelsNativeMap( + DisplayMetrics displayMetrics, double fontScale) { final WritableNativeMap result = new WritableNativeMap(); result.putInt("width", displayMetrics.widthPixels); result.putInt("height", displayMetrics.heightPixels); diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/FloatUtil.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/FloatUtil.java index c1464e842d6..aa217cc8c77 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/FloatUtil.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/FloatUtil.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; public class FloatUtil { diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/GuardedFrameCallback.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/GuardedFrameCallback.java index cf39087ecba..701122139f3 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/GuardedFrameCallback.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/GuardedFrameCallback.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; import com.facebook.react.bridge.ReactContext; @@ -33,8 +32,8 @@ public abstract class GuardedFrameCallback extends ChoreographerCompat.FrameCall } /** - * Like the standard doFrame but RuntimeExceptions will be caught and passed to - * {@link com.facebook.react.bridge.ReactContext#handleException(RuntimeException)}. + * Like the standard doFrame but RuntimeExceptions will be caught and passed to {@link + * com.facebook.react.bridge.ReactContext#handleException(RuntimeException)}. */ protected abstract void doFrameGuarded(long frameTimeNanos); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/IViewManagerWithChildren.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/IViewManagerWithChildren.java index c07021107a0..6cfbaa40740 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/IViewManagerWithChildren.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/IViewManagerWithChildren.java @@ -1,22 +1,19 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; public interface IViewManagerWithChildren { /** - * Returns whether this View type needs to handle laying out its own children instead of - * deferring to the standard css-layout algorithm. - * Returns true for the layout to *not* be automatically invoked. Instead onLayout will be - * invoked as normal and it is the View instance's responsibility to properly call layout on its - * children. - * Returns false for the default behavior of automatically laying out children without going - * through the ViewGroup's onLayout method. In that case, onLayout for this View type must *not* - * call layout on its children. + * Returns whether this View type needs to handle laying out its own children instead of deferring + * to the standard css-layout algorithm. Returns true for the layout to *not* be automatically + * invoked. Instead onLayout will be invoked as normal and it is the View instance's + * responsibility to properly call layout on its children. Returns false for the default behavior + * of automatically laying out children without going through the ViewGroup's onLayout method. In + * that case, onLayout for this View type must *not* call layout on its children. */ public boolean needsCustomLayoutForChildren(); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/IllegalViewOperationException.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/IllegalViewOperationException.java index 45ea0700ea3..4d5bc8b7ffa 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/IllegalViewOperationException.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/IllegalViewOperationException.java @@ -1,19 +1,16 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; -import androidx.annotation.Nullable; import android.view.View; +import androidx.annotation.Nullable; import com.facebook.react.bridge.JSApplicationCausedNativeException; -/** - * An exception caused by JS requesting the UI manager to perform an illegal view operation. - */ +/** An exception caused by JS requesting the UI manager to perform an illegal view operation. */ public class IllegalViewOperationException extends JSApplicationCausedNativeException { @Nullable private View mView; diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/JSTouchDispatcher.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/JSTouchDispatcher.java index 46ea5edfa9d..b7dddfd5254 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/JSTouchDispatcher.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/JSTouchDispatcher.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; import android.view.MotionEvent; @@ -18,9 +17,9 @@ import com.facebook.react.uimanager.events.TouchEventCoalescingKeyHelper; import com.facebook.react.uimanager.events.TouchEventType; /** - * JSTouchDispatcher handles dispatching touches to JS from RootViews. If you implement RootView - * you need to call handleTouchEvent from onTouchEvent and onInterceptTouchEvent. It will correctly - * find the right view to handle the touch and also dispatch the appropriate event to JS + * JSTouchDispatcher handles dispatching touches to JS from RootViews. If you implement RootView you + * need to call handleTouchEvent from onTouchEvent and onInterceptTouchEvent. It will correctly find + * the right view to handle the touch and also dispatch the appropriate event to JS */ public class JSTouchDispatcher { @@ -30,13 +29,14 @@ public class JSTouchDispatcher { private long mGestureStartTime = TouchEvent.UNSET; private final ViewGroup mRootViewGroup; private final TouchEventCoalescingKeyHelper mTouchEventCoalescingKeyHelper = - new TouchEventCoalescingKeyHelper(); + new TouchEventCoalescingKeyHelper(); public JSTouchDispatcher(ViewGroup viewGroup) { mRootViewGroup = viewGroup; } - public void onChildStartedNativeGesture(MotionEvent androidEvent, EventDispatcher eventDispatcher) { + public void onChildStartedNativeGesture( + MotionEvent androidEvent, EventDispatcher eventDispatcher) { if (mChildIsHandlingNativeGesture) { // This means we previously had another child start handling this native gesture and now a // different native parent of that child has decided to intercept the touch stream and handle @@ -51,19 +51,17 @@ public class JSTouchDispatcher { /** * Main catalyst view is responsible for collecting and sending touch events to JS. This method - * reacts for an incoming android native touch events ({@link MotionEvent}) and calls into - * {@link com.facebook.react.uimanager.events.EventDispatcher} when appropriate. - * It uses {@link com.facebook.react.uimanager.TouchTargetHelper#findTouchTargetView} - * helper method for figuring out a react view ID in the case of ACTION_DOWN - * event (when the gesture starts). + * reacts for an incoming android native touch events ({@link MotionEvent}) and calls into {@link + * com.facebook.react.uimanager.events.EventDispatcher} when appropriate. It uses {@link + * com.facebook.react.uimanager.TouchTargetHelper#findTouchTargetView} helper method for figuring + * out a react view ID in the case of ACTION_DOWN event (when the gesture starts). */ public void handleTouchEvent(MotionEvent ev, EventDispatcher eventDispatcher) { int action = ev.getAction() & MotionEvent.ACTION_MASK; if (action == MotionEvent.ACTION_DOWN) { if (mTargetTag != -1) { FLog.e( - ReactConstants.TAG, - "Got DOWN touch before receiving UP or CANCEL from last gesture"); + ReactConstants.TAG, "Got DOWN touch before receiving UP or CANCEL from last gesture"); } // First event for this gesture. We expect tag to be set to -1, and we use helper method @@ -73,14 +71,14 @@ public class JSTouchDispatcher { mGestureStartTime = ev.getEventTime(); mTargetTag = findTargetTagAndSetCoordinates(ev); eventDispatcher.dispatchEvent( - TouchEvent.obtain( - mTargetTag, - TouchEventType.START, - ev, - mGestureStartTime, - mTargetCoordinates[0], - mTargetCoordinates[1], - mTouchEventCoalescingKeyHelper)); + TouchEvent.obtain( + mTargetTag, + TouchEventType.START, + ev, + mGestureStartTime, + mTargetCoordinates[0], + mTargetCoordinates[1], + mTouchEventCoalescingKeyHelper)); } else if (mChildIsHandlingNativeGesture) { // If the touch was intercepted by a child, we've already sent a cancel event to JS for this // gesture, so we shouldn't send any more touches related to it. @@ -89,73 +87,72 @@ public class JSTouchDispatcher { // All the subsequent action types are expected to be called after ACTION_DOWN thus target // is supposed to be set for them. FLog.e( - ReactConstants.TAG, - "Unexpected state: received touch event but didn't get starting ACTION_DOWN for this " + - "gesture before"); + ReactConstants.TAG, + "Unexpected state: received touch event but didn't get starting ACTION_DOWN for this " + + "gesture before"); } else if (action == MotionEvent.ACTION_UP) { // End of the gesture. We reset target tag to -1 and expect no further event associated with // this gesture. findTargetTagAndSetCoordinates(ev); eventDispatcher.dispatchEvent( - TouchEvent.obtain( - mTargetTag, - TouchEventType.END, - ev, - mGestureStartTime, - mTargetCoordinates[0], - mTargetCoordinates[1], - mTouchEventCoalescingKeyHelper)); + TouchEvent.obtain( + mTargetTag, + TouchEventType.END, + ev, + mGestureStartTime, + mTargetCoordinates[0], + mTargetCoordinates[1], + mTouchEventCoalescingKeyHelper)); mTargetTag = -1; mGestureStartTime = TouchEvent.UNSET; } else if (action == MotionEvent.ACTION_MOVE) { // Update pointer position for current gesture findTargetTagAndSetCoordinates(ev); eventDispatcher.dispatchEvent( - TouchEvent.obtain( - mTargetTag, - TouchEventType.MOVE, - ev, - mGestureStartTime, - mTargetCoordinates[0], - mTargetCoordinates[1], - mTouchEventCoalescingKeyHelper)); + TouchEvent.obtain( + mTargetTag, + TouchEventType.MOVE, + ev, + mGestureStartTime, + mTargetCoordinates[0], + mTargetCoordinates[1], + mTouchEventCoalescingKeyHelper)); } else if (action == MotionEvent.ACTION_POINTER_DOWN) { // New pointer goes down, this can only happen after ACTION_DOWN is sent for the first pointer eventDispatcher.dispatchEvent( - TouchEvent.obtain( - mTargetTag, - TouchEventType.START, - ev, - mGestureStartTime, - mTargetCoordinates[0], - mTargetCoordinates[1], - mTouchEventCoalescingKeyHelper)); + TouchEvent.obtain( + mTargetTag, + TouchEventType.START, + ev, + mGestureStartTime, + mTargetCoordinates[0], + mTargetCoordinates[1], + mTouchEventCoalescingKeyHelper)); } else if (action == MotionEvent.ACTION_POINTER_UP) { // Exactly onw of the pointers goes up eventDispatcher.dispatchEvent( - TouchEvent.obtain( - mTargetTag, - TouchEventType.END, - ev, - mGestureStartTime, - mTargetCoordinates[0], - mTargetCoordinates[1], - mTouchEventCoalescingKeyHelper)); + TouchEvent.obtain( + mTargetTag, + TouchEventType.END, + ev, + mGestureStartTime, + mTargetCoordinates[0], + mTargetCoordinates[1], + mTouchEventCoalescingKeyHelper)); } else if (action == MotionEvent.ACTION_CANCEL) { if (mTouchEventCoalescingKeyHelper.hasCoalescingKey(ev.getDownTime())) { dispatchCancelEvent(ev, eventDispatcher); } else { FLog.e( - ReactConstants.TAG, - "Received an ACTION_CANCEL touch event for which we have no corresponding ACTION_DOWN" - ); + ReactConstants.TAG, + "Received an ACTION_CANCEL touch event for which we have no corresponding ACTION_DOWN"); } mTargetTag = -1; mGestureStartTime = TouchEvent.UNSET; } else { FLog.w( - ReactConstants.TAG, - "Warning : touch event was ignored. Action=" + action + " Target=" + mTargetTag); + ReactConstants.TAG, + "Warning : touch event was ignored. Action=" + action + " Target=" + mTargetTag); } } @@ -171,23 +168,24 @@ public class JSTouchDispatcher { // touch stream and start a native gesture only upon receiving the UP/CANCEL event. if (mTargetTag == -1) { FLog.w( - ReactConstants.TAG, - "Can't cancel already finished gesture. Is a child View trying to start a gesture from " + - "an UP/CANCEL event?"); + ReactConstants.TAG, + "Can't cancel already finished gesture. Is a child View trying to start a gesture from " + + "an UP/CANCEL event?"); return; } Assertions.assertCondition( - !mChildIsHandlingNativeGesture, - "Expected to not have already sent a cancel for this gesture"); - Assertions.assertNotNull(eventDispatcher).dispatchEvent( - TouchEvent.obtain( - mTargetTag, - TouchEventType.CANCEL, - androidEvent, - mGestureStartTime, - mTargetCoordinates[0], - mTargetCoordinates[1], - mTouchEventCoalescingKeyHelper)); + !mChildIsHandlingNativeGesture, + "Expected to not have already sent a cancel for this gesture"); + Assertions.assertNotNull(eventDispatcher) + .dispatchEvent( + TouchEvent.obtain( + mTargetTag, + TouchEventType.CANCEL, + androidEvent, + mGestureStartTime, + mTargetCoordinates[0], + mTargetCoordinates[1], + mTouchEventCoalescingKeyHelper)); } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/LayoutShadowNode.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/LayoutShadowNode.java index 3936518cf47..d8b280410b9 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/LayoutShadowNode.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/LayoutShadowNode.java @@ -33,14 +33,12 @@ import javax.annotation.Nullable; */ public class LayoutShadowNode extends ReactShadowNodeImpl { - /** - * A Mutable version of com.facebook.yoga.YogaValue - */ + /** A Mutable version of com.facebook.yoga.YogaValue */ private static class MutableYogaValue { float value; YogaUnit unit; - private MutableYogaValue() { } + private MutableYogaValue() {} private MutableYogaValue(MutableYogaValue mutableYogaValue) { this.value = mutableYogaValue.value; @@ -119,6 +117,7 @@ public class LayoutShadowNode extends ReactShadowNodeImpl { } boolean mCollapsable; + @ReactProp(name = "collapsable") public void setCollapsable(boolean collapsable) { mCollapsable = collapsable; @@ -271,26 +270,31 @@ public class LayoutShadowNode extends ReactShadowNodeImpl { } switch (flexDirection) { - case "column": { - setFlexDirection(YogaFlexDirection.COLUMN); - break; - } - case "column-reverse": { - setFlexDirection(YogaFlexDirection.COLUMN_REVERSE); - break; - } - case "row": { - setFlexDirection(YogaFlexDirection.ROW); - break; - } - case "row-reverse": { - setFlexDirection(YogaFlexDirection.ROW_REVERSE); - break; - } - default: { - throw new JSApplicationIllegalArgumentException( - "invalid value for flexDirection: " + flexDirection); - } + case "column": + { + setFlexDirection(YogaFlexDirection.COLUMN); + break; + } + case "column-reverse": + { + setFlexDirection(YogaFlexDirection.COLUMN_REVERSE); + break; + } + case "row": + { + setFlexDirection(YogaFlexDirection.ROW); + break; + } + case "row-reverse": + { + setFlexDirection(YogaFlexDirection.ROW_REVERSE); + break; + } + default: + { + throw new JSApplicationIllegalArgumentException( + "invalid value for flexDirection: " + flexDirection); + } } } @@ -306,22 +310,26 @@ public class LayoutShadowNode extends ReactShadowNodeImpl { } switch (flexWrap) { - case "nowrap": { - setFlexWrap(YogaWrap.NO_WRAP); - break; - } - case "wrap": { - setFlexWrap(YogaWrap.WRAP); - break; - } - case "wrap-reverse": { - setFlexWrap(YogaWrap.WRAP_REVERSE); - break; - } - default: { - throw new JSApplicationIllegalArgumentException( - "invalid value for flexWrap: " + flexWrap); - } + case "nowrap": + { + setFlexWrap(YogaWrap.NO_WRAP); + break; + } + case "wrap": + { + setFlexWrap(YogaWrap.WRAP); + break; + } + case "wrap-reverse": + { + setFlexWrap(YogaWrap.WRAP_REVERSE); + break; + } + default: + { + throw new JSApplicationIllegalArgumentException( + "invalid value for flexWrap: " + flexWrap); + } } } @@ -337,42 +345,51 @@ public class LayoutShadowNode extends ReactShadowNodeImpl { } switch (alignSelf) { - case "auto": { - setAlignSelf(YogaAlign.AUTO); - return; - } - case "flex-start": { - setAlignSelf(YogaAlign.FLEX_START); - return; - } - case "center": { - setAlignSelf(YogaAlign.CENTER); - return; - } - case "flex-end": { - setAlignSelf(YogaAlign.FLEX_END); - return; - } - case "stretch": { - setAlignSelf(YogaAlign.STRETCH); - return; - } - case "baseline": { - setAlignSelf(YogaAlign.BASELINE); - return; - } - case "space-between": { - setAlignSelf(YogaAlign.SPACE_BETWEEN); - return; - } - case "space-around": { - setAlignSelf(YogaAlign.SPACE_AROUND); - return; - } - default: { - throw new JSApplicationIllegalArgumentException( - "invalid value for alignSelf: " + alignSelf); - } + case "auto": + { + setAlignSelf(YogaAlign.AUTO); + return; + } + case "flex-start": + { + setAlignSelf(YogaAlign.FLEX_START); + return; + } + case "center": + { + setAlignSelf(YogaAlign.CENTER); + return; + } + case "flex-end": + { + setAlignSelf(YogaAlign.FLEX_END); + return; + } + case "stretch": + { + setAlignSelf(YogaAlign.STRETCH); + return; + } + case "baseline": + { + setAlignSelf(YogaAlign.BASELINE); + return; + } + case "space-between": + { + setAlignSelf(YogaAlign.SPACE_BETWEEN); + return; + } + case "space-around": + { + setAlignSelf(YogaAlign.SPACE_AROUND); + return; + } + default: + { + throw new JSApplicationIllegalArgumentException( + "invalid value for alignSelf: " + alignSelf); + } } } @@ -388,42 +405,51 @@ public class LayoutShadowNode extends ReactShadowNodeImpl { } switch (alignItems) { - case "auto": { - setAlignItems(YogaAlign.AUTO); - return; - } - case "flex-start": { - setAlignItems(YogaAlign.FLEX_START); - return; - } - case "center": { - setAlignItems(YogaAlign.CENTER); - return; - } - case "flex-end": { - setAlignItems(YogaAlign.FLEX_END); - return; - } - case "stretch": { - setAlignItems(YogaAlign.STRETCH); - return; - } - case "baseline": { - setAlignItems(YogaAlign.BASELINE); - return; - } - case "space-between": { - setAlignItems(YogaAlign.SPACE_BETWEEN); - return; - } - case "space-around": { - setAlignItems(YogaAlign.SPACE_AROUND); - return; - } - default: { - throw new JSApplicationIllegalArgumentException( - "invalid value for alignItems: " + alignItems); - } + case "auto": + { + setAlignItems(YogaAlign.AUTO); + return; + } + case "flex-start": + { + setAlignItems(YogaAlign.FLEX_START); + return; + } + case "center": + { + setAlignItems(YogaAlign.CENTER); + return; + } + case "flex-end": + { + setAlignItems(YogaAlign.FLEX_END); + return; + } + case "stretch": + { + setAlignItems(YogaAlign.STRETCH); + return; + } + case "baseline": + { + setAlignItems(YogaAlign.BASELINE); + return; + } + case "space-between": + { + setAlignItems(YogaAlign.SPACE_BETWEEN); + return; + } + case "space-around": + { + setAlignItems(YogaAlign.SPACE_AROUND); + return; + } + default: + { + throw new JSApplicationIllegalArgumentException( + "invalid value for alignItems: " + alignItems); + } } } @@ -439,42 +465,51 @@ public class LayoutShadowNode extends ReactShadowNodeImpl { } switch (alignContent) { - case "auto": { - setAlignContent(YogaAlign.AUTO); - return; - } - case "flex-start": { - setAlignContent(YogaAlign.FLEX_START); - return; - } - case "center": { - setAlignContent(YogaAlign.CENTER); - return; - } - case "flex-end": { - setAlignContent(YogaAlign.FLEX_END); - return; - } - case "stretch": { - setAlignContent(YogaAlign.STRETCH); - return; - } - case "baseline": { - setAlignContent(YogaAlign.BASELINE); - return; - } - case "space-between": { - setAlignContent(YogaAlign.SPACE_BETWEEN); - return; - } - case "space-around": { - setAlignContent(YogaAlign.SPACE_AROUND); - return; - } - default: { - throw new JSApplicationIllegalArgumentException( - "invalid value for alignContent: " + alignContent); - } + case "auto": + { + setAlignContent(YogaAlign.AUTO); + return; + } + case "flex-start": + { + setAlignContent(YogaAlign.FLEX_START); + return; + } + case "center": + { + setAlignContent(YogaAlign.CENTER); + return; + } + case "flex-end": + { + setAlignContent(YogaAlign.FLEX_END); + return; + } + case "stretch": + { + setAlignContent(YogaAlign.STRETCH); + return; + } + case "baseline": + { + setAlignContent(YogaAlign.BASELINE); + return; + } + case "space-between": + { + setAlignContent(YogaAlign.SPACE_BETWEEN); + return; + } + case "space-around": + { + setAlignContent(YogaAlign.SPACE_AROUND); + return; + } + default: + { + throw new JSApplicationIllegalArgumentException( + "invalid value for alignContent: " + alignContent); + } } } @@ -490,34 +525,41 @@ public class LayoutShadowNode extends ReactShadowNodeImpl { } switch (justifyContent) { - case "flex-start": { - setJustifyContent(YogaJustify.FLEX_START); - break; - } - case "center": { - setJustifyContent(YogaJustify.CENTER); - break; - } - case "flex-end": { - setJustifyContent(YogaJustify.FLEX_END); - break; - } - case "space-between": { - setJustifyContent(YogaJustify.SPACE_BETWEEN); - break; - } - case "space-around": { - setJustifyContent(YogaJustify.SPACE_AROUND); - break; - } - case "space-evenly": { - setJustifyContent(YogaJustify.SPACE_EVENLY); - break; - } - default: { - throw new JSApplicationIllegalArgumentException( - "invalid value for justifyContent: " + justifyContent); - } + case "flex-start": + { + setJustifyContent(YogaJustify.FLEX_START); + break; + } + case "center": + { + setJustifyContent(YogaJustify.CENTER); + break; + } + case "flex-end": + { + setJustifyContent(YogaJustify.FLEX_END); + break; + } + case "space-between": + { + setJustifyContent(YogaJustify.SPACE_BETWEEN); + break; + } + case "space-around": + { + setJustifyContent(YogaJustify.SPACE_AROUND); + break; + } + case "space-evenly": + { + setJustifyContent(YogaJustify.SPACE_EVENLY); + break; + } + default: + { + throw new JSApplicationIllegalArgumentException( + "invalid value for justifyContent: " + justifyContent); + } } } @@ -532,22 +574,26 @@ public class LayoutShadowNode extends ReactShadowNodeImpl { } switch (overflow) { - case "visible": { - setOverflow(YogaOverflow.VISIBLE); - break; - } - case "hidden": { - setOverflow(YogaOverflow.HIDDEN); - break; - } - case "scroll": { - setOverflow(YogaOverflow.SCROLL); - break; - } - default: { - throw new JSApplicationIllegalArgumentException( - "invalid value for overflow: " + overflow); - } + case "visible": + { + setOverflow(YogaOverflow.VISIBLE); + break; + } + case "hidden": + { + setOverflow(YogaOverflow.HIDDEN); + break; + } + case "scroll": + { + setOverflow(YogaOverflow.SCROLL); + break; + } + default: + { + throw new JSApplicationIllegalArgumentException( + "invalid value for overflow: " + overflow); + } } } @@ -563,34 +609,35 @@ public class LayoutShadowNode extends ReactShadowNodeImpl { } switch (display) { - case "flex": { - setDisplay(YogaDisplay.FLEX); - break; - } - case "none": { - setDisplay(YogaDisplay.NONE); - break; - } - default: { - throw new JSApplicationIllegalArgumentException( - "invalid value for display: " + display); - } + case "flex": + { + setDisplay(YogaDisplay.FLEX); + break; + } + case "none": + { + setDisplay(YogaDisplay.NONE); + break; + } + default: + { + throw new JSApplicationIllegalArgumentException("invalid value for display: " + display); + } } } @ReactPropGroup( - names = { - ViewProps.MARGIN, - ViewProps.MARGIN_VERTICAL, - ViewProps.MARGIN_HORIZONTAL, - ViewProps.MARGIN_START, - ViewProps.MARGIN_END, - ViewProps.MARGIN_TOP, - ViewProps.MARGIN_BOTTOM, - ViewProps.MARGIN_LEFT, - ViewProps.MARGIN_RIGHT, - } - ) + names = { + ViewProps.MARGIN, + ViewProps.MARGIN_VERTICAL, + ViewProps.MARGIN_HORIZONTAL, + ViewProps.MARGIN_START, + ViewProps.MARGIN_END, + ViewProps.MARGIN_TOP, + ViewProps.MARGIN_BOTTOM, + ViewProps.MARGIN_LEFT, + ViewProps.MARGIN_RIGHT, + }) public void setMargins(int index, Dynamic margin) { if (isVirtual()) { return; @@ -617,18 +664,17 @@ public class LayoutShadowNode extends ReactShadowNodeImpl { } @ReactPropGroup( - names = { - ViewProps.PADDING, - ViewProps.PADDING_VERTICAL, - ViewProps.PADDING_HORIZONTAL, - ViewProps.PADDING_START, - ViewProps.PADDING_END, - ViewProps.PADDING_TOP, - ViewProps.PADDING_BOTTOM, - ViewProps.PADDING_LEFT, - ViewProps.PADDING_RIGHT, - } - ) + names = { + ViewProps.PADDING, + ViewProps.PADDING_VERTICAL, + ViewProps.PADDING_HORIZONTAL, + ViewProps.PADDING_START, + ViewProps.PADDING_END, + ViewProps.PADDING_TOP, + ViewProps.PADDING_BOTTOM, + ViewProps.PADDING_LEFT, + ViewProps.PADDING_RIGHT, + }) public void setPaddings(int index, Dynamic padding) { if (isVirtual()) { return; @@ -652,17 +698,16 @@ public class LayoutShadowNode extends ReactShadowNodeImpl { } @ReactPropGroup( - names = { - ViewProps.BORDER_WIDTH, - ViewProps.BORDER_START_WIDTH, - ViewProps.BORDER_END_WIDTH, - ViewProps.BORDER_TOP_WIDTH, - ViewProps.BORDER_BOTTOM_WIDTH, - ViewProps.BORDER_LEFT_WIDTH, - ViewProps.BORDER_RIGHT_WIDTH, - }, - defaultFloat = YogaConstants.UNDEFINED - ) + names = { + ViewProps.BORDER_WIDTH, + ViewProps.BORDER_START_WIDTH, + ViewProps.BORDER_END_WIDTH, + ViewProps.BORDER_TOP_WIDTH, + ViewProps.BORDER_BOTTOM_WIDTH, + ViewProps.BORDER_LEFT_WIDTH, + ViewProps.BORDER_RIGHT_WIDTH, + }, + defaultFloat = YogaConstants.UNDEFINED) public void setBorderWidths(int index, float borderWidth) { if (isVirtual()) { return; @@ -672,15 +717,14 @@ public class LayoutShadowNode extends ReactShadowNodeImpl { } @ReactPropGroup( - names = { - ViewProps.START, - ViewProps.END, - ViewProps.LEFT, - ViewProps.RIGHT, - ViewProps.TOP, - ViewProps.BOTTOM, - } - ) + names = { + ViewProps.START, + ViewProps.END, + ViewProps.LEFT, + ViewProps.RIGHT, + ViewProps.TOP, + ViewProps.BOTTOM, + }) public void setPositionValues(int index, Dynamic position) { if (isVirtual()) { return; @@ -733,18 +777,21 @@ public class LayoutShadowNode extends ReactShadowNodeImpl { } switch (position) { - case "relative": { - setPositionType(YogaPositionType.RELATIVE); - break; - } - case "absolute": { - setPositionType(YogaPositionType.ABSOLUTE); - break; - } - default: { - throw new JSApplicationIllegalArgumentException( - "invalid value for position: " + position); - } + case "relative": + { + setPositionType(YogaPositionType.RELATIVE); + break; + } + case "absolute": + { + setPositionType(YogaPositionType.ABSOLUTE); + break; + } + default: + { + throw new JSApplicationIllegalArgumentException( + "invalid value for position: " + position); + } } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/MatrixMathHelper.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/MatrixMathHelper.java index c6a438a8034..9c17046c714 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/MatrixMathHelper.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/MatrixMathHelper.java @@ -1,17 +1,16 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; import com.facebook.infer.annotation.Assertions; /** - * Provides helper methods for converting transform operations into a matrix and then into a list - * of translate, scale and rotate commands. + * Provides helper methods for converting transform operations into a matrix and then into a list of + * translate, scale and rotate commands. */ public class MatrixMathHelper { @@ -24,7 +23,7 @@ public class MatrixMathHelper { double[] translation = new double[3]; double[] rotationDegrees = new double[3]; - private static void resetArray(double []arr) { + private static void resetArray(double[] arr) { for (int i = 0; i < arr.length; i++) { arr[i] = 0; } @@ -47,39 +46,58 @@ public class MatrixMathHelper { } public static void multiplyInto(double[] out, double[] a, double[] b) { - double a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], - a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], - a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], - a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15]; + double a00 = a[0], + a01 = a[1], + a02 = a[2], + a03 = a[3], + a10 = a[4], + a11 = a[5], + a12 = a[6], + a13 = a[7], + a20 = a[8], + a21 = a[9], + a22 = a[10], + a23 = a[11], + a30 = a[12], + a31 = a[13], + a32 = a[14], + a33 = a[15]; - double b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3]; - out[0] = b0*a00 + b1*a10 + b2*a20 + b3*a30; - out[1] = b0*a01 + b1*a11 + b2*a21 + b3*a31; - out[2] = b0*a02 + b1*a12 + b2*a22 + b3*a32; - out[3] = b0*a03 + b1*a13 + b2*a23 + b3*a33; + double b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3]; + out[0] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; + out[1] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; + out[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; + out[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; - b0 = b[4]; b1 = b[5]; b2 = b[6]; b3 = b[7]; - out[4] = b0*a00 + b1*a10 + b2*a20 + b3*a30; - out[5] = b0*a01 + b1*a11 + b2*a21 + b3*a31; - out[6] = b0*a02 + b1*a12 + b2*a22 + b3*a32; - out[7] = b0*a03 + b1*a13 + b2*a23 + b3*a33; + b0 = b[4]; + b1 = b[5]; + b2 = b[6]; + b3 = b[7]; + out[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; + out[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; + out[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; + out[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; - b0 = b[8]; b1 = b[9]; b2 = b[10]; b3 = b[11]; - out[8] = b0*a00 + b1*a10 + b2*a20 + b3*a30; - out[9] = b0*a01 + b1*a11 + b2*a21 + b3*a31; - out[10] = b0*a02 + b1*a12 + b2*a22 + b3*a32; - out[11] = b0*a03 + b1*a13 + b2*a23 + b3*a33; + b0 = b[8]; + b1 = b[9]; + b2 = b[10]; + b3 = b[11]; + out[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; + out[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; + out[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; + out[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; - b0 = b[12]; b1 = b[13]; b2 = b[14]; b3 = b[15]; - out[12] = b0*a00 + b1*a10 + b2*a20 + b3*a30; - out[13] = b0*a01 + b1*a11 + b2*a21 + b3*a31; - out[14] = b0*a02 + b1*a12 + b2*a22 + b3*a32; - out[15] = b0*a03 + b1*a13 + b2*a23 + b3*a33; + b0 = b[12]; + b1 = b[13]; + b2 = b[14]; + b3 = b[15]; + out[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; + out[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; + out[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; + out[15] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; } - /** - * @param transformMatrix 16-element array of numbers representing 4x4 transform matrix - */ + /** @param transformMatrix 16-element array of numbers representing 4x4 transform matrix */ public static void decomposeMatrix(double[] transformMatrix, MatrixDecompositionContext ctx) { Assertions.assertCondition(transformMatrix.length == 16); @@ -115,16 +133,12 @@ public class MatrixMathHelper { if (!isZero(matrix[0][3]) || !isZero(matrix[1][3]) || !isZero(matrix[2][3])) { // rightHandSide is the right hand side of the equation. // rightHandSide is a vector, or point in 3d space relative to the origin. - double[] rightHandSide = { matrix[0][3], matrix[1][3], matrix[2][3], matrix[3][3] }; + double[] rightHandSide = {matrix[0][3], matrix[1][3], matrix[2][3], matrix[3][3]}; // Solve the equation by inverting perspectiveMatrix and multiplying // rightHandSide by the inverse. - double[] inversePerspectiveMatrix = inverse( - perspectiveMatrix - ); - double[] transposedInversePerspectiveMatrix = transpose( - inversePerspectiveMatrix - ); + double[] inversePerspectiveMatrix = inverse(perspectiveMatrix); + double[] transposedInversePerspectiveMatrix = transpose(inversePerspectiveMatrix); multiplyVectorByMatrix(rightHandSide, transposedInversePerspectiveMatrix, perspective); } else { // no perspective @@ -192,36 +206,60 @@ public class MatrixMathHelper { // Based on: http://nghiaho.com/?page_id=846 double conv = 180 / Math.PI; rotationDegrees[0] = roundTo3Places(-Math.atan2(row[2][1], row[2][2]) * conv); - rotationDegrees[1] = roundTo3Places(-Math.atan2(-row[2][0], Math.sqrt(row[2][1] * row[2][1] + row[2][2] * row[2][2])) * conv); + rotationDegrees[1] = + roundTo3Places( + -Math.atan2(-row[2][0], Math.sqrt(row[2][1] * row[2][1] + row[2][2] * row[2][2])) + * conv); rotationDegrees[2] = roundTo3Places(-Math.atan2(row[1][0], row[0][0]) * conv); } public static double determinant(double[] matrix) { - double m00 = matrix[0], m01 = matrix[1], m02 = matrix[2], m03 = matrix[3], m10 = matrix[4], - m11 = matrix[5], m12 = matrix[6], m13 = matrix[7], m20 = matrix[8], m21 = matrix[9], - m22 = matrix[10], m23 = matrix[11], m30 = matrix[12], m31 = matrix[13], m32 = matrix[14], - m33 = matrix[15]; - return ( - m03 * m12 * m21 * m30 - m02 * m13 * m21 * m30 - - m03 * m11 * m22 * m30 + m01 * m13 * m22 * m30 + - m02 * m11 * m23 * m30 - m01 * m12 * m23 * m30 - - m03 * m12 * m20 * m31 + m02 * m13 * m20 * m31 + - m03 * m10 * m22 * m31 - m00 * m13 * m22 * m31 - - m02 * m10 * m23 * m31 + m00 * m12 * m23 * m31 + - m03 * m11 * m20 * m32 - m01 * m13 * m20 * m32 - - m03 * m10 * m21 * m32 + m00 * m13 * m21 * m32 + - m01 * m10 * m23 * m32 - m00 * m11 * m23 * m32 - - m02 * m11 * m20 * m33 + m01 * m12 * m20 * m33 + - m02 * m10 * m21 * m33 - m00 * m12 * m21 * m33 - - m01 * m10 * m22 * m33 + m00 * m11 * m22 * m33 - ); + double m00 = matrix[0], + m01 = matrix[1], + m02 = matrix[2], + m03 = matrix[3], + m10 = matrix[4], + m11 = matrix[5], + m12 = matrix[6], + m13 = matrix[7], + m20 = matrix[8], + m21 = matrix[9], + m22 = matrix[10], + m23 = matrix[11], + m30 = matrix[12], + m31 = matrix[13], + m32 = matrix[14], + m33 = matrix[15]; + return (m03 * m12 * m21 * m30 + - m02 * m13 * m21 * m30 + - m03 * m11 * m22 * m30 + + m01 * m13 * m22 * m30 + + m02 * m11 * m23 * m30 + - m01 * m12 * m23 * m30 + - m03 * m12 * m20 * m31 + + m02 * m13 * m20 * m31 + + m03 * m10 * m22 * m31 + - m00 * m13 * m22 * m31 + - m02 * m10 * m23 * m31 + + m00 * m12 * m23 * m31 + + m03 * m11 * m20 * m32 + - m01 * m13 * m20 * m32 + - m03 * m10 * m21 * m32 + + m00 * m13 * m21 * m32 + + m01 * m10 * m23 * m32 + - m00 * m11 * m23 * m32 + - m02 * m11 * m20 * m33 + + m01 * m12 * m20 * m33 + + m02 * m10 * m21 * m33 + - m00 * m12 * m21 * m33 + - m01 * m10 * m22 * m33 + + m00 * m11 * m22 * m33); } /** - * Inverse of a matrix. Multiplying by the inverse is used in matrix math - * instead of division. + * Inverse of a matrix. Multiplying by the inverse is used in matrix math instead of division. * - * Formula from: + *

Formula from: * http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm */ public static double[] inverse(double[] matrix) { @@ -229,33 +267,139 @@ public class MatrixMathHelper { if (isZero(det)) { return matrix; } - double m00 = matrix[0], m01 = matrix[1], m02 = matrix[2], m03 = matrix[3], m10 = matrix[4], - m11 = matrix[5], m12 = matrix[6], m13 = matrix[7], m20 = matrix[8], m21 = matrix[9], - m22 = matrix[10], m23 = matrix[11], m30 = matrix[12], m31 = matrix[13], m32 = matrix[14], - m33 = matrix[15]; + double m00 = matrix[0], + m01 = matrix[1], + m02 = matrix[2], + m03 = matrix[3], + m10 = matrix[4], + m11 = matrix[5], + m12 = matrix[6], + m13 = matrix[7], + m20 = matrix[8], + m21 = matrix[9], + m22 = matrix[10], + m23 = matrix[11], + m30 = matrix[12], + m31 = matrix[13], + m32 = matrix[14], + m33 = matrix[15]; return new double[] { - (m12 * m23 * m31 - m13 * m22 * m31 + m13 * m21 * m32 - m11 * m23 * m32 - m12 * m21 * m33 + m11 * m22 * m33) / det, - (m03 * m22 * m31 - m02 * m23 * m31 - m03 * m21 * m32 + m01 * m23 * m32 + m02 * m21 * m33 - m01 * m22 * m33) / det, - (m02 * m13 * m31 - m03 * m12 * m31 + m03 * m11 * m32 - m01 * m13 * m32 - m02 * m11 * m33 + m01 * m12 * m33) / det, - (m03 * m12 * m21 - m02 * m13 * m21 - m03 * m11 * m22 + m01 * m13 * m22 + m02 * m11 * m23 - m01 * m12 * m23) / det, - (m13 * m22 * m30 - m12 * m23 * m30 - m13 * m20 * m32 + m10 * m23 * m32 + m12 * m20 * m33 - m10 * m22 * m33) / det, - (m02 * m23 * m30 - m03 * m22 * m30 + m03 * m20 * m32 - m00 * m23 * m32 - m02 * m20 * m33 + m00 * m22 * m33) / det, - (m03 * m12 * m30 - m02 * m13 * m30 - m03 * m10 * m32 + m00 * m13 * m32 + m02 * m10 * m33 - m00 * m12 * m33) / det, - (m02 * m13 * m20 - m03 * m12 * m20 + m03 * m10 * m22 - m00 * m13 * m22 - m02 * m10 * m23 + m00 * m12 * m23) / det, - (m11 * m23 * m30 - m13 * m21 * m30 + m13 * m20 * m31 - m10 * m23 * m31 - m11 * m20 * m33 + m10 * m21 * m33) / det, - (m03 * m21 * m30 - m01 * m23 * m30 - m03 * m20 * m31 + m00 * m23 * m31 + m01 * m20 * m33 - m00 * m21 * m33) / det, - (m01 * m13 * m30 - m03 * m11 * m30 + m03 * m10 * m31 - m00 * m13 * m31 - m01 * m10 * m33 + m00 * m11 * m33) / det, - (m03 * m11 * m20 - m01 * m13 * m20 - m03 * m10 * m21 + m00 * m13 * m21 + m01 * m10 * m23 - m00 * m11 * m23) / det, - (m12 * m21 * m30 - m11 * m22 * m30 - m12 * m20 * m31 + m10 * m22 * m31 + m11 * m20 * m32 - m10 * m21 * m32) / det, - (m01 * m22 * m30 - m02 * m21 * m30 + m02 * m20 * m31 - m00 * m22 * m31 - m01 * m20 * m32 + m00 * m21 * m32) / det, - (m02 * m11 * m30 - m01 * m12 * m30 - m02 * m10 * m31 + m00 * m12 * m31 + m01 * m10 * m32 - m00 * m11 * m32) / det, - (m01 * m12 * m20 - m02 * m11 * m20 + m02 * m10 * m21 - m00 * m12 * m21 - m01 * m10 * m22 + m00 * m11 * m22) / det + (m12 * m23 * m31 + - m13 * m22 * m31 + + m13 * m21 * m32 + - m11 * m23 * m32 + - m12 * m21 * m33 + + m11 * m22 * m33) + / det, + (m03 * m22 * m31 + - m02 * m23 * m31 + - m03 * m21 * m32 + + m01 * m23 * m32 + + m02 * m21 * m33 + - m01 * m22 * m33) + / det, + (m02 * m13 * m31 + - m03 * m12 * m31 + + m03 * m11 * m32 + - m01 * m13 * m32 + - m02 * m11 * m33 + + m01 * m12 * m33) + / det, + (m03 * m12 * m21 + - m02 * m13 * m21 + - m03 * m11 * m22 + + m01 * m13 * m22 + + m02 * m11 * m23 + - m01 * m12 * m23) + / det, + (m13 * m22 * m30 + - m12 * m23 * m30 + - m13 * m20 * m32 + + m10 * m23 * m32 + + m12 * m20 * m33 + - m10 * m22 * m33) + / det, + (m02 * m23 * m30 + - m03 * m22 * m30 + + m03 * m20 * m32 + - m00 * m23 * m32 + - m02 * m20 * m33 + + m00 * m22 * m33) + / det, + (m03 * m12 * m30 + - m02 * m13 * m30 + - m03 * m10 * m32 + + m00 * m13 * m32 + + m02 * m10 * m33 + - m00 * m12 * m33) + / det, + (m02 * m13 * m20 + - m03 * m12 * m20 + + m03 * m10 * m22 + - m00 * m13 * m22 + - m02 * m10 * m23 + + m00 * m12 * m23) + / det, + (m11 * m23 * m30 + - m13 * m21 * m30 + + m13 * m20 * m31 + - m10 * m23 * m31 + - m11 * m20 * m33 + + m10 * m21 * m33) + / det, + (m03 * m21 * m30 + - m01 * m23 * m30 + - m03 * m20 * m31 + + m00 * m23 * m31 + + m01 * m20 * m33 + - m00 * m21 * m33) + / det, + (m01 * m13 * m30 + - m03 * m11 * m30 + + m03 * m10 * m31 + - m00 * m13 * m31 + - m01 * m10 * m33 + + m00 * m11 * m33) + / det, + (m03 * m11 * m20 + - m01 * m13 * m20 + - m03 * m10 * m21 + + m00 * m13 * m21 + + m01 * m10 * m23 + - m00 * m11 * m23) + / det, + (m12 * m21 * m30 + - m11 * m22 * m30 + - m12 * m20 * m31 + + m10 * m22 * m31 + + m11 * m20 * m32 + - m10 * m21 * m32) + / det, + (m01 * m22 * m30 + - m02 * m21 * m30 + + m02 * m20 * m31 + - m00 * m22 * m31 + - m01 * m20 * m32 + + m00 * m21 * m32) + / det, + (m02 * m11 * m30 + - m01 * m12 * m30 + - m02 * m10 * m31 + + m00 * m12 * m31 + + m01 * m10 * m32 + - m00 * m11 * m32) + / det, + (m01 * m12 * m20 + - m02 * m11 * m20 + + m02 * m10 * m21 + - m00 * m12 * m21 + - m01 * m10 * m22 + + m00 * m11 * m22) + / det }; } - /** - * Turns columns into rows and rows into columns. - */ + /** Turns columns into rows and rows into columns. */ public static double[] transpose(double[] m) { return new double[] { m[0], m[4], m[8], m[12], @@ -265,9 +409,7 @@ public class MatrixMathHelper { }; } - /** - * Based on: http://tog.acm.org/resources/GraphicsGems/gemsii/unmatrix.c - */ + /** Based on: http://tog.acm.org/resources/GraphicsGems/gemsii/unmatrix.c */ public static void multiplyVectorByMatrix(double[] v, double[] m, double[] result) { double vx = v[0], vy = v[1], vz = v[2], vw = v[3]; result[0] = vx * m[0] + vy * m[4] + vz * m[8] + vw * m[12]; @@ -276,33 +418,23 @@ public class MatrixMathHelper { result[3] = vx * m[3] + vy * m[7] + vz * m[11] + vw * m[15]; } - /** - * From: https://code.google.com/p/webgl-mjs/source/browse/mjs.js - */ + /** From: https://code.google.com/p/webgl-mjs/source/browse/mjs.js */ public static double v3Length(double[] a) { - return Math.sqrt(a[0]*a[0] + a[1]*a[1] + a[2]*a[2]); + return Math.sqrt(a[0] * a[0] + a[1] * a[1] + a[2] * a[2]); } - /** - * Based on: https://code.google.com/p/webgl-mjs/source/browse/mjs.js - */ + /** Based on: https://code.google.com/p/webgl-mjs/source/browse/mjs.js */ public static double[] v3Normalize(double[] vector, double norm) { double im = 1 / (isZero(norm) ? v3Length(vector) : norm); - return new double[] { - vector[0] * im, - vector[1] * im, - vector[2] * im - }; + return new double[] {vector[0] * im, vector[1] * im, vector[2] * im}; } /** - * The dot product of a and b, two 3-element vectors. - * From: https://code.google.com/p/webgl-mjs/source/browse/mjs.js + * The dot product of a and b, two 3-element vectors. From: + * https://code.google.com/p/webgl-mjs/source/browse/mjs.js */ public static double v3Dot(double[] a, double[] b) { - return a[0] * b[0] + - a[1] * b[1] + - a[2] * b[2]; + return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; } /** @@ -310,10 +442,8 @@ public class MatrixMathHelper { * http://www.opensource.apple.com/source/WebCore/WebCore-514/platform/graphics/transforms/TransformationMatrix.cpp */ public static double[] v3Combine(double[] a, double[] b, double aScale, double bScale) { - return new double[]{ - aScale * a[0] + bScale * b[0], - aScale * a[1] + bScale * b[1], - aScale * a[2] + bScale * b[2] + return new double[] { + aScale * a[0] + bScale * b[0], aScale * a[1] + bScale * b[1], aScale * a[2] + bScale * b[2] }; } @@ -322,10 +452,8 @@ public class MatrixMathHelper { * http://www.opensource.apple.com/source/WebCore/WebCore-514/platform/graphics/transforms/TransformationMatrix.cpp */ public static double[] v3Cross(double[] a, double[] b) { - return new double[]{ - a[1] * b[2] - a[2] * b[1], - a[2] * b[0] - a[0] * b[2], - a[0] * b[1] - a[1] * b[0] + return new double[] { + a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0] }; } @@ -344,8 +472,14 @@ public class MatrixMathHelper { } public static void resetIdentityMatrix(double[] matrix) { - matrix[1] = matrix[2] = matrix[3] = matrix[4] = matrix[6] = matrix[7] = matrix[8] = matrix[9] = - matrix[11] = matrix[12] = matrix[13] = matrix[14] = 0; + matrix[1] = + matrix[2] = + matrix[3] = + matrix[4] = + matrix[6] = + matrix[7] = + matrix[8] = + matrix[9] = matrix[11] = matrix[12] = matrix[13] = matrix[14] = 0; matrix[0] = matrix[5] = matrix[10] = matrix[15] = 1; } diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/MeasureSpecAssertions.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/MeasureSpecAssertions.java index 6f457dfef88..3c08c68f8f1 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/MeasureSpecAssertions.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/MeasureSpecAssertions.java @@ -1,17 +1,14 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; import android.view.View; -/** - * Shared utility for asserting on MeasureSpecs. - */ +/** Shared utility for asserting on MeasureSpecs. */ public class MeasureSpecAssertions { public static final void assertExplicitMeasureSpec(int widthMeasureSpec, int heightMeasureSpec) { @@ -20,8 +17,8 @@ public class MeasureSpecAssertions { if (widthMode == View.MeasureSpec.UNSPECIFIED || heightMode == View.MeasureSpec.UNSPECIFIED) { throw new IllegalStateException( - "A catalyst view must have an explicit width and height given to it. This should " + - "normally happen as part of the standard catalyst UI framework."); + "A catalyst view must have an explicit width and height given to it. This should " + + "normally happen as part of the standard catalyst UI framework."); } } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/NativeKind.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/NativeKind.java index 44ca85d0287..a6cb8b9a2bd 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/NativeKind.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/NativeKind.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; // Common conditionals: diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/NativeViewHierarchyManager.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/NativeViewHierarchyManager.java index 02b481c1618..81aed9c57f8 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/NativeViewHierarchyManager.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/NativeViewHierarchyManager.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; import android.content.res.Resources; @@ -40,25 +39,21 @@ import javax.annotation.concurrent.NotThreadSafe; /** * Delegate of {@link UIManagerModule} that owns the native view hierarchy and mapping between - * native view names used in JS and corresponding instances of {@link ViewManager}. The - * {@link UIManagerModule} communicates with this class by it's public interface methods: - * - {@link #updateProperties} - * - {@link #updateLayout} - * - {@link #createView} - * - {@link #manageChildren} + * native view names used in JS and corresponding instances of {@link ViewManager}. The {@link + * UIManagerModule} communicates with this class by it's public interface methods: - {@link + * #updateProperties} - {@link #updateLayout} - {@link #createView} - {@link #manageChildren} * executing all the scheduled UI operations at the end of JS batch. * - * NB: All native view management methods listed above must be called from the UI thread. + *

NB: All native view management methods listed above must be called from the UI thread. * - * The {@link ReactContext} instance that is passed to views that this manager creates differs - * from the one that we pass as a constructor. Instead we wrap the provided instance of - * {@link ReactContext} in an instance of {@link ThemedReactContext} that additionally provide - * a correct theme based on the root view for a view tree that we attach newly created view to. - * Therefore this view manager will create a copy of {@link ThemedReactContext} that wraps - * the instance of {@link ReactContext} for each root view added to the manager (see - * {@link #addRootView}). + *

The {@link ReactContext} instance that is passed to views that this manager creates differs + * from the one that we pass as a constructor. Instead we wrap the provided instance of {@link + * ReactContext} in an instance of {@link ThemedReactContext} that additionally provide a correct + * theme based on the root view for a view tree that we attach newly created view to. Therefore this + * view manager will create a copy of {@link ThemedReactContext} that wraps the instance of {@link + * ReactContext} for each root view added to the manager (see {@link #addRootView}). * - * TODO(5483031): Only dispatch updates when shadow views have changed + *

TODO(5483031): Only dispatch updates when shadow views have changed */ @NotThreadSafe public class NativeViewHierarchyManager { @@ -91,23 +86,28 @@ public class NativeViewHierarchyManager { mRootViewManager = manager; } - public synchronized final View resolveView(int tag) { + public final synchronized View resolveView(int tag) { View view = mTagsToViews.get(tag); if (view == null) { - throw new IllegalViewOperationException("Trying to resolve view with tag " + tag - + " which doesn't exist"); + throw new IllegalViewOperationException( + "Trying to resolve view with tag " + tag + " which doesn't exist"); } return view; } - public synchronized final ViewManager resolveViewManager(int tag) { + public final synchronized ViewManager resolveViewManager(int tag) { ViewManager viewManager = mTagsToViewManagers.get(tag); if (viewManager == null) { boolean alreadyDropped = Arrays.asList(mDroppedViewArray).contains(tag); - throw new IllegalViewOperationException("ViewManager for tag " - + tag + " could not be found.\n View already dropped? " - + alreadyDropped + ".\nLast index "+ mDroppedViewIndex + " in last 100 views" - + mDroppedViewArray.toString()); + throw new IllegalViewOperationException( + "ViewManager for tag " + + tag + + " could not be found.\n View already dropped? " + + alreadyDropped + + ".\nLast index " + + mDroppedViewIndex + + " in last 100 views" + + mDroppedViewArray.toString()); } return viewManager; } @@ -153,36 +153,41 @@ public class NativeViewHierarchyManager { int parentTag, int tag, int x, int y, int width, int height) { UiThreadUtil.assertOnUiThread(); SystraceMessage.beginSection( - Systrace.TRACE_TAG_REACT_VIEW, - "NativeViewHierarchyManager_updateLayout") + Systrace.TRACE_TAG_REACT_VIEW, "NativeViewHierarchyManager_updateLayout") .arg("parentTag", parentTag) .arg("tag", tag) .flush(); try { View viewToUpdate = resolveView(tag); - // Even though we have exact dimensions, we still call measure because some platform views (e.g. + // Even though we have exact dimensions, we still call measure because some platform views + // (e.g. // Switch) assume that method will always be called before onLayout and onDraw. They use it to // calculate and cache information used in the draw pass. For most views, onMeasure can be // stubbed out to only call setMeasuredDimensions. For ViewGroups, onLayout should be stubbed - // out to not recursively call layout on its children: React Native already handles doing that. + // out to not recursively call layout on its children: React Native already handles doing + // that. // - // Also, note measure and layout need to be called *after* all View properties have been updated + // Also, note measure and layout need to be called *after* all View properties have been + // updated // because of caching and calculation that may occur in onMeasure and onLayout. Layout - // operations should also follow the native view hierarchy and go top to bottom for consistency + // operations should also follow the native view hierarchy and go top to bottom for + // consistency // with standard layout passes (some views may depend on this). viewToUpdate.measure( View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY)); - // We update the layout of the ReactRootView when there is a change in the layout of its child. + // We update the layout of the ReactRootView when there is a change in the layout of its + // child. // This is required to re-measure the size of the native View container (usually a // FrameLayout) that is configured with layout_height = WRAP_CONTENT or layout_width = // WRAP_CONTENT // // This code is going to be executed ONLY when there is a change in the size of the Root - // View defined in the js side. Changes in the layout of inner views will not trigger an update + // View defined in the js side. Changes in the layout of inner views will not trigger an + // update // on the layout of the Root View. ViewParent parent = viewToUpdate.getParent(); if (parent instanceof RootView) { @@ -197,8 +202,9 @@ public class NativeViewHierarchyManager { parentViewManagerWithChildren = (IViewManagerWithChildren) parentViewManager; } else { throw new IllegalViewOperationException( - "Trying to use view with tag " + parentTag + - " as a parent, but its Manager doesn't implement IViewManagerWithChildren"); + "Trying to use view with tag " + + parentTag + + " as a parent, but its Manager doesn't implement IViewManagerWithChildren"); } if (parentViewManagerWithChildren != null && !parentViewManagerWithChildren.needsCustomLayoutForChildren()) { @@ -231,8 +237,7 @@ public class NativeViewHierarchyManager { } private void updateLayout(View viewToUpdate, int x, int y, int width, int height) { - if (mLayoutAnimationEnabled && - mLayoutAnimator.shouldAnimateLayout(viewToUpdate)) { + if (mLayoutAnimationEnabled && mLayoutAnimator.shouldAnimateLayout(viewToUpdate)) { mLayoutAnimator.applyLayoutUpdate(viewToUpdate, x, y, width, height); } else { viewToUpdate.layout(x, y, x + width, y + height); @@ -246,8 +251,7 @@ public class NativeViewHierarchyManager { @Nullable ReactStylesDiffMap initialProps) { UiThreadUtil.assertOnUiThread(); SystraceMessage.beginSection( - Systrace.TRACE_TAG_REACT_VIEW, - "NativeViewHierarchyManager_createView") + Systrace.TRACE_TAG_REACT_VIEW, "NativeViewHierarchyManager_createView") .arg("tag", tag) .arg("className", className) .flush(); @@ -281,11 +285,12 @@ public class NativeViewHierarchyManager { if (null != viewToManage) { stringBuilder.append("View tag:" + viewToManage.getId() + "\n"); stringBuilder.append(" children(" + viewManager.getChildCount(viewToManage) + "): [\n"); - for (int index=0; index= viewManager.getChildCount(viewToManage)) { if (mRootTags.get(tag) && viewManager.getChildCount(viewToManage) == 0) { @@ -415,33 +417,32 @@ public class NativeViewHierarchyManager { return; } throw new IllegalViewOperationException( - "Trying to remove a view index above child " + - "count " + indexToRemove + " view tag: " + tag + "\n detail: " + - constructManageChildrenErrorMessage( - viewToManage, - viewManager, - indicesToRemove, - viewsToAdd, - tagsToDelete)); + "Trying to remove a view index above child " + + "count " + + indexToRemove + + " view tag: " + + tag + + "\n detail: " + + constructManageChildrenErrorMessage( + viewToManage, viewManager, indicesToRemove, viewsToAdd, tagsToDelete)); } if (indexToRemove >= lastIndexToRemove) { throw new IllegalViewOperationException( "Trying to remove an out of order view index:" - + indexToRemove + " view tag: " + tag + "\n detail: " + - constructManageChildrenErrorMessage( - viewToManage, - viewManager, - indicesToRemove, - viewsToAdd, - tagsToDelete)); + + indexToRemove + + " view tag: " + + tag + + "\n detail: " + + constructManageChildrenErrorMessage( + viewToManage, viewManager, indicesToRemove, viewsToAdd, tagsToDelete)); } int normalizedIndexToRemove = normalizeIndex(indexToRemove, pendingIndicesToDelete); View viewToRemove = viewManager.getChildAt(viewToManage, normalizedIndexToRemove); - if (mLayoutAnimationEnabled && - mLayoutAnimator.shouldAnimateLayout(viewToRemove) && - arrayContains(tagsToDelete, viewToRemove.getId())) { + if (mLayoutAnimationEnabled + && mLayoutAnimator.shouldAnimateLayout(viewToRemove) + && arrayContains(tagsToDelete, viewToRemove.getId())) { // The view will be removed and dropped by the 'delete' layout animation // instead, so do nothing } else { @@ -459,32 +460,28 @@ public class NativeViewHierarchyManager { final View viewToDestroy = mTagsToViews.get(tagToDelete); if (viewToDestroy == null) { throw new IllegalViewOperationException( - "Trying to destroy unknown view tag: " - + tagToDelete + "\n detail: " + - constructManageChildrenErrorMessage( - viewToManage, - viewManager, - indicesToRemove, - viewsToAdd, - tagsToDelete)); + "Trying to destroy unknown view tag: " + + tagToDelete + + "\n detail: " + + constructManageChildrenErrorMessage( + viewToManage, viewManager, indicesToRemove, viewsToAdd, tagsToDelete)); } - if (mLayoutAnimationEnabled && - mLayoutAnimator.shouldAnimateLayout(viewToDestroy)) { + if (mLayoutAnimationEnabled && mLayoutAnimator.shouldAnimateLayout(viewToDestroy)) { int updatedCount = pendingIndicesToDelete.get(indexToDelete, 0) + 1; pendingIndicesToDelete.put(indexToDelete, updatedCount); mLayoutAnimator.deleteView( - viewToDestroy, - new LayoutAnimationListener() { - @Override - public void onAnimationEnd() { - viewManager.removeView(viewToManage, viewToDestroy); - dropView(viewToDestroy); + viewToDestroy, + new LayoutAnimationListener() { + @Override + public void onAnimationEnd() { + viewManager.removeView(viewToManage, viewToDestroy); + dropView(viewToDestroy); - int count = pendingIndicesToDelete.get(indexToDelete, 0); - pendingIndicesToDelete.put(indexToDelete, Math.max(0, count - 1)); - } - }); + int count = pendingIndicesToDelete.get(indexToDelete, 0); + pendingIndicesToDelete.put(indexToDelete, Math.max(0, count - 1)); + } + }); } else { dropView(viewToDestroy); } @@ -498,13 +495,10 @@ public class NativeViewHierarchyManager { if (viewToAdd == null) { throw new IllegalViewOperationException( "Trying to add unknown view tag: " - + viewAtIndex.mTag + "\n detail: " + - constructManageChildrenErrorMessage( - viewToManage, - viewManager, - indicesToRemove, - viewsToAdd, - tagsToDelete)); + + viewAtIndex.mTag + + "\n detail: " + + constructManageChildrenErrorMessage( + viewToManage, viewManager, indicesToRemove, viewsToAdd, tagsToDelete)); } int normalizedIndexToAdd = normalizeIndex(viewAtIndex.mIndex, pendingIndicesToDelete); viewManager.addView(viewToManage, viewToAdd, normalizedIndexToAdd); @@ -529,28 +523,16 @@ public class NativeViewHierarchyManager { * views */ private static String constructSetChildrenErrorMessage( - ViewGroup viewToManage, - ViewGroupManager viewManager, - ReadableArray childrenTags) { + ViewGroup viewToManage, ViewGroupManager viewManager, ReadableArray childrenTags) { ViewAtIndex[] viewsToAdd = new ViewAtIndex[childrenTags.size()]; for (int i = 0; i < childrenTags.size(); i++) { viewsToAdd[i] = new ViewAtIndex(childrenTags.getInt(i), i); } - return constructManageChildrenErrorMessage( - viewToManage, - viewManager, - null, - viewsToAdd, - null - ); + return constructManageChildrenErrorMessage(viewToManage, viewManager, null, viewsToAdd, null); } - /** - * Simplified version of manageChildren that only deals with adding children views - */ - public synchronized void setChildren( - int tag, - ReadableArray childrenTags) { + /** Simplified version of manageChildren that only deals with adding children views */ + public synchronized void setChildren(int tag, ReadableArray childrenTags) { UiThreadUtil.assertOnUiThread(); ViewGroup viewToManage = (ViewGroup) mTagsToViews.get(tag); ViewGroupManager viewManager = (ViewGroupManager) resolveViewManager(tag); @@ -559,32 +541,30 @@ public class NativeViewHierarchyManager { View viewToAdd = mTagsToViews.get(childrenTags.getInt(i)); if (viewToAdd == null) { throw new IllegalViewOperationException( - "Trying to add unknown view tag: " - + childrenTags.getInt(i) + "\n detail: " + - constructSetChildrenErrorMessage( - viewToManage, - viewManager, - childrenTags)); + "Trying to add unknown view tag: " + + childrenTags.getInt(i) + + "\n detail: " + + constructSetChildrenErrorMessage(viewToManage, viewManager, childrenTags)); } viewManager.addView(viewToManage, viewToAdd, i); } } - /** - * See {@link UIManagerModule#addRootView}. - */ + /** See {@link UIManagerModule#addRootView}. */ public synchronized void addRootView(int tag, View view) { addRootViewGroup(tag, view); } - protected synchronized final void addRootViewGroup(int tag, View view) { + protected final synchronized void addRootViewGroup(int tag, View view) { if (view.getId() != View.NO_ID) { FLog.e( - TAG, - "Trying to add a root view with an explicit id (" + view.getId() + ") already " + - "set. React Native uses the id field to track react tags and will overwrite this field. " + - "If that is fine, explicitly overwrite the id field to View.NO_ID before calling " + - "addRootView."); + TAG, + "Trying to add a root view with an explicit id (" + + view.getId() + + ") already " + + "set. React Native uses the id field to track react tags and will overwrite this field. " + + "If that is fine, explicitly overwrite the id field to View.NO_ID before calling " + + "addRootView."); } mTagsToViews.put(tag, view); @@ -598,9 +578,7 @@ public class NativeViewHierarchyManager { mDroppedViewIndex = (mDroppedViewIndex + 1) % 100; } - /** - * Releases all references to given native View. - */ + /** Releases all references to given native View. */ protected synchronized void dropView(View view) { UiThreadUtil.assertOnUiThread(); if (view == null) { @@ -626,7 +604,7 @@ public class NativeViewHierarchyManager { for (int i = viewGroupManager.getChildCount(viewGroup) - 1; i >= 0; i--) { View child = viewGroupManager.getChildAt(viewGroup, i); if (child == null) { - FLog.e(TAG, "Unable to drop null child view"); + FLog.e(TAG, "Unable to drop null child view"); } else if (mTagsToViews.get(child.getId()) != null) { dropView(child); } @@ -641,8 +619,8 @@ public class NativeViewHierarchyManager { public synchronized void removeRootView(int rootViewTag) { UiThreadUtil.assertOnUiThread(); if (!mRootTags.get(rootViewTag)) { - SoftAssertions.assertUnreachable( - "View with tag " + rootViewTag + " is not registered as a root view"); + SoftAssertions.assertUnreachable( + "View with tag " + rootViewTag + " is not registered as a root view"); } View rootView = mTagsToViews.get(rootViewTag); dropView(rootView); @@ -679,12 +657,12 @@ public class NativeViewHierarchyManager { } /** - * Returns the coordinates of a view relative to the window (not just the RootView - * which is what measure will return) + * Returns the coordinates of a view relative to the window (not just the RootView which is what + * measure will return) * * @param tag - the tag for the view * @param outputBuffer - output buffer that contains [x,y,width,height] of the view in coordinates - * relative to the device window + * relative to the device window */ public synchronized void measureInWindow(int tag, int[] outputBuffer) { UiThreadUtil.assertOnUiThread(); @@ -719,9 +697,7 @@ public class NativeViewHierarchyManager { } public synchronized void setJSResponder( - int reactTag, - int initialReactTag, - boolean blockNativeResponder) { + int reactTag, int initialReactTag, boolean blockNativeResponder) { if (!blockNativeResponder) { mJSResponderHandler.setJSResponder(initialReactTag, null); return; @@ -739,8 +715,7 @@ public class NativeViewHierarchyManager { SoftAssertions.assertUnreachable( "Cannot block native responder on " + reactTag + " that is a root view"); } - mJSResponderHandler - .setJSResponder(initialReactTag, view.getParent()); + mJSResponderHandler.setJSResponder(initialReactTag, view.getParent()); } public void clearJSResponder() { @@ -756,14 +731,12 @@ public class NativeViewHierarchyManager { } public synchronized void dispatchCommand( - int reactTag, - int commandId, - @Nullable ReadableArray args) { + int reactTag, int commandId, @Nullable ReadableArray args) { UiThreadUtil.assertOnUiThread(); View view = mTagsToViews.get(reactTag); if (view == null) { - throw new IllegalViewOperationException("Trying to send command to a non-existing view " + - "with tag " + reactTag); + throw new IllegalViewOperationException( + "Trying to send command to a non-existing view " + "with tag " + reactTag); } ViewManager viewManager = resolveViewManager(reactTag); @@ -771,14 +744,12 @@ public class NativeViewHierarchyManager { } public synchronized void dispatchCommand( - int reactTag, - String commandId, - @Nullable ReadableArray args) { + int reactTag, String commandId, @Nullable ReadableArray args) { UiThreadUtil.assertOnUiThread(); View view = mTagsToViews.get(reactTag); if (view == null) { - throw new IllegalViewOperationException("Trying to send command to a non-existing view " + - "with tag " + reactTag); + throw new IllegalViewOperationException( + "Trying to send command to a non-existing view " + "with tag " + reactTag); } ViewManager viewManager = resolveViewManager(reactTag); @@ -789,13 +760,13 @@ public class NativeViewHierarchyManager { * Show a {@link PopupMenu}. * * @param reactTag the tag of the anchor view (the PopupMenu is displayed next to this view); this - * needs to be the tag of a native view (shadow views can not be anchors) + * needs to be the tag of a native view (shadow views can not be anchors) * @param items the menu items as an array of strings * @param success will be called with the position of the selected item as the first argument, or - * no arguments if the menu is dismissed + * no arguments if the menu is dismissed */ - public synchronized void showPopupMenu(int reactTag, ReadableArray items, Callback success, - Callback error) { + public synchronized void showPopupMenu( + int reactTag, ReadableArray items, Callback success, Callback error) { UiThreadUtil.assertOnUiThread(); View anchor = mTagsToViews.get(reactTag); if (anchor == null) { @@ -816,17 +787,15 @@ public class NativeViewHierarchyManager { mPopupMenu.show(); } - /** - * Dismiss the last opened PopupMenu {@link PopupMenu}. - */ + /** Dismiss the last opened PopupMenu {@link PopupMenu}. */ public void dismissPopupMenu() { if (mPopupMenu != null) { mPopupMenu.dismiss(); } } - private static class PopupMenuCallbackHandler implements PopupMenu.OnMenuItemClickListener, - PopupMenu.OnDismissListener { + private static class PopupMenuCallbackHandler + implements PopupMenu.OnMenuItemClickListener, PopupMenu.OnDismissListener { final Callback mSuccess; boolean mConsumed = false; @@ -855,8 +824,8 @@ public class NativeViewHierarchyManager { } /** - * @return Themed React context for view with a given {@param reactTag} - it gets the - * context directly from the view using {@link View#getContext}. + * @return Themed React context for view with a given {@param reactTag} - it gets the context + * directly from the view using {@link View#getContext}. */ private ThemedReactContext getReactContextForView(int reactTag) { View view = mTagsToViews.get(reactTag); diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/NativeViewHierarchyOptimizer.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/NativeViewHierarchyOptimizer.java index a22e8b90501..5fd869d928b 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/NativeViewHierarchyOptimizer.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/NativeViewHierarchyOptimizer.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; import android.util.SparseBooleanArray; @@ -17,34 +16,32 @@ import javax.annotation.Nullable; * Class responsible for optimizing the native view hierarchy while still respecting the final UI * product specified by JS. Basically, JS sends us a hierarchy of nodes that, while easy to reason * about in JS, are very inefficient to translate directly to native views. This class sits in - * between {@link UIManagerModule}, which directly receives view commands from JS, and - * {@link UIViewOperationQueue}, which enqueues actual operations on the native view hierarchy. It - * is able to take instructions from UIManagerModule and output instructions to the native view - * hierarchy that achieve the same displayed UI but with fewer views. + * between {@link UIManagerModule}, which directly receives view commands from JS, and {@link + * UIViewOperationQueue}, which enqueues actual operations on the native view hierarchy. It is able + * to take instructions from UIManagerModule and output instructions to the native view hierarchy + * that achieve the same displayed UI but with fewer views. * - * Currently this class is only used to remove layout-only views, that is to say views that only + *

Currently this class is only used to remove layout-only views, that is to say views that only * affect the positions of their children but do not draw anything themselves. These views are * fairly common because 1) containers are used to do layouting via flexbox and 2) the return of * each Component#render() call in JS must be exactly one view, which means views are often wrapped * in a unnecessary layer of hierarchy. * - * This optimization is implemented by keeping track of both the unoptimized JS hierarchy and the + *

This optimization is implemented by keeping track of both the unoptimized JS hierarchy and the * optimized native hierarchy in {@link ReactShadowNode}. * - * This optimization is important for view hierarchy depth (which can cause stack overflows during - * view traversal for complex apps), memory usage, amount of time spent during GCs, - * and time-to-display. + *

This optimization is important for view hierarchy depth (which can cause stack overflows + * during view traversal for complex apps), memory usage, amount of time spent during GCs, and + * time-to-display. * - * Some examples of the optimizations this class will do based on commands from JS: - * - Create a view with only layout props: a description of that view is created as a - * {@link ReactShadowNode} in UIManagerModule, but this class will not output any commands to - * create the view in the native view hierarchy. - * - Update a layout-only view to have non-layout props: before issuing the updateShadowNode call - * to the native view hierarchy, issue commands to create the view we optimized away move it into - * the view hierarchy - * - Manage the children of a view: multiple manageChildren calls for various parent views may be - * issued to the native view hierarchy depending on where the views being added/removed are - * attached in the optimized hierarchy + *

Some examples of the optimizations this class will do based on commands from JS: - Create a + * view with only layout props: a description of that view is created as a {@link ReactShadowNode} + * in UIManagerModule, but this class will not output any commands to create the view in the native + * view hierarchy. - Update a layout-only view to have non-layout props: before issuing the + * updateShadowNode call to the native view hierarchy, issue commands to create the view we + * optimized away move it into the view hierarchy - Manage the children of a view: multiple + * manageChildren calls for various parent views may be issued to the native view hierarchy + * depending on where the views being added/removed are attached in the optimized hierarchy */ public class NativeViewHierarchyOptimizer { @@ -74,15 +71,12 @@ public class NativeViewHierarchyOptimizer { } public NativeViewHierarchyOptimizer( - UIViewOperationQueue uiViewOperationQueue, - ShadowNodeRegistry shadowNodeRegistry) { + UIViewOperationQueue uiViewOperationQueue, ShadowNodeRegistry shadowNodeRegistry) { mUIViewOperationQueue = uiViewOperationQueue; mShadowNodeRegistry = shadowNodeRegistry; } - /** - * Handles a createView call. May or may not actually create a native view. - */ + /** Handles a createView call. May or may not actually create a native view. */ public void handleCreateView( ReactShadowNode node, ThemedReactContext themedContext, @@ -91,42 +85,32 @@ public class NativeViewHierarchyOptimizer { assertNodeSupportedWithoutOptimizer(node); int tag = node.getReactTag(); mUIViewOperationQueue.enqueueCreateView( - themedContext, - tag, - node.getViewClass(), - initialProps); + themedContext, tag, node.getViewClass(), initialProps); return; } - boolean isLayoutOnly = node.getViewClass().equals(ViewProps.VIEW_CLASS_NAME) && - isLayoutOnlyAndCollapsable(initialProps); + boolean isLayoutOnly = + node.getViewClass().equals(ViewProps.VIEW_CLASS_NAME) + && isLayoutOnlyAndCollapsable(initialProps); node.setIsLayoutOnly(isLayoutOnly); if (node.getNativeKind() != NativeKind.NONE) { mUIViewOperationQueue.enqueueCreateView( - themedContext, - node.getReactTag(), - node.getViewClass(), - initialProps); + themedContext, node.getReactTag(), node.getViewClass(), initialProps); } } - /** - * Handles native children cleanup when css node is removed from hierarchy - */ + /** Handles native children cleanup when css node is removed from hierarchy */ public static void handleRemoveNode(ReactShadowNode node) { node.removeAllNativeChildren(); } /** * Handles an updateView call. If a view transitions from being layout-only to not (or vice-versa) - * this could result in some number of additional createView and manageChildren calls. If the - * view is layout only, no updateView call will be dispatched to the native hierarchy. + * this could result in some number of additional createView and manageChildren calls. If the view + * is layout only, no updateView call will be dispatched to the native hierarchy. */ - public void handleUpdateView( - ReactShadowNode node, - String className, - ReactStylesDiffMap props) { + public void handleUpdateView(ReactShadowNode node, String className, ReactStylesDiffMap props) { if (!ENABLED) { assertNodeSupportedWithoutOptimizer(node); mUIViewOperationQueue.enqueueUpdateProperties(node.getReactTag(), className, props); @@ -145,11 +129,11 @@ public class NativeViewHierarchyOptimizer { * Handles a manageChildren call. This may translate into multiple manageChildren calls for * multiple other views. * - * NB: the assumption for calling this method is that all corresponding ReactShadowNodes have - * been updated **but tagsToDelete have NOT been deleted yet**. This is because we need to use - * the metadata from those nodes to figure out the correct commands to dispatch. This is unlike - * all other calls on this class where we assume all operations on the shadow hierarchy have - * already completed by the time a corresponding method here is called. + *

NB: the assumption for calling this method is that all corresponding ReactShadowNodes have + * been updated **but tagsToDelete have NOT been deleted yet**. This is because we need to use the + * metadata from those nodes to figure out the correct commands to dispatch. This is unlike all + * other calls on this class where we assume all operations on the shadow hierarchy have already + * completed by the time a corresponding method here is called. */ public void handleManageChildren( ReactShadowNode nodeToManage, @@ -161,11 +145,7 @@ public class NativeViewHierarchyOptimizer { if (!ENABLED) { assertNodeSupportedWithoutOptimizer(nodeToManage); mUIViewOperationQueue.enqueueManageChildren( - nodeToManage.getReactTag(), - indicesToRemove, - viewsToAdd, - tagsToDelete, - indicesToDelete); + nodeToManage.getReactTag(), indicesToRemove, viewsToAdd, tagsToDelete, indicesToDelete); return; } @@ -193,18 +173,13 @@ public class NativeViewHierarchyOptimizer { } /** - * Handles a setChildren call. This is a simplification of handleManagerChildren that only adds + * Handles a setChildren call. This is a simplification of handleManagerChildren that only adds * children in index order of the childrenTags array */ - public void handleSetChildren( - ReactShadowNode nodeToManage, - ReadableArray childrenTags - ) { + public void handleSetChildren(ReactShadowNode nodeToManage, ReadableArray childrenTags) { if (!ENABLED) { assertNodeSupportedWithoutOptimizer(nodeToManage); - mUIViewOperationQueue.enqueueSetChildren( - nodeToManage.getReactTag(), - childrenTags); + mUIViewOperationQueue.enqueueSetChildren(nodeToManage.getReactTag(), childrenTags); return; } @@ -215,9 +190,9 @@ public class NativeViewHierarchyOptimizer { } /** - * Handles an updateLayout call. All updateLayout calls are collected and dispatched at the end - * of a batch because updateLayout calls to layout-only nodes can necessitate multiple - * updateLayout calls for all its children. + * Handles an updateLayout call. All updateLayout calls are collected and dispatched at the end of + * a batch because updateLayout calls to layout-only nodes can necessitate multiple updateLayout + * calls for all its children. */ public void handleUpdateLayout(ReactShadowNode node) { if (!ENABLED) { @@ -250,17 +225,17 @@ public class NativeViewHierarchyOptimizer { } private NodeIndexPair walkUpUntilNativeKindIsParent( - ReactShadowNode node, - int indexInNativeChildren) { + ReactShadowNode node, int indexInNativeChildren) { while (node.getNativeKind() != NativeKind.PARENT) { ReactShadowNode parent = node.getParent(); if (parent == null) { return null; } - indexInNativeChildren = indexInNativeChildren + - (node.getNativeKind() == NativeKind.LEAF ? 1 : 0) + - parent.getNativeOffsetForChild(node); + indexInNativeChildren = + indexInNativeChildren + + (node.getNativeKind() == NativeKind.LEAF ? 1 : 0) + + parent.getNativeOffsetForChild(node); node = parent; } @@ -314,16 +289,11 @@ public class NativeViewHierarchyOptimizer { } private void addNonNativeChild( - ReactShadowNode nativeParent, - ReactShadowNode nonNativeChild, - int index) { + ReactShadowNode nativeParent, ReactShadowNode nonNativeChild, int index) { addGrandchildren(nativeParent, nonNativeChild, index); } - private void addNativeChild( - ReactShadowNode parent, - ReactShadowNode child, - int index) { + private void addNativeChild(ReactShadowNode parent, ReactShadowNode child, int index) { parent.addNativeChildAt(child, index); mUIViewOperationQueue.enqueueManageChildren( parent.getReactTag(), @@ -337,10 +307,7 @@ public class NativeViewHierarchyOptimizer { } } - private void addGrandchildren( - ReactShadowNode nativeParent, - ReactShadowNode child, - int index) { + private void addGrandchildren(ReactShadowNode nativeParent, ReactShadowNode child, int index) { Assertions.assertCondition(child.getNativeKind() != NativeKind.PARENT); // `child` can't hold native children. Add all of `child`'s children to `parent`. @@ -425,8 +392,7 @@ public class NativeViewHierarchyOptimizer { } private void transitionLayoutOnlyViewToNativeView( - ReactShadowNode node, - @Nullable ReactStylesDiffMap props) { + ReactShadowNode node, @Nullable ReactStylesDiffMap props) { ReactShadowNode parent = node.getParent(); if (parent == null) { node.setIsLayoutOnly(false); @@ -444,10 +410,7 @@ public class NativeViewHierarchyOptimizer { // Create the view since it doesn't exist in the native hierarchy yet mUIViewOperationQueue.enqueueCreateView( - node.getThemedContext(), - node.getReactTag(), - node.getViewClass(), - props); + node.getThemedContext(), node.getReactTag(), node.getViewClass(), props); // Add the node and all its children as if we are adding a new nodes parent.addChildAt(node, childIndex); diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/NoSuchNativeViewException.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/NoSuchNativeViewException.java index 22e13d6717b..e5df832edcf 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/NoSuchNativeViewException.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/NoSuchNativeViewException.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; /** diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/OnLayoutEvent.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/OnLayoutEvent.java index 459d3407b44..6d16c0e948c 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/OnLayoutEvent.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/OnLayoutEvent.java @@ -1,22 +1,18 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; import androidx.core.util.Pools; - import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.WritableMap; import com.facebook.react.uimanager.events.Event; import com.facebook.react.uimanager.events.RCTEventEmitter; -/** - * Event used to notify JS component about changes of its position or dimensions - */ +/** Event used to notify JS component about changes of its position or dimensions */ public class OnLayoutEvent extends Event { private static final Pools.SynchronizedPool EVENTS_POOL = @@ -38,8 +34,7 @@ public class OnLayoutEvent extends Event { EVENTS_POOL.release(this); } - private OnLayoutEvent() { - } + private OnLayoutEvent() {} protected void init(int viewTag, int x, int y, int width, int height) { super.init(viewTag); diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/PixelUtil.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/PixelUtil.java index c5765bc2448..0821a26a666 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/PixelUtil.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/PixelUtil.java @@ -1,54 +1,39 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; import android.util.DisplayMetrics; import android.util.TypedValue; -/** - * Android dp to pixel manipulation - */ +/** Android dp to pixel manipulation */ public class PixelUtil { - /** - * Convert from DIP to PX - */ + /** Convert from DIP to PX */ public static float toPixelFromDIP(float value) { return TypedValue.applyDimension( - TypedValue.COMPLEX_UNIT_DIP, - value, - DisplayMetricsHolder.getWindowDisplayMetrics()); + TypedValue.COMPLEX_UNIT_DIP, value, DisplayMetricsHolder.getWindowDisplayMetrics()); } - /** - * Convert from DIP to PX - */ + /** Convert from DIP to PX */ public static float toPixelFromDIP(double value) { return toPixelFromDIP((float) value); } - /** - * Convert from PX to SP - */ + /** Convert from PX to SP */ public static float toSPFromPixel(float value) { return value / DisplayMetricsHolder.getScreenDisplayMetrics().scaledDensity; } - /** - * Convert from SP to PX - */ + /** Convert from SP to PX */ public static float toPixelFromSP(float value) { return toPixelFromSP(value, Float.NaN); } - /** - * Convert from SP to PX - */ + /** Convert from SP to PX */ public static float toPixelFromSP(float value, float maxFontScale) { DisplayMetrics displayMetrics = DisplayMetricsHolder.getWindowDisplayMetrics(); float scaledDensity = displayMetrics.scaledDensity; @@ -60,25 +45,18 @@ public class PixelUtil { return value * scaledDensity; } - /** - * Convert from SP to PX - */ + /** Convert from SP to PX */ public static float toPixelFromSP(double value) { return toPixelFromSP((float) value); } - /** - * Convert from PX to DP - */ + /** Convert from PX to DP */ public static float toDIPFromPixel(float value) { return value / DisplayMetricsHolder.getWindowDisplayMetrics().density; } - /** - * @return {@link float} that represents the density of the display metrics for device screen. - */ + /** @return {@link float} that represents the density of the display metrics for device screen. */ public static float getDisplayMetricDensity() { return DisplayMetricsHolder.getScreenDisplayMetrics().density; } - } diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/PointerEvents.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/PointerEvents.java index 0be5d8f6ee3..98d193758b6 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/PointerEvents.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/PointerEvents.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; /** @@ -13,24 +12,16 @@ package com.facebook.react.uimanager; */ public enum PointerEvents { - /** - * Neither the container nor its children receive events. - */ + /** Neither the container nor its children receive events. */ NONE, - /** - * Container doesn't get events but all of its children do. - */ + /** Container doesn't get events but all of its children do. */ BOX_NONE, - /** - * Container gets events but none of its children do. - */ + /** Container gets events but none of its children do. */ BOX_ONLY, - /** - * Container and all of its children receive touch events (like pointerEvents is unspecified). - */ + /** Container and all of its children receive touch events (like pointerEvents is unspecified). */ AUTO, ; } diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactAccessibilityDelegate.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactAccessibilityDelegate.java index 332114fca6a..4f22b9f5e38 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactAccessibilityDelegate.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactAccessibilityDelegate.java @@ -5,22 +5,17 @@ package com.facebook.react.uimanager; -import android.os.Bundle; import android.content.Context; +import android.os.Bundle; +import android.text.SpannableString; +import android.text.style.URLSpan; +import android.util.Log; +import android.view.View; import androidx.core.view.AccessibilityDelegateCompat; import androidx.core.view.ViewCompat; import androidx.core.view.accessibility.AccessibilityNodeInfoCompat; import androidx.core.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityActionCompat; -import androidx.core.view.accessibility.AccessibilityNodeInfoCompat.CollectionItemInfoCompat; -import android.text.SpannableString; -import android.text.style.URLSpan; -import androidx.core.view.AccessibilityDelegateCompat; -import androidx.core.view.ViewCompat; -import androidx.core.view.accessibility.AccessibilityNodeInfoCompat; -import androidx.core.view.accessibility.AccessibilityNodeInfoCompat.CollectionItemInfoCompat; -import android.util.Log; -import android.view.View; - +import com.facebook.react.R; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.Dynamic; import com.facebook.react.bridge.ReactContext; @@ -30,43 +25,61 @@ import com.facebook.react.bridge.ReadableMapKeySetIterator; import com.facebook.react.bridge.ReadableType; import com.facebook.react.bridge.WritableMap; import com.facebook.react.uimanager.events.RCTEventEmitter; -import com.facebook.react.R; - import java.util.HashMap; -import java.util.Locale; import javax.annotation.Nullable; /** - * Utility class that handles the addition of a "role" for accessibility to - * either a View or AccessibilityNodeInfo. + * Utility class that handles the addition of a "role" for accessibility to either a View or + * AccessibilityNodeInfo. */ - public class ReactAccessibilityDelegate extends AccessibilityDelegateCompat { private static final String TAG = "ReactAccessibilityDelegate"; private static int sCounter = 0x3f000000; - public static final HashMap sActionIdMap= new HashMap<>(); + public static final HashMap sActionIdMap = new HashMap<>(); + static { sActionIdMap.put("activate", AccessibilityActionCompat.ACTION_CLICK.getId()); sActionIdMap.put("longpress", AccessibilityActionCompat.ACTION_LONG_CLICK.getId()); sActionIdMap.put("increment", AccessibilityActionCompat.ACTION_SCROLL_FORWARD.getId()); - sActionIdMap.put("decrement", AccessibilityActionCompat.ACTION_SCROLL_BACKWARD.getId()); + sActionIdMap.put("decrement", AccessibilityActionCompat.ACTION_SCROLL_BACKWARD.getId()); } /** - * These roles are defined by Google's TalkBack screen reader, and this list - * should be kept up to date with their implementation. Details can be seen in - * their source code here: + * These roles are defined by Google's TalkBack screen reader, and this list should be kept up to + * date with their implementation. Details can be seen in their source code here: * - *

- * https://github.com/google/talkback/blob/master/utils/src/main/java/Role.java + *

https://github.com/google/talkback/blob/master/utils/src/main/java/Role.java */ - public enum AccessibilityRole { - NONE, BUTTON, LINK, SEARCH, IMAGE, IMAGEBUTTON, KEYBOARDKEY, TEXT, ADJUSTABLE, SUMMARY, HEADER, ALERT, CHECKBOX, - COMBOBOX, MENU, MENUBAR, MENUITEM, PROGRESSBAR, RADIO, RADIOGROUP, SCROLLBAR, SPINBUTTON, - SWITCH, TAB, TABLIST, TIMER, TOOLBAR; + NONE, + BUTTON, + LINK, + SEARCH, + IMAGE, + IMAGEBUTTON, + KEYBOARDKEY, + TEXT, + ADJUSTABLE, + SUMMARY, + HEADER, + ALERT, + CHECKBOX, + COMBOBOX, + MENU, + MENUBAR, + MENUITEM, + PROGRESSBAR, + RADIO, + RADIOGROUP, + SCROLLBAR, + SPINBUTTON, + SWITCH, + TAB, + TABLIST, + TIMER, + TOOLBAR; public static String getValue(AccessibilityRole role) { switch (role) { @@ -140,13 +153,15 @@ public class ReactAccessibilityDelegate extends AccessibilityDelegateCompat { @Override public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfoCompat info) { super.onInitializeAccessibilityNodeInfo(host, info); - final AccessibilityRole accessibilityRole = (AccessibilityRole) host.getTag(R.id.accessibility_role); + final AccessibilityRole accessibilityRole = + (AccessibilityRole) host.getTag(R.id.accessibility_role); if (accessibilityRole != null) { setRole(info, accessibilityRole, host.getContext()); } // states are changable. - final ReadableArray accessibilityStates = (ReadableArray) host.getTag(R.id.accessibility_states); + final ReadableArray accessibilityStates = + (ReadableArray) host.getTag(R.id.accessibility_states); final ReadableMap accessibilityState = (ReadableMap) host.getTag(R.id.accessibility_state); if (accessibilityStates != null) { setStates(info, accessibilityStates, host.getContext()); @@ -154,7 +169,8 @@ public class ReactAccessibilityDelegate extends AccessibilityDelegateCompat { if (accessibilityState != null) { setState(info, accessibilityState, host.getContext()); } - final ReadableArray accessibilityActions = (ReadableArray) host.getTag(R.id.accessibility_actions); + final ReadableArray accessibilityActions = + (ReadableArray) host.getTag(R.id.accessibility_actions); if (accessibilityActions != null) { for (int i = 0; i < accessibilityActions.size(); i++) { final ReadableMap action = accessibilityActions.getMap(i); @@ -169,7 +185,8 @@ public class ReactAccessibilityDelegate extends AccessibilityDelegateCompat { sCounter++; } mAccessibilityActionsMap.put(actionId, action.getString("name")); - final AccessibilityActionCompat accessibilityAction = new AccessibilityActionCompat(actionId, actionLabel); + final AccessibilityActionCompat accessibilityAction = + new AccessibilityActionCompat(actionId, actionLabel); info.addAction(accessibilityAction); } } @@ -180,17 +197,17 @@ public class ReactAccessibilityDelegate extends AccessibilityDelegateCompat { if (mAccessibilityActionsMap.containsKey(action)) { final WritableMap event = Arguments.createMap(); event.putString("actionName", mAccessibilityActionsMap.get(action)); - ReactContext reactContext = (ReactContext)host.getContext(); - reactContext.getJSModule(RCTEventEmitter.class).receiveEvent( - host.getId(), - "topAccessibilityAction", - event); + ReactContext reactContext = (ReactContext) host.getContext(); + reactContext + .getJSModule(RCTEventEmitter.class) + .receiveEvent(host.getId(), "topAccessibilityAction", event); return true; } return super.performAccessibilityAction(host, action, args); } - private static void setStates(AccessibilityNodeInfoCompat info, ReadableArray accessibilityStates, Context context) { + private static void setStates( + AccessibilityNodeInfoCompat info, ReadableArray accessibilityStates, Context context) { for (int i = 0; i < accessibilityStates.size(); i++) { String state = accessibilityStates.getString(i); switch (state) { @@ -217,8 +234,9 @@ public class ReactAccessibilityDelegate extends AccessibilityDelegateCompat { } } } - - private static void setState(AccessibilityNodeInfoCompat info, ReadableMap accessibilityState, Context context) { + + private static void setState( + AccessibilityNodeInfoCompat info, ReadableMap accessibilityState, Context context) { Log.d(TAG, "setState " + accessibilityState); final ReadableMapKeySetIterator i = accessibilityState.keySetIterator(); while (i.hasNextKey()) { @@ -233,19 +251,20 @@ public class ReactAccessibilityDelegate extends AccessibilityDelegateCompat { info.setCheckable(true); info.setChecked(boolValue); if (info.getClassName().equals(AccessibilityRole.getValue(AccessibilityRole.SWITCH))) { - info.setText(context.getString(boolValue ? R.string.state_on_description : R.string.state_off_description)); + info.setText( + context.getString( + boolValue ? R.string.state_on_description : R.string.state_off_description)); } } } } - /** - * Strings for setting the Role Description in english - */ + /** Strings for setting the Role Description in english */ // TODO: Eventually support for other languages on talkback - public static void setRole(AccessibilityNodeInfoCompat nodeInfo, AccessibilityRole role, final Context context) { + public static void setRole( + AccessibilityNodeInfoCompat nodeInfo, AccessibilityRole role, final Context context) { if (role == null) { role = AccessibilityRole.NONE; } @@ -276,7 +295,7 @@ public class ReactAccessibilityDelegate extends AccessibilityDelegateCompat { } else if (role.equals(AccessibilityRole.HEADER)) { nodeInfo.setRoleDescription(context.getString(R.string.header_description)); final AccessibilityNodeInfoCompat.CollectionItemInfoCompat itemInfo = - AccessibilityNodeInfoCompat.CollectionItemInfoCompat.obtain(0, 1, 0, 1, true); + AccessibilityNodeInfoCompat.CollectionItemInfoCompat.obtain(0, 1, 0, 1, true); nodeInfo.setCollectionItemInfo(itemInfo); } else if (role.equals(AccessibilityRole.ALERT)) { nodeInfo.setRoleDescription(context.getString(R.string.alert_description)); @@ -312,10 +331,10 @@ public class ReactAccessibilityDelegate extends AccessibilityDelegateCompat { // problems, // so leave it alone. if (!ViewCompat.hasAccessibilityDelegate(view) - && (view.getTag(R.id.accessibility_role) != null || - view.getTag(R.id.accessibility_states) != null || - view.getTag(R.id.accessibility_state) != null || - view.getTag(R.id.accessibility_actions) != null)) { + && (view.getTag(R.id.accessibility_role) != null + || view.getTag(R.id.accessibility_states) != null + || view.getTag(R.id.accessibility_state) != null + || view.getTag(R.id.accessibility_actions) != null)) { ViewCompat.setAccessibilityDelegate(view, new ReactAccessibilityDelegate()); } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactClippingViewGroup.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactClippingViewGroup.java index 04dd014e7c4..2c4fbf2f4f1 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactClippingViewGroup.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactClippingViewGroup.java @@ -1,22 +1,21 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; import android.graphics.Rect; import android.view.View; /** - * Interface that should be implemented by {@link View} subclasses that support - * {@code removeClippedSubviews} property. When this property is set for the {@link ViewGroup} - * subclass it's responsible for detaching it's child views that are clipped by the view boundaries. - * Those view boundaries should be determined based on it's parent clipping area and current view's - * offset in parent and doesn't necessarily reflect the view visible area (in a sense of a value - * that {@link View#getGlobalVisibleRect} may return). In order to determine the clipping rect for + * Interface that should be implemented by {@link View} subclasses that support {@code + * removeClippedSubviews} property. When this property is set for the {@link ViewGroup} subclass + * it's responsible for detaching it's child views that are clipped by the view boundaries. Those + * view boundaries should be determined based on it's parent clipping area and current view's offset + * in parent and doesn't necessarily reflect the view visible area (in a sense of a value that + * {@link View#getGlobalVisibleRect} may return). In order to determine the clipping rect for * current view helper method {@link ReactClippingViewGroupHelper#calculateClippingRect} can be used * that takes into account parent view settings. */ @@ -24,13 +23,13 @@ public interface ReactClippingViewGroup { /** * Notify view that clipping area may have changed and it should recalculate the list of children - * that should be attached/detached. This method should be called only when property - * {@code removeClippedSubviews} is set to {@code true} on a view. + * that should be attached/detached. This method should be called only when property {@code + * removeClippedSubviews} is set to {@code true} on a view. * - * CAUTION: Views are responsible for calling {@link #updateClippingRect} on it's children. This - * should happen if child implement {@link ReactClippingViewGroup}, return true from - * {@link #getRemoveClippedSubviews} and clipping rect change of the current view may affect - * clipping rect of this child. + *

CAUTION: Views are responsible for calling {@link #updateClippingRect} on it's children. + * This should happen if child implement {@link ReactClippingViewGroup}, return true from {@link + * #getRemoveClippedSubviews} and clipping rect change of the current view may affect clipping + * rect of this child. */ void updateClippingRect(); @@ -46,14 +45,12 @@ public interface ReactClippingViewGroup { * Sets property {@code removeClippedSubviews} as a result of property update in JS. Should be * called only from @{link ViewManager#updateView} method. * - * Helper method {@link ReactClippingViewGroupHelper#applyRemoveClippedSubviewsProperty} may be - * used by {@link ViewManager} subclass to apply this property based on property update map - * {@link ReactStylesDiffMap}. + *

Helper method {@link ReactClippingViewGroupHelper#applyRemoveClippedSubviewsProperty} may be + * used by {@link ViewManager} subclass to apply this property based on property update map {@link + * ReactStylesDiffMap}. */ void setRemoveClippedSubviews(boolean removeClippedSubviews); - /** - * Get the current value of {@code removeClippedSubviews} property. - */ + /** Get the current value of {@code removeClippedSubviews} property. */ boolean getRemoveClippedSubviews(); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactClippingViewGroupHelper.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactClippingViewGroupHelper.java index c5d9ab6a51a..78e51eaa21b 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactClippingViewGroupHelper.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactClippingViewGroupHelper.java @@ -1,21 +1,19 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; -import javax.annotation.concurrent.NotThreadSafe; - import android.graphics.Rect; import android.view.View; import android.view.ViewParent; +import javax.annotation.concurrent.NotThreadSafe; /** - * Provides implementation of common tasks for view and it's view manager supporting property - * {@code removeClippedSubviews}. + * Provides implementation of common tasks for view and it's view manager supporting property {@code + * removeClippedSubviews}. */ @NotThreadSafe public class ReactClippingViewGroupHelper { @@ -26,8 +24,8 @@ public class ReactClippingViewGroupHelper { /** * Can be used by view that support {@code removeClippedSubviews} property to calculate area that - * given {@param view} should be clipped to based on the clipping rectangle of it's parent in - * case when parent is also set to clip it's children. + * given {@param view} should be clipped to based on the clipping rectangle of it's parent in case + * when parent is also set to clip it's children. * * @param view view that we want to calculate clipping rect for * @param outputRect where the calculated rectangle will be written @@ -43,7 +41,8 @@ public class ReactClippingViewGroupHelper { clippingViewGroup.getClippingRect(sHelperRect); // Intersect the view with the parent's rectangle // This will result in the overlap with coordinates in the parent space - if (!sHelperRect.intersect(view.getLeft(), view.getTop(), view.getRight(), view.getBottom())) { + if (!sHelperRect.intersect( + view.getLeft(), view.getTop(), view.getRight(), view.getBottom())) { outputRect.setEmpty(); return; } diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactCompoundView.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactCompoundView.java index 5c421b481ab..681689584fe 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactCompoundView.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactCompoundView.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; import android.view.View; @@ -18,6 +17,7 @@ public interface ReactCompoundView { /** * Return react tag for touched element. Event coordinates are relative to the view + * * @param touchX the X touch coordinate relative to the view * @param touchY the Y touch coordinate relative to the view */ diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactCompoundViewGroup.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactCompoundViewGroup.java index eb6c3e53de6..8c0e01b77ad 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactCompoundViewGroup.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactCompoundViewGroup.java @@ -1,22 +1,21 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; /** - * This interface should be implemented be native ViewGroup subclasses that can represent more - * than a single react node. In that case, virtual and non-virtual (mapping to a View) elements - * can overlap, and TouchTargetHelper may incorrectly dispatch touch event to a wrong element - * because it priorities children over parents. + * This interface should be implemented be native ViewGroup subclasses that can represent more than + * a single react node. In that case, virtual and non-virtual (mapping to a View) elements can + * overlap, and TouchTargetHelper may incorrectly dispatch touch event to a wrong element because it + * priorities children over parents. */ public interface ReactCompoundViewGroup extends ReactCompoundView { /** - * Returns true if react node responsible for the touch even is flattened into this ViewGroup. - * Use reactTagForTouch() to get its tag. + * Returns true if react node responsible for the touch even is flattened into this ViewGroup. Use + * reactTagForTouch() to get its tag. */ boolean interceptsTouchEvent(float touchX, float touchY); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactInvalidPropertyException.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactInvalidPropertyException.java index 695225b550e..53af2e18952 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactInvalidPropertyException.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactInvalidPropertyException.java @@ -1,16 +1,20 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; public class ReactInvalidPropertyException extends RuntimeException { public ReactInvalidPropertyException(String property, String value, String expectedValues) { - super("Invalid React property `" + property + "` with value `" + value + - "`, expected " + expectedValues); + super( + "Invalid React property `" + + property + + "` with value `" + + value + + "`, expected " + + expectedValues); } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactPointerEventsView.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactPointerEventsView.java index 477ef86e36d..e2075020325 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactPointerEventsView.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactPointerEventsView.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; import android.view.View; @@ -15,8 +14,6 @@ import android.view.View; */ public interface ReactPointerEventsView { - /** - * Return the PointerEvents of the View. - */ + /** Return the PointerEvents of the View. */ PointerEvents getPointerEvents(); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactRoot.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactRoot.java index 67db0299266..0213241d549 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactRoot.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactRoot.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; import android.os.Bundle; @@ -12,51 +11,40 @@ import android.view.ViewGroup; import com.facebook.react.uimanager.common.UIManagerType; import javax.annotation.Nullable; - -/** - * Interface for the root native view of a React native application - */ +/** Interface for the root native view of a React native application */ public interface ReactRoot { - /** - * Return cached launch properties for app - */ - @Nullable Bundle getAppProperties(); - @Nullable String getInitialUITemplate(); + /** Return cached launch properties for app */ + @Nullable + Bundle getAppProperties(); + + @Nullable + String getInitialUITemplate(); + String getJSModuleName(); - /** - * Fabric or Default UI Manager, see {@link UIManagerType} - */ - @UIManagerType int getUIManagerType(); + /** Fabric or Default UI Manager, see {@link UIManagerType} */ + @UIManagerType + int getUIManagerType(); int getRootViewTag(); void setRootViewTag(int rootViewTag); - /** - * Calls into JS to start the React application. - */ + /** Calls into JS to start the React application. */ void runApplication(); - /** - * Handler for stages {@link com.facebook.react.surface.ReactStage} - */ + /** Handler for stages {@link com.facebook.react.surface.ReactStage} */ void onStage(int stage); - /** - * Return native view for root - */ + /** Return native view for root */ ViewGroup getRootViewGroup(); - /** - * @return Cached values for widthMeasureSpec and heightMeasureSpec - */ + /** @return Cached values for widthMeasureSpec and heightMeasureSpec */ int getWidthMeasureSpec(); + int getHeightMeasureSpec(); - /** - * Sets a flag that determines whether to log that content appeared on next view added. - */ + /** Sets a flag that determines whether to log that content appeared on next view added. */ void setShouldLogContentAppeared(boolean shouldLogContentAppeared); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactShadowNode.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactShadowNode.java index 50c7140466b..dff922db8a2 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactShadowNode.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactShadowNode.java @@ -1,8 +1,8 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ package com.facebook.react.uimanager; @@ -18,7 +18,6 @@ import com.facebook.yoga.YogaOverflow; import com.facebook.yoga.YogaPositionType; import com.facebook.yoga.YogaValue; import com.facebook.yoga.YogaWrap; -import java.util.List; import javax.annotation.Nullable; /** diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactShadowNodeImpl.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactShadowNodeImpl.java index 47a2a7157e4..172df19ca72 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactShadowNodeImpl.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactShadowNodeImpl.java @@ -1,8 +1,8 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ package com.facebook.react.uimanager; @@ -234,7 +234,7 @@ public class ReactShadowNodeImpl implements ReactShadowNode public ReactShadowNodeImpl removeChildAt(int i) { if (mChildren == null) { throw new ArrayIndexOutOfBoundsException( - "Index " + i + " out of bounds: node has no children"); + "Index " + i + " out of bounds: node has no children"); } ReactShadowNodeImpl removed = mChildren.remove(i); removed.mParent = null; @@ -259,7 +259,7 @@ public class ReactShadowNodeImpl implements ReactShadowNode public final ReactShadowNodeImpl getChildAt(int i) { if (mChildren == null) { throw new ArrayIndexOutOfBoundsException( - "Index " + i + " out of bounds: node has no children"); + "Index " + i + " out of bounds: node has no children"); } return mChildren.get(i); } @@ -311,8 +311,7 @@ public class ReactShadowNodeImpl implements ReactShadowNode * require layouting (marked with {@link #dirty()}). */ @Override - public void onBeforeLayout(NativeViewHierarchyOptimizer nativeViewHierarchyOptimizer) { - } + public void onBeforeLayout(NativeViewHierarchyOptimizer nativeViewHierarchyOptimizer) {} @Override public final void updateProperties(ReactStylesDiffMap props) { @@ -371,17 +370,17 @@ public class ReactShadowNodeImpl implements ReactShadowNode mScreenHeight = newScreenHeight; if (layoutHasChanged) { - //TODO: T26400974 ReactShadowNode should not depend on nativeViewHierarchyOptimizer + // TODO: T26400974 ReactShadowNode should not depend on nativeViewHierarchyOptimizer if (nativeViewHierarchyOptimizer != null) { nativeViewHierarchyOptimizer.handleUpdateLayout(this); } else { uiViewOperationQueue.enqueueUpdateLayout( - getParent().getReactTag(), - getReactTag(), - getScreenX(), - getScreenY(), - getScreenWidth(), - getScreenHeight()); + getParent().getReactTag(), + getReactTag(), + getScreenX(), + getScreenY(), + getScreenWidth(), + getScreenHeight()); } } @@ -546,10 +545,9 @@ public class ReactShadowNodeImpl implements ReactShadowNode @Override public NativeKind getNativeKind() { - return - isVirtual() || isLayoutOnly() ? NativeKind.NONE : - hoistNativeChildren() ? NativeKind.LEAF : - NativeKind.PARENT; + return isVirtual() || isLayoutOnly() + ? NativeKind.NONE + : hoistNativeChildren() ? NativeKind.LEAF : NativeKind.PARENT; } @Override @@ -577,10 +575,9 @@ public class ReactShadowNodeImpl implements ReactShadowNode private int getTotalNativeNodeContributionToParent() { NativeKind kind = getNativeKind(); - return - kind == NativeKind.NONE ? mTotalNativeChildren : - kind == NativeKind.LEAF ? 1 + mTotalNativeChildren : - 1; // kind == NativeKind.PARENT + return kind == NativeKind.NONE + ? mTotalNativeChildren + : kind == NativeKind.LEAF ? 1 + mTotalNativeChildren : 1; // kind == NativeKind.PARENT } @Override @@ -987,12 +984,24 @@ public class ReactShadowNodeImpl implements ReactShadowNode result.append(" "); } - result.append("<").append(getClass().getSimpleName()).append(" view='").append(getViewClass()) - .append("' tag=").append(getReactTag()); + result + .append("<") + .append(getClass().getSimpleName()) + .append(" view='") + .append(getViewClass()) + .append("' tag=") + .append(getReactTag()); if (mYogaNode != null) { - result.append(" layout='x:").append(getScreenX()) - .append(" y:").append(getScreenY()).append(" w:").append(getLayoutWidth()).append(" h:") - .append(getLayoutHeight()).append("'"); + result + .append(" layout='x:") + .append(getScreenX()) + .append(" y:") + .append(getScreenY()) + .append(" w:") + .append(getLayoutWidth()) + .append(" h:") + .append(getLayoutHeight()) + .append("'"); } else { result.append("(virtual node)"); } @@ -1033,9 +1042,11 @@ public class ReactShadowNodeImpl implements ReactShadowNode @Override public Iterable calculateLayoutOnChildren() { - return isVirtualAnchor() ? + return isVirtualAnchor() + ? // All of the descendants are virtual so none of them are involved in layout. - null : + null + : // Just return the children. Flexbox calculations have already been run on them. mChildren; } diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactStylesDiffMap.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactStylesDiffMap.java index 3f76974779b..b614fb49479 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactStylesDiffMap.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactStylesDiffMap.java @@ -1,39 +1,35 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; -import java.util.HashMap; +import android.view.View; +import com.facebook.react.bridge.Dynamic; +import com.facebook.react.bridge.ReadableArray; +import com.facebook.react.bridge.ReadableMap; import java.util.Map; import javax.annotation.Nullable; -import android.view.View; - -import com.facebook.react.bridge.ReadableArray; -import com.facebook.react.bridge.ReadableMap; -import com.facebook.react.bridge.Dynamic; - /** - * Wrapper for {@link ReadableMap} which should be used for styles property map. It extends - * some of the accessor methods of {@link ReadableMap} by adding a default value property - * such that caller is enforced to provide a default value for a style property. + * Wrapper for {@link ReadableMap} which should be used for styles property map. It extends some of + * the accessor methods of {@link ReadableMap} by adding a default value property such that caller + * is enforced to provide a default value for a style property. * - * Instances of this class are used to update {@link View} or {@link CSSNode} style properties. - * Since properties are generated by React framework based on what has been updated each value - * in this map should either be interpreted as a new value set for a style property or as a "reset - * this property to default" command in case when value is null (this is a way React communicates - * change in which the style key that was previously present in a map has been removed). + *

Instances of this class are used to update {@link View} or {@link CSSNode} style properties. + * Since properties are generated by React framework based on what has been updated each value in + * this map should either be interpreted as a new value set for a style property or as a "reset this + * property to default" command in case when value is null (this is a way React communicates change + * in which the style key that was previously present in a map has been removed). * - * NOTE: Accessor method with default value will throw an exception when the key is not present in - * the map. Style applicator logic should verify whether the key exists in the map using - * {@link #hasKey} before fetching the value. The motivation behind this is that in case when the - * updated style diff map doesn't contain a certain style key it means that the corresponding view - * property shouldn't be updated (whereas in all other cases it should be updated to the new value - * or the property should be reset). + *

NOTE: Accessor method with default value will throw an exception when the key is not present + * in the map. Style applicator logic should verify whether the key exists in the map using {@link + * #hasKey} before fetching the value. The motivation behind this is that in case when the updated + * style diff map doesn't contain a certain style key it means that the corresponding view property + * shouldn't be updated (whereas in all other cases it should be updated to the new value or the + * property should be reset). */ public class ReactStylesDiffMap { @@ -43,7 +39,7 @@ public class ReactStylesDiffMap { mBackingMap = props; } - public Map toMap () { + public Map toMap() { return mBackingMap.toHashMap(); } @@ -64,8 +60,9 @@ public class ReactStylesDiffMap { } public float getFloat(String name, float restoreNullToDefaultValue) { - return mBackingMap.isNull(name) ? - restoreNullToDefaultValue : (float) mBackingMap.getDouble(name); + return mBackingMap.isNull(name) + ? restoreNullToDefaultValue + : (float) mBackingMap.getDouble(name); } public int getInt(String name, int restoreNullToDefaultValue) { diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactYogaConfigProvider.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactYogaConfigProvider.java index 4facdbf2a57..75d77a23b21 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactYogaConfigProvider.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactYogaConfigProvider.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; import com.facebook.yoga.YogaConfig; diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactZIndexedViewGroup.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactZIndexedViewGroup.java index fcd7adeea19..97176b72430 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactZIndexedViewGroup.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactZIndexedViewGroup.java @@ -5,20 +5,19 @@ package com.facebook.react.uimanager; -/** - * ViewGroup that supports z-index. - */ +/** ViewGroup that supports z-index. */ public interface ReactZIndexedViewGroup { /** * Determine the index of a child view at {@param index} considering z-index. + * * @param index The child view index * @return The child view index considering z-index */ int getZIndexMappedChildIndex(int index); /** - * Redraw the view based on updated child z-index. This should be called after updating one of its child - * z-index. + * Redraw the view based on updated child z-index. This should be called after updating one of its + * child z-index. */ void updateDrawingOrder(); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/RootView.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/RootView.java index a74ab492927..c867c877092 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/RootView.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/RootView.java @@ -1,17 +1,14 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; import android.view.MotionEvent; -/** - * Interface for the root native view of a React native application. - */ +/** Interface for the root native view of a React native application. */ public interface RootView { /** diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/RootViewManager.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/RootViewManager.java index a17ef7e1645..911fcca085b 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/RootViewManager.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/RootViewManager.java @@ -1,18 +1,15 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; import android.view.ViewGroup; import android.widget.FrameLayout; -/** - * View manager for ReactRootView components. - */ +/** View manager for ReactRootView components. */ public class RootViewManager extends ViewGroupManager { public static final String REACT_CLASS = "RootView"; diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/RootViewUtil.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/RootViewUtil.java index 7f1e023eb99..ea443c8a9b0 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/RootViewUtil.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/RootViewUtil.java @@ -1,22 +1,18 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; import android.view.View; import android.view.ViewParent; - import com.facebook.infer.annotation.Assertions; public class RootViewUtil { - /** - * Returns the root view of a given view in a react application. - */ + /** Returns the root view of a given view in a react application. */ public static RootView getRootView(View reactView) { View current = reactView; while (true) { diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/ShadowNodeRegistry.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/ShadowNodeRegistry.java index 4ce41a0bb8d..919bd678bbe 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/ShadowNodeRegistry.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/ShadowNodeRegistry.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; import android.util.SparseArray; diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/SimpleViewManager.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/SimpleViewManager.java index fd310c134e7..2b6ff292e9a 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/SimpleViewManager.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/SimpleViewManager.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; import android.view.View; @@ -17,8 +16,8 @@ import android.view.View; * * @param the view handled by this manager */ -public abstract class SimpleViewManager extends - BaseViewManager { +public abstract class SimpleViewManager + extends BaseViewManager { @Override public LayoutShadowNode createShadowNodeInstance() { @@ -31,6 +30,5 @@ public abstract class SimpleViewManager extends } @Override - public void updateExtraData(T root, Object extraData) { - } + public void updateExtraData(T root, Object extraData) {} } diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/Spacing.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/Spacing.java index 899139e5103..34ab984e1b2 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/Spacing.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/Spacing.java @@ -1,14 +1,12 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; import com.facebook.yoga.YogaConstants; - import java.util.Arrays; /** @@ -18,24 +16,17 @@ import java.util.Arrays; */ public class Spacing { - /** - * Spacing type that represents the left direction. E.g. {@code marginLeft}. - */ + /** Spacing type that represents the left direction. E.g. {@code marginLeft}. */ public static final int LEFT = 0; - /** - * Spacing type that represents the top direction. E.g. {@code marginTop}. - */ + /** Spacing type that represents the top direction. E.g. {@code marginTop}. */ public static final int TOP = 1; - /** - * Spacing type that represents the right direction. E.g. {@code marginRight}. - */ + /** Spacing type that represents the right direction. E.g. {@code marginRight}. */ public static final int RIGHT = 2; - /** - * Spacing type that represents the bottom direction. E.g. {@code marginBottom}. - */ + /** Spacing type that represents the bottom direction. E.g. {@code marginBottom}. */ public static final int BOTTOM = 3; /** - * Spacing type that represents start direction e.g. left in left-to-right, right in right-to-left. + * Spacing type that represents start direction e.g. left in left-to-right, right in + * right-to-left. */ public static final int START = 4; /** @@ -43,8 +34,8 @@ public class Spacing { */ public static final int END = 5; /** - * Spacing type that represents horizontal direction (left and right). E.g. - * {@code marginHorizontal}. + * Spacing type that represents horizontal direction (left and right). E.g. {@code + * marginHorizontal}. */ public static final int HORIZONTAL = 6; /** @@ -57,15 +48,8 @@ public class Spacing { public static final int ALL = 8; private static final int[] sFlagsMap = { - 1, /*LEFT*/ - 2, /*TOP*/ - 4, /*RIGHT*/ - 8, /*BOTTOM*/ - 16, /*START*/ - 32, /*END*/ - 64, /*HORIZONTAL*/ - 128, /*VERTICAL*/ - 256, /*ALL*/ + 1, /*LEFT*/ 2, /*TOP*/ 4, /*RIGHT*/ 8, /*BOTTOM*/ 16, /*START*/ 32, /*END*/ 64, /*HORIZONTAL*/ + 128, /*VERTICAL*/ 256, /*ALL*/ }; private final float[] mSpacing; @@ -92,11 +76,11 @@ public class Spacing { /** * Set a spacing value. * - * @param spacingType one of {@link #LEFT}, {@link #TOP}, {@link #RIGHT}, {@link #BOTTOM}, - * {@link #VERTICAL}, {@link #HORIZONTAL}, {@link #ALL} + * @param spacingType one of {@link #LEFT}, {@link #TOP}, {@link #RIGHT}, {@link #BOTTOM}, {@link + * #VERTICAL}, {@link #HORIZONTAL}, {@link #ALL} * @param value the value for this direction * @return {@code true} if the spacing has changed, or {@code false} if the same value was already - * set + * set */ public boolean set(int spacingType, float value) { if (!FloatUtil.floatsEqual(mSpacing[spacingType], value)) { @@ -109,9 +93,9 @@ public class Spacing { } mHasAliasesSet = - (mValueFlags & sFlagsMap[ALL]) != 0 || - (mValueFlags & sFlagsMap[VERTICAL]) != 0 || - (mValueFlags & sFlagsMap[HORIZONTAL]) != 0; + (mValueFlags & sFlagsMap[ALL]) != 0 + || (mValueFlags & sFlagsMap[VERTICAL]) != 0 + || (mValueFlags & sFlagsMap[HORIZONTAL]) != 0; return true; } @@ -125,9 +109,8 @@ public class Spacing { * @param spacingType one of {@link #LEFT}, {@link #TOP}, {@link #RIGHT}, {@link #BOTTOM} */ public float get(int spacingType) { - float defaultValue = (spacingType == START || spacingType == END - ? YogaConstants.UNDEFINED - : mDefaultValue); + float defaultValue = + (spacingType == START || spacingType == END ? YogaConstants.UNDEFINED : mDefaultValue); if (mValueFlags == 0) { return defaultValue; @@ -153,8 +136,8 @@ public class Spacing { * Get the raw value (that was set using {@link #set(int, float)}), without taking into account * any default values. * - * @param spacingType one of {@link #LEFT}, {@link #TOP}, {@link #RIGHT}, {@link #BOTTOM}, - * {@link #VERTICAL}, {@link #HORIZONTAL}, {@link #ALL} + * @param spacingType one of {@link #LEFT}, {@link #TOP}, {@link #RIGHT}, {@link #BOTTOM}, {@link + * #VERTICAL}, {@link #HORIZONTAL}, {@link #ALL} */ public float getRaw(int spacingType) { return mSpacing[spacingType]; @@ -171,28 +154,25 @@ public class Spacing { } /** - * Try to get start value and fallback to given type if not defined. This is used privately - * by the layout engine as a more efficient way to fetch direction-aware values by - * avoid extra method invocations. + * Try to get start value and fallback to given type if not defined. This is used privately by the + * layout engine as a more efficient way to fetch direction-aware values by avoid extra method + * invocations. */ float getWithFallback(int spacingType, int fallbackType) { - return - (mValueFlags & sFlagsMap[spacingType]) != 0 - ? mSpacing[spacingType] - : get(fallbackType); + return (mValueFlags & sFlagsMap[spacingType]) != 0 ? mSpacing[spacingType] : get(fallbackType); } private static float[] newFullSpacingArray() { return new float[] { - YogaConstants.UNDEFINED, - YogaConstants.UNDEFINED, - YogaConstants.UNDEFINED, - YogaConstants.UNDEFINED, - YogaConstants.UNDEFINED, - YogaConstants.UNDEFINED, - YogaConstants.UNDEFINED, - YogaConstants.UNDEFINED, - YogaConstants.UNDEFINED, + YogaConstants.UNDEFINED, + YogaConstants.UNDEFINED, + YogaConstants.UNDEFINED, + YogaConstants.UNDEFINED, + YogaConstants.UNDEFINED, + YogaConstants.UNDEFINED, + YogaConstants.UNDEFINED, + YogaConstants.UNDEFINED, + YogaConstants.UNDEFINED, }; } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/StateWrapper.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/StateWrapper.java index 2f6ba96d847..9b469e87a66 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/StateWrapper.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/StateWrapper.java @@ -10,20 +10,16 @@ import com.facebook.react.bridge.ReadableNativeMap; import com.facebook.react.bridge.WritableMap; /** - * This is a wrapper that can be used for passing State objects from Fabric C++ - * core to platform-specific components in Java. - * State allows you to break out of uni-directional dataflow by calling updateState, - * which communicates state back to the C++ layer. + * This is a wrapper that can be used for passing State objects from Fabric C++ core to + * platform-specific components in Java. State allows you to break out of uni-directional dataflow + * by calling updateState, which communicates state back to the C++ layer. */ public interface StateWrapper { /** - * Get a ReadableNativeMap object from the C++ layer, which is a K/V map of - * string keys to values. + * Get a ReadableNativeMap object from the C++ layer, which is a K/V map of string keys to values. */ ReadableNativeMap getState(); - /** - * Pass a map of values back to the C++ layer. - */ + /** Pass a map of values back to the C++ layer. */ void updateState(WritableMap map); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/ThemedReactContext.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/ThemedReactContext.java index fdeb2c81208..39bafdd73de 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/ThemedReactContext.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/ThemedReactContext.java @@ -1,28 +1,25 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; -import javax.annotation.Nullable; - import android.app.Activity; import android.content.Context; - +import com.facebook.react.bridge.LifecycleEventListener; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContext; -import com.facebook.react.bridge.LifecycleEventListener; +import javax.annotation.Nullable; /** - * Wraps {@link ReactContext} with the base {@link Context} passed into the constructor. - * It provides also a way to start activities using the viewContext to which RN native views belong. - * It delegates lifecycle listener registration to the original instance of {@link ReactContext} - * which is supposed to receive the lifecycle events. At the same time we disallow receiving - * lifecycle events for this wrapper instances. - * TODO: T7538544 Rename ThemedReactContext to be in alignment with name of ReactApplicationContext + * Wraps {@link ReactContext} with the base {@link Context} passed into the constructor. It provides + * also a way to start activities using the viewContext to which RN native views belong. It + * delegates lifecycle listener registration to the original instance of {@link ReactContext} which + * is supposed to receive the lifecycle events. At the same time we disallow receiving lifecycle + * events for this wrapper instances. TODO: T7538544 Rename ThemedReactContext to be in alignment + * with name of ReactApplicationContext */ public class ThemedReactContext extends ReactContext { diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/TouchTargetHelper.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/TouchTargetHelper.java index cee8c4ad7c0..ef808536b25 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/TouchTargetHelper.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/TouchTargetHelper.java @@ -1,28 +1,25 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; -import javax.annotation.Nullable; - import android.graphics.Matrix; import android.graphics.PointF; import android.graphics.Rect; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; - import com.facebook.react.bridge.JSApplicationIllegalArgumentException; import com.facebook.react.bridge.UiThreadUtil; import com.facebook.react.touch.ReactHitSlopView; +import javax.annotation.Nullable; /** - * Class responsible for identifying which react view should handle a given {@link MotionEvent}. - * It uses the event coordinates to traverse the view hierarchy and return a suitable view. + * Class responsible for identifying which react view should handle a given {@link MotionEvent}. It + * uses the event coordinates to traverse the view hierarchy and return a suitable view. */ public class TouchTargetHelper { @@ -32,25 +29,21 @@ public class TouchTargetHelper { private static final Matrix mInverseMatrix = new Matrix(); /** - * Find touch event target view within the provided container given the coordinates provided - * via {@link MotionEvent}. + * Find touch event target view within the provided container given the coordinates provided via + * {@link MotionEvent}. * * @param eventX the X screen coordinate of the touch location * @param eventY the Y screen coordinate of the touch location * @param viewGroup the container view to traverse * @return the react tag ID of the child view that should handle the event */ - public static int findTargetTagForTouch( - float eventX, - float eventY, - ViewGroup viewGroup) { - return findTargetTagAndCoordinatesForTouch( - eventX, eventY, viewGroup, mEventCoords, null); + public static int findTargetTagForTouch(float eventX, float eventY, ViewGroup viewGroup) { + return findTargetTagAndCoordinatesForTouch(eventX, eventY, viewGroup, mEventCoords, null); } /** - * Find touch event target view within the provided container given the coordinates provided - * via {@link MotionEvent}. + * Find touch event target view within the provided container given the coordinates provided via + * {@link MotionEvent}. * * @param eventX the X screen coordinate of the touch location * @param eventY the Y screen coordinate of the touch location @@ -59,17 +52,14 @@ public class TouchTargetHelper { * @return the react tag ID of the child view that should handle the event */ public static int findTargetTagForTouch( - float eventX, - float eventY, - ViewGroup viewGroup, - @Nullable int[] nativeViewId) { + float eventX, float eventY, ViewGroup viewGroup, @Nullable int[] nativeViewId) { return findTargetTagAndCoordinatesForTouch( eventX, eventY, viewGroup, mEventCoords, nativeViewId); } /** - * Find touch event target view within the provided container given the coordinates provided - * via {@link MotionEvent}. + * Find touch event target view within the provided container given the coordinates provided via + * {@link MotionEvent}. * * @param eventX the X screen coordinate of the touch location * @param eventY the Y screen coordinate of the touch location @@ -110,27 +100,28 @@ public class TouchTargetHelper { } /** - * Returns the touch target View that is either viewGroup or one if its descendants. - * This is a recursive DFS since view the entire tree must be parsed until the target is found. - * If the search does not backtrack, it is possible to follow a branch that cannot be a target - * (because of pointerEvents). For example, if both C and E can be the target of an event: - * A (pointerEvents: auto) - B (pointerEvents: box-none) - C (pointerEvents: none) - * \ D (pointerEvents: auto) - E (pointerEvents: auto) - * If the search goes down the first branch, it would return A as the target, which is incorrect. - * NB: This modifies the eventCoords to always be relative to the current viewGroup. When the - * method returns, it will contain the eventCoords relative to the targetView found. + * Returns the touch target View that is either viewGroup or one if its descendants. This is a + * recursive DFS since view the entire tree must be parsed until the target is found. If the + * search does not backtrack, it is possible to follow a branch that cannot be a target (because + * of pointerEvents). For example, if both C and E can be the target of an event: A + * (pointerEvents: auto) - B (pointerEvents: box-none) - C (pointerEvents: none) \ D + * (pointerEvents: auto) - E (pointerEvents: auto) If the search goes down the first branch, it + * would return A as the target, which is incorrect. NB: This modifies the eventCoords to always + * be relative to the current viewGroup. When the method returns, it will contain the eventCoords + * relative to the targetView found. */ private static View findTouchTargetView(float[] eventCoords, ViewGroup viewGroup) { int childrenCount = viewGroup.getChildCount(); // Consider z-index when determining the touch target. - ReactZIndexedViewGroup zIndexedViewGroup = viewGroup instanceof ReactZIndexedViewGroup ? - (ReactZIndexedViewGroup) viewGroup : - null; + ReactZIndexedViewGroup zIndexedViewGroup = + viewGroup instanceof ReactZIndexedViewGroup ? (ReactZIndexedViewGroup) viewGroup : null; for (int i = childrenCount - 1; i >= 0; i--) { - int childIndex = zIndexedViewGroup != null ? zIndexedViewGroup.getZIndexMappedChildIndex(i) : i; + int childIndex = + zIndexedViewGroup != null ? zIndexedViewGroup.getZIndexMappedChildIndex(i) : i; View child = viewGroup.getChildAt(childIndex); PointF childPoint = mTempPoint; - if (isTransformedTouchPointInView(eventCoords[0], eventCoords[1], viewGroup, child, childPoint)) { + if (isTransformedTouchPointInView( + eventCoords[0], eventCoords[1], viewGroup, child, childPoint)) { // If it is contained within the child View, the childPoint value will contain the view // coordinates relative to the child // We need to store the existing X,Y for the viewGroup away as it is possible this child @@ -151,16 +142,12 @@ public class TouchTargetHelper { } /** - * Returns whether the touch point is within the child View - * It is transform aware and will invert the transform Matrix to find the true local points - * This code is taken from {@link ViewGroup#isTransformedTouchPointInView()} + * Returns whether the touch point is within the child View It is transform aware and will invert + * the transform Matrix to find the true local points This code is taken from {@link + * ViewGroup#isTransformedTouchPointInView()} */ private static boolean isTransformedTouchPointInView( - float x, - float y, - ViewGroup parent, - View child, - PointF outLocalPoint) { + float x, float y, ViewGroup parent, View child, PointF outLocalPoint) { float localX = x + parent.getScrollX() - child.getLeft(); float localY = y + parent.getScrollY() - child.getTop(); Matrix matrix = child.getMatrix(); @@ -176,8 +163,10 @@ public class TouchTargetHelper { } if (child instanceof ReactHitSlopView && ((ReactHitSlopView) child).getHitSlopRect() != null) { Rect hitSlopRect = ((ReactHitSlopView) child).getHitSlopRect(); - if ((localX >= -hitSlopRect.left && localX < (child.getRight() - child.getLeft()) + hitSlopRect.right) - && (localY >= -hitSlopRect.top && localY < (child.getBottom() - child.getTop()) + hitSlopRect.bottom)) { + if ((localX >= -hitSlopRect.left + && localX < (child.getRight() - child.getLeft()) + hitSlopRect.right) + && (localY >= -hitSlopRect.top + && localY < (child.getBottom() - child.getTop()) + hitSlopRect.bottom)) { outLocalPoint.set(localX, localY); return true; } @@ -185,7 +174,7 @@ public class TouchTargetHelper { return false; } else { if ((localX >= 0 && localX < (child.getRight() - child.getLeft())) - && (localY >= 0 && localY < (child.getBottom() - child.getTop()))) { + && (localY >= 0 && localY < (child.getBottom() - child.getTop()))) { outLocalPoint.set(localX, localY); return true; } @@ -194,15 +183,16 @@ public class TouchTargetHelper { } } - /** * Returns the touch target View of the event given, or null if neither the given View nor any of * its descendants are the touch target. */ private static @Nullable View findTouchTargetViewWithPointerEvents( float eventCoords[], View view) { - PointerEvents pointerEvents = view instanceof ReactPointerEventsView ? - ((ReactPointerEventsView) view).getPointerEvents() : PointerEvents.AUTO; + PointerEvents pointerEvents = + view instanceof ReactPointerEventsView + ? ((ReactPointerEventsView) view).getPointerEvents() + : PointerEvents.AUTO; // Views that are disabled should never be the target of pointer events. However, their children // can be because some views (SwipeRefreshLayout) use enabled but still have children that can @@ -238,7 +228,8 @@ public class TouchTargetHelper { // is both a ViewGroup and ReactCompoundView (ReactTextView is a ReactCompoundView but not a // ViewGroup). if (view instanceof ReactCompoundView) { - int reactTag = ((ReactCompoundView)view).reactTagForTouch(eventCoords[0], eventCoords[1]); + int reactTag = + ((ReactCompoundView) view).reactTagForTouch(eventCoords[0], eventCoords[1]); if (reactTag != view.getId()) { // make sure we exclude the View itself because of the PointerEvents.BOX_NONE return view; @@ -273,5 +264,4 @@ public class TouchTargetHelper { } return targetView.getId(); } - } diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/TransformHelper.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/TransformHelper.java index 0dd0e2d276e..b2e3b64130a 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/TransformHelper.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/TransformHelper.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; import com.facebook.react.bridge.JSApplicationIllegalArgumentException; @@ -18,12 +17,13 @@ import com.facebook.react.bridge.ReadableType; */ public class TransformHelper { - private static ThreadLocal sHelperMatrix = new ThreadLocal() { - @Override - protected double[] initialValue() { - return new double[16]; - } - }; + private static ThreadLocal sHelperMatrix = + new ThreadLocal() { + @Override + protected double[] initialValue() { + return new double[16]; + } + }; private static double convertToRadians(ReadableMap transformMap, String key) { double value; @@ -60,17 +60,11 @@ public class TransformHelper { } else if ("perspective".equals(transformType)) { MatrixMathHelper.applyPerspective(helperMatrix, transform.getDouble(transformType)); } else if ("rotateX".equals(transformType)) { - MatrixMathHelper.applyRotateX( - helperMatrix, - convertToRadians(transform, transformType)); + MatrixMathHelper.applyRotateX(helperMatrix, convertToRadians(transform, transformType)); } else if ("rotateY".equals(transformType)) { - MatrixMathHelper.applyRotateY( - helperMatrix, - convertToRadians(transform, transformType)); + MatrixMathHelper.applyRotateY(helperMatrix, convertToRadians(transform, transformType)); } else if ("rotate".equals(transformType) || "rotateZ".equals(transformType)) { - MatrixMathHelper.applyRotateZ( - helperMatrix, - convertToRadians(transform, transformType)); + MatrixMathHelper.applyRotateZ(helperMatrix, convertToRadians(transform, transformType)); } else if ("scale".equals(transformType)) { double scale = transform.getDouble(transformType); MatrixMathHelper.applyScaleX(helperMatrix, scale); @@ -90,16 +84,12 @@ public class TransformHelper { } else if ("translateY".equals(transformType)) { MatrixMathHelper.applyTranslate2D(helperMatrix, 0d, transform.getDouble(transformType)); } else if ("skewX".equals(transformType)) { - MatrixMathHelper.applySkewX( - helperMatrix, - convertToRadians(transform, transformType)); + MatrixMathHelper.applySkewX(helperMatrix, convertToRadians(transform, transformType)); } else if ("skewY".equals(transformType)) { - MatrixMathHelper.applySkewY( - helperMatrix, - convertToRadians(transform, transformType)); + MatrixMathHelper.applySkewY(helperMatrix, convertToRadians(transform, transformType)); } else { - throw new JSApplicationIllegalArgumentException("Unsupported transform type: " - + transformType); + throw new JSApplicationIllegalArgumentException( + "Unsupported transform type: " + transformType); } MatrixMathHelper.multiplyInto(result, result, helperMatrix); diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIBlock.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIBlock.java index 619c793c125..8f0a18e7c64 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIBlock.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIBlock.java @@ -1,17 +1,12 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; -import android.view.View; - -/** - * A task to execute on the UI View for third party libraries. - */ +/** A task to execute on the UI View for third party libraries. */ public interface UIBlock { public void execute(NativeViewHierarchyManager nativeViewHierarchyManager); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIImplementation.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIImplementation.java index 483958049fe..9a73e556e6a 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIImplementation.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIImplementation.java @@ -1,8 +1,8 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ package com.facebook.react.uimanager; @@ -27,15 +27,13 @@ import com.facebook.systrace.SystraceMessage; import com.facebook.yoga.YogaConstants; import com.facebook.yoga.YogaDirection; import java.util.Arrays; -import java.util.HashSet; import java.util.List; import java.util.Map; -import java.util.Set; import javax.annotation.Nullable; /** - * A class that is used to receive React commands from JS and translate them into a - * shadow node hierarchy that is then mapped to a native view hierarchy. + * A class that is used to receive React commands from JS and translate them into a shadow node + * hierarchy that is then mapped to a native view hierarchy. */ public class UIImplementation { protected Object uiImplementationThreadLock = new Object(); @@ -105,9 +103,8 @@ public class UIImplementation { mReactContext = reactContext; mViewManagers = viewManagers; mOperationsQueue = operationsQueue; - mNativeViewHierarchyOptimizer = new NativeViewHierarchyOptimizer( - mOperationsQueue, - mShadowNodeRegistry); + mNativeViewHierarchyOptimizer = + new NativeViewHierarchyOptimizer(mOperationsQueue, mShadowNodeRegistry); mEventDispatcher = eventDispatcher; } @@ -164,36 +161,32 @@ public class UIImplementation { * Registers a root node with a given tag, size and ThemedReactContext and adds it to a node * registry. */ - public void registerRootView( - T rootView, int tag, ThemedReactContext context) { + public void registerRootView(T rootView, int tag, ThemedReactContext context) { synchronized (uiImplementationThreadLock) { final ReactShadowNode rootCSSNode = createRootShadowNode(); rootCSSNode.setReactTag(tag); // Thread safety needed here rootCSSNode.setThemedContext(context); - context.runOnNativeModulesQueueThread(new Runnable() { - @Override - public void run() { - mShadowNodeRegistry.addRootNode(rootCSSNode); - } - }); + context.runOnNativeModulesQueueThread( + new Runnable() { + @Override + public void run() { + mShadowNodeRegistry.addRootNode(rootCSSNode); + } + }); // register it within NativeViewHierarchyManager mOperationsQueue.addRootView(tag, rootView); } } - /** - * Unregisters a root node with a given tag. - */ + /** Unregisters a root node with a given tag. */ public void removeRootView(int rootViewTag) { removeRootShadowNode(rootViewTag); mOperationsQueue.enqueueRemoveRootView(rootViewTag); } - /** - * Unregisters a root node with a given tag from the shadow node registry - */ + /** Unregisters a root node with a given tag from the shadow node registry */ public void removeRootShadowNode(int rootViewTag) { synchronized (uiImplementationThreadLock) { mShadowNodeRegistry.removeRootNode(rootViewTag); // Thread safety needed here @@ -204,15 +197,10 @@ public class UIImplementation { * Invoked when native view that corresponds to a root node, or acts as a root view (ie. Modals) * has its size changed. */ - public void updateNodeSize( - int nodeViewTag, - int newWidth, - int newHeight) { + public void updateNodeSize(int nodeViewTag, int newWidth, int newHeight) { ReactShadowNode cssNode = mShadowNodeRegistry.getNode(nodeViewTag); if (cssNode == null) { - FLog.w( - ReactConstants.TAG, - "Tried to update size of non-existent tag: " + nodeViewTag); + FLog.w(ReactConstants.TAG, "Tried to update size of non-existent tag: " + nodeViewTag); return; } cssNode.setStyleWidth(newWidth); @@ -225,9 +213,7 @@ public class UIImplementation { ReactShadowNode shadowNode = mShadowNodeRegistry.getNode(tag); if (shadowNode == null) { - FLog.w( - ReactConstants.TAG, - "Attempt to set local data for view with unknown tag: " + tag); + FLog.w(ReactConstants.TAG, "Attempt to set local data for view with unknown tag: " + tag); return; } @@ -244,9 +230,7 @@ public class UIImplementation { return mOperationsQueue.getProfiledBatchPerfCounters(); } - /** - * Invoked by React to create a new node with a given tag, class name and properties. - */ + /** Invoked by React to create a new node with a given tag, class name and properties. */ public void createView(int tag, String className, int rootViewTag, ReadableMap props) { synchronized (uiImplementationThreadLock) { ReactShadowNode cssNode = createShadowNode(className); @@ -270,17 +254,13 @@ public class UIImplementation { } protected void handleCreateView( - ReactShadowNode cssNode, - int rootViewTag, - @Nullable ReactStylesDiffMap styles) { + ReactShadowNode cssNode, int rootViewTag, @Nullable ReactStylesDiffMap styles) { if (!cssNode.isVirtual()) { mNativeViewHierarchyOptimizer.handleCreateView(cssNode, cssNode.getThemedContext(), styles); } } - /** - * Invoked by React to create a new node with a given tag has its properties changed. - */ + /** Invoked by React to create a new node with a given tag has its properties changed. */ public void updateView(int tag, String className, ReadableMap props) { ViewManager viewManager = mViewManagers.get(className); if (viewManager == null) { @@ -301,8 +281,8 @@ public class UIImplementation { /** * Used by native animated module to bypass the process of updating the values through the shadow * view hierarchy. This method will directly update native views, which means that updates for - * layout-related propertied won't be handled properly. - * Make sure you know what you're doing before calling this method :) + * layout-related propertied won't be handled properly. Make sure you know what you're doing + * before calling this method :) */ public void synchronouslyUpdateViewOnUIThread(int tag, ReactStylesDiffMap props) { UiThreadUtil.assertOnUiThread(); @@ -310,9 +290,7 @@ public class UIImplementation { } protected void handleUpdateView( - ReactShadowNode cssNode, - String className, - ReactStylesDiffMap styles) { + ReactShadowNode cssNode, String className, ReactStylesDiffMap styles) { if (!cssNode.isVirtual()) { mNativeViewHierarchyOptimizer.handleUpdateView(cssNode, className, styles); } @@ -324,7 +302,7 @@ public class UIImplementation { * @param tag react tag of the node we want to manage * @param indicesToRemove ordered (asc) list of indicies at which view should be removed * @param viewsToAdd ordered (asc based on mIndex property) list of tag-index pairs that represent - * a view which should be added at the specified index + * a view which should be added at the specified index * @param tagsToDelete list of tags corresponding to views that should be removed */ public void manageChildren( @@ -362,10 +340,7 @@ public class UIImplementation { for (int i = 0; i < numToMove; i++) { int moveFromIndex = moveFrom.getInt(i); int tagToMove = cssNodeToManage.getChildAt(moveFromIndex).getReactTag(); - viewsToAdd[i] = new ViewAtIndex( - tagToMove, - moveTo.getInt(i) - ); + viewsToAdd[i] = new ViewAtIndex(tagToMove, moveTo.getInt(i)); indicesToRemove[i] = moveFromIndex; tagsToRemove[i] = tagToMove; } @@ -410,8 +385,8 @@ public class UIImplementation { for (int i = indicesToRemove.length - 1; i >= 0; i--) { int indexToRemove = indicesToRemove[i]; if (indexToRemove == lastIndexRemoved) { - throw new IllegalViewOperationException("Repeated indices in Removal list for view tag: " - + viewTag); + throw new IllegalViewOperationException( + "Repeated indices in Removal list for view tag: " + viewTag); } cssNodeToManage.removeChildAt(indicesToRemove[i]); // Thread safety needed here @@ -422,19 +397,19 @@ public class UIImplementation { ViewAtIndex viewAtIndex = viewsToAdd[i]; ReactShadowNode cssNodeToAdd = mShadowNodeRegistry.getNode(viewAtIndex.mTag); if (cssNodeToAdd == null) { - throw new IllegalViewOperationException("Trying to add unknown view tag: " - + viewAtIndex.mTag); + throw new IllegalViewOperationException( + "Trying to add unknown view tag: " + viewAtIndex.mTag); } cssNodeToManage.addChildAt(cssNodeToAdd, viewAtIndex.mIndex); } mNativeViewHierarchyOptimizer.handleManageChildren( - cssNodeToManage, - indicesToRemove, - tagsToRemove, - viewsToAdd, - tagsToDelete, - indicesToDelete); + cssNodeToManage, + indicesToRemove, + tagsToRemove, + viewsToAdd, + tagsToDelete, + indicesToDelete); for (int i = 0; i < tagsToDelete.length; i++) { removeShadowNode(mShadowNodeRegistry.getNode(tagsToDelete[i])); @@ -443,30 +418,26 @@ public class UIImplementation { } /** - * An optimized version of manageChildren that is used for initial setting of child views. - * The children are assumed to be in index order + * An optimized version of manageChildren that is used for initial setting of child views. The + * children are assumed to be in index order * * @param viewTag tag of the parent * @param childrenTags tags of the children */ - public void setChildren( - int viewTag, - ReadableArray childrenTags) { + public void setChildren(int viewTag, ReadableArray childrenTags) { synchronized (uiImplementationThreadLock) { ReactShadowNode cssNodeToManage = mShadowNodeRegistry.getNode(viewTag); for (int i = 0; i < childrenTags.size(); i++) { ReactShadowNode cssNodeToAdd = mShadowNodeRegistry.getNode(childrenTags.getInt(i)); if (cssNodeToAdd == null) { - throw new IllegalViewOperationException("Trying to add unknown view tag: " - + childrenTags.getInt(i)); + throw new IllegalViewOperationException( + "Trying to add unknown view tag: " + childrenTags.getInt(i)); } cssNodeToManage.addChildAt(cssNodeToAdd, i); } - mNativeViewHierarchyOptimizer.handleSetChildren( - cssNodeToManage, - childrenTags); + mNativeViewHierarchyOptimizer.handleSetChildren(cssNodeToManage, childrenTags); } } @@ -507,8 +478,8 @@ public class UIImplementation { /** * Method which takes a container tag and then releases all subviews for that container upon - * receipt. - * TODO: The method name is incorrect and will be renamed, #6033872 + * receipt. TODO: The method name is incorrect and will be renamed, #6033872 + * * @param containerTag the tag of the container for which the subviews must be removed */ public void removeSubviewsFromContainerWithID(int containerTag) { @@ -527,16 +498,16 @@ public class UIImplementation { } /** - * Find the touch target child native view in the supplied root view hierarchy, given a react + * Find the touch target child native view in the supplied root view hierarchy, given a react * target location. * - * This method is currently used only by Element Inspector DevTool. + *

This method is currently used only by Element Inspector DevTool. * * @param reactTag the tag of the root view to traverse * @param targetX target X location * @param targetY target Y location * @param callback will be called if with the identified child view react ID, and measurement - * info. If no view was found, callback will be invoked with no data. + * info. If no view was found, callback will be invoked with no data. */ public void findSubviewIn(int reactTag, float targetX, float targetY, Callback callback) { mOperationsQueue.enqueueFindTargetForTouch(reactTag, targetX, targetY, callback); @@ -556,7 +527,7 @@ public class UIImplementation { /** * Determines the location on screen, width, and height of the given view relative to the device - * screen and returns the values via an async callback. This is the absolute position including + * screen and returns the values via an async callback. This is the absolute position including * things like the status bar */ public void measureInWindow(int reactTag, Callback callback) { @@ -566,14 +537,11 @@ public class UIImplementation { /** * Measures the view specified by tag relative to the given ancestorTag. This means that the * returned x, y are relative to the origin x, y of the ancestor view. Results are stored in the - * given outputBuffer. We allow ancestor view and measured view to be the same, in which case - * the position always will be (0, 0) and method will only measure the view dimensions. + * given outputBuffer. We allow ancestor view and measured view to be the same, in which case the + * position always will be (0, 0) and method will only measure the view dimensions. */ public void measureLayout( - int tag, - int ancestorTag, - Callback errorCallback, - Callback successCallback) { + int tag, int ancestorTag, Callback errorCallback, Callback successCallback) { try { measureLayout(tag, ancestorTag, mMeasureBuffer); float relativeX = PixelUtil.toDIPFromPixel(mMeasureBuffer[0]); @@ -590,9 +558,7 @@ public class UIImplementation { * Like {@link #measure} and {@link #measureLayout} but measures relative to the immediate parent. */ public void measureLayoutRelativeToParent( - int tag, - Callback errorCallback, - Callback successCallback) { + int tag, Callback errorCallback, Callback successCallback) { try { measureLayoutRelativeToParent(tag, mMeasureBuffer); float relativeX = PixelUtil.toDIPFromPixel(mMeasureBuffer[0]); @@ -605,15 +571,12 @@ public class UIImplementation { } } - /** - * Invoked at the end of the transaction to commit any updates to the node hierarchy. - */ + /** Invoked at the end of the transaction to commit any updates to the node hierarchy. */ public void dispatchViewUpdates(int batchId) { SystraceMessage.beginSection( - Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, - "UIImplementation.dispatchViewUpdates") - .arg("batchId", batchId) - .flush(); + Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "UIImplementation.dispatchViewUpdates") + .arg("batchId", batchId) + .flush(); final long commitStartTime = SystemClock.uptimeMillis(); try { updateViewHierarchy(); @@ -637,8 +600,7 @@ public class UIImplementation { protected void updateViewHierarchy() { Systrace.beginSection( - Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, - "UIImplementation.updateViewHierarchy"); + Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "UIImplementation.updateViewHierarchy"); try { for (int i = 0; i < mShadowNodeRegistry.getRootNodeCount(); i++) { int tag = mShadowNodeRegistry.getRootTag(i); @@ -681,10 +643,10 @@ public class UIImplementation { * LayoutAnimation API on Android is currently experimental. Therefore, it needs to be enabled * explicitly in order to avoid regression in existing application written for iOS using this API. * - * Warning : This method will be removed in future version of React Native, and layout animation - * will be enabled by default, so always check for its existence before invoking it. + *

Warning : This method will be removed in future version of React Native, and layout + * animation will be enabled by default, so always check for its existence before invoking it. * - * TODO(9139831) : remove this method once layout animation is fully stable. + *

TODO(9139831) : remove this method once layout animation is fully stable. * * @param enabled whether layout animation is enabled or not */ @@ -693,15 +655,15 @@ public class UIImplementation { } /** - * Configure an animation to be used for the native layout changes, and native views - * creation. The animation will only apply during the current batch operations. + * Configure an animation to be used for the native layout changes, and native views creation. The + * animation will only apply during the current batch operations. * - * TODO(7728153) : animating view deletion is currently not supported. - * TODO(7613721) : callbacks are not supported, this feature will likely be killed. + *

TODO(7728153) : animating view deletion is currently not supported. TODO(7613721) : + * callbacks are not supported, this feature will likely be killed. * * @param config the configuration of the animation for view addition/removal/update. * @param success will be called when the animation completes, or when the animation get - * interrupted. In this case, callback parameter will be false. + * interrupted. In this case, callback parameter will be false. * @param error will be called if there was an error processing the animation */ public void configureNextLayoutAnimation(ReadableMap config, Callback success) { @@ -712,8 +674,8 @@ public class UIImplementation { ReactShadowNode node = mShadowNodeRegistry.getNode(reactTag); if (node == null) { - //TODO: this should only happen when using Fabric renderer. This is a temporary approach - //and it will be refactored when fabric supports JS Responder. + // TODO: this should only happen when using Fabric renderer. This is a temporary approach + // and it will be refactored when fabric supports JS Responder. return; } @@ -727,12 +689,14 @@ public class UIImplementation { mOperationsQueue.enqueueClearJSResponder(); } - public void dispatchViewManagerCommand(int reactTag, int commandId, @Nullable ReadableArray commandArgs) { + public void dispatchViewManagerCommand( + int reactTag, int commandId, @Nullable ReadableArray commandArgs) { assertViewExists(reactTag, "dispatchViewManagerCommand"); mOperationsQueue.enqueueDispatchCommand(reactTag, commandId, commandArgs); } - public void dispatchViewManagerCommand(int reactTag, String commandId, @Nullable ReadableArray commandArgs) { + public void dispatchViewManagerCommand( + int reactTag, String commandId, @Nullable ReadableArray commandArgs) { assertViewExists(reactTag, "dispatchViewManagerCommand"); mOperationsQueue.enqueueDispatchCommand(reactTag, commandId, commandArgs); } @@ -741,11 +705,11 @@ public class UIImplementation { * Show a PopupMenu. * * @param reactTag the tag of the anchor view (the PopupMenu is displayed next to this view); this - * needs to be the tag of a native view (shadow views can not be anchors) + * needs to be the tag of a native view (shadow views can not be anchors) * @param items the menu items as an array of strings * @param error will be called if there is an error displaying the menu * @param success will be called with the position of the selected item as the first argument, or - * no arguments if the menu is dismissed + * no arguments if the menu is dismissed */ public void showPopupMenu(int reactTag, ReadableArray items, Callback error, Callback success) { assertViewExists(reactTag, "showPopupMenu"); @@ -768,8 +732,7 @@ public class UIImplementation { mOperationsQueue.pauseFrameCallback(); } - public void onHostDestroy() { - } + public void onHostDestroy() {} public void setViewHierarchyUpdateDebugListener( @Nullable NotThreadSafeViewHierarchyUpdateDebugListener listener) { @@ -826,9 +789,7 @@ public class UIImplementation { } private void measureLayoutRelativeToVerifiedAncestor( - ReactShadowNode node, - ReactShadowNode ancestor, - int[] outputBuffer) { + ReactShadowNode node, ReactShadowNode ancestor, int[] outputBuffer) { int offsetX = 0; int offsetY = 0; if (node != ancestor) { @@ -854,8 +815,12 @@ public class UIImplementation { private void assertViewExists(int reactTag, String operationNameForExceptionMessage) { if (mShadowNodeRegistry.getNode(reactTag) == null) { throw new IllegalViewOperationException( - "Unable to execute operation " + operationNameForExceptionMessage + " on view with " + - "tag: " + reactTag + ", since the view does not exists"); + "Unable to execute operation " + + operationNameForExceptionMessage + + " on view with " + + "tag: " + + reactTag + + ", since the view does not exists"); } } @@ -865,14 +830,17 @@ public class UIImplementation { if (viewManager instanceof IViewManagerWithChildren) { viewManagerWithChildren = (IViewManagerWithChildren) viewManager; } else { - throw new IllegalViewOperationException("Trying to use view " + node.getViewClass() + - " as a parent, but its Manager doesn't extends ViewGroupManager"); + throw new IllegalViewOperationException( + "Trying to use view " + + node.getViewClass() + + " as a parent, but its Manager doesn't extends ViewGroupManager"); } if (viewManagerWithChildren != null && viewManagerWithChildren.needsCustomLayoutForChildren()) { throw new IllegalViewOperationException( - "Trying to measure a view using measureLayout/measureLayoutRelativeToParent relative to" + - " an ancestor that requires custom layout for it's children (" + node.getViewClass() + - "). Use measure instead."); + "Trying to measure a view using measureLayout/measureLayoutRelativeToParent relative to" + + " an ancestor that requires custom layout for it's children (" + + node.getViewClass() + + "). Use measure instead."); } } @@ -895,22 +863,19 @@ public class UIImplementation { int widthSpec = cssRoot.getWidthMeasureSpec(); int heightSpec = cssRoot.getHeightMeasureSpec(); cssRoot.calculateLayout( - MeasureSpec.getMode(widthSpec) == MeasureSpec.UNSPECIFIED - ? YogaConstants.UNDEFINED - : MeasureSpec.getSize(widthSpec), - MeasureSpec.getMode(heightSpec) == MeasureSpec.UNSPECIFIED - ? YogaConstants.UNDEFINED - : MeasureSpec.getSize(heightSpec)); + MeasureSpec.getMode(widthSpec) == MeasureSpec.UNSPECIFIED + ? YogaConstants.UNDEFINED + : MeasureSpec.getSize(widthSpec), + MeasureSpec.getMode(heightSpec) == MeasureSpec.UNSPECIFIED + ? YogaConstants.UNDEFINED + : MeasureSpec.getSize(heightSpec)); } finally { Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); mLastCalculateLayoutTime = SystemClock.uptimeMillis() - startTime; } } - protected void applyUpdatesRecursive( - ReactShadowNode cssNode, - float absoluteX, - float absoluteY) { + protected void applyUpdatesRecursive(ReactShadowNode cssNode, float absoluteX, float absoluteY) { if (!cssNode.hasUpdates()) { return; } @@ -919,19 +884,15 @@ public class UIImplementation { if (cssChildren != null) { for (ReactShadowNode cssChild : cssChildren) { applyUpdatesRecursive( - cssChild, - absoluteX + cssNode.getLayoutX(), - absoluteY + cssNode.getLayoutY()); + cssChild, absoluteX + cssNode.getLayoutX(), absoluteY + cssNode.getLayoutY()); } } int tag = cssNode.getReactTag(); if (!mShadowNodeRegistry.isRootNode(tag)) { - boolean frameDidChange = cssNode.dispatchUpdates( - absoluteX, - absoluteY, - mOperationsQueue, - mNativeViewHierarchyOptimizer); + boolean frameDidChange = + cssNode.dispatchUpdates( + absoluteX, absoluteY, mOperationsQueue, mNativeViewHierarchyOptimizer); // Notify JS about layout event if requested // and if the position or dimensions actually changed @@ -968,8 +929,8 @@ public class UIImplementation { rootTag = node.getRootTag(); } else { FLog.w( - ReactConstants.TAG, - "Warning : attempted to resolve a non-existent react shadow node. reactTag=" + reactTag); + ReactConstants.TAG, + "Warning : attempted to resolve a non-existent react shadow node. reactTag=" + reactTag); } return rootTag; diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIImplementationProvider.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIImplementationProvider.java index 5a6d95ce990..2d5442b1d6a 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIImplementationProvider.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIImplementationProvider.java @@ -1,8 +1,8 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ package com.facebook.react.uimanager; @@ -10,9 +10,7 @@ import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.uimanager.events.EventDispatcher; import java.util.List; -/** - * Provides UIImplementation to use in {@link UIManagerModule}. - */ +/** Provides UIImplementation to use in {@link UIManagerModule}. */ @Deprecated public class UIImplementationProvider { @@ -34,21 +32,18 @@ public class UIImplementationProvider { EventDispatcher eventDispatcher, int minTimeLeftInFrameForNonBatchedOperationMs) { return new UIImplementation( - reactContext, - viewManagerList, - eventDispatcher, - minTimeLeftInFrameForNonBatchedOperationMs); + reactContext, viewManagerList, eventDispatcher, minTimeLeftInFrameForNonBatchedOperationMs); } UIImplementation createUIImplementation( - ReactApplicationContext reactContext, - ViewManagerRegistry viewManagerRegistry, - EventDispatcher eventDispatcher, - int minTimeLeftInFrameForNonBatchedOperationMs) { + ReactApplicationContext reactContext, + ViewManagerRegistry viewManagerRegistry, + EventDispatcher eventDispatcher, + int minTimeLeftInFrameForNonBatchedOperationMs) { return new UIImplementation( - reactContext, - viewManagerRegistry, - eventDispatcher, - minTimeLeftInFrameForNonBatchedOperationMs); + reactContext, + viewManagerRegistry, + eventDispatcher, + minTimeLeftInFrameForNonBatchedOperationMs); } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerHelper.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerHelper.java index 406989e1576..5b4d965c95a 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerHelper.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerHelper.java @@ -1,14 +1,12 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; import static com.facebook.react.uimanager.common.UIManagerType.FABRIC; -import static com.facebook.react.uimanager.common.UIManagerType.DEFAULT; import static com.facebook.react.uimanager.common.ViewUtil.getUIManagerType; import com.facebook.react.bridge.CatalystInstance; @@ -17,26 +15,19 @@ import com.facebook.react.bridge.ReactContext; import com.facebook.react.bridge.UIManager; import com.facebook.react.uimanager.common.UIManagerType; -/** - * Helper class for {@link UIManager}. - */ +/** Helper class for {@link UIManager}. */ public class UIManagerHelper { - /** - * @return a {@link UIManager} that can handle the react tag received by parameter. - */ + /** @return a {@link UIManager} that can handle the react tag received by parameter. */ public static UIManager getUIManagerForReactTag(ReactContext context, int reactTag) { return getUIManager(context, getUIManagerType(reactTag)); } - /** - * @return a {@link UIManager} that can handle the react tag received by parameter. - */ + /** @return a {@link UIManager} that can handle the react tag received by parameter. */ public static UIManager getUIManager(ReactContext context, @UIManagerType int uiManagerType) { CatalystInstance catalystInstance = context.getCatalystInstance(); - return uiManagerType == FABRIC ? - (UIManager)catalystInstance.getJSIModule(JSIModuleType.UIManager) : - catalystInstance.getNativeModule(UIManagerModule.class); + return uiManagerType == FABRIC + ? (UIManager) catalystInstance.getJSIModule(JSIModuleType.UIManager) + : catalystInstance.getNativeModule(UIManagerModule.class); } - } diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerModule.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerModule.java index 356d6f84be0..a2b18000298 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerModule.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerModule.java @@ -38,7 +38,6 @@ import com.facebook.react.bridge.UiThreadUtil; import com.facebook.react.bridge.WritableMap; import com.facebook.react.common.MapBuilder; import com.facebook.react.common.ReactConstants; -import com.facebook.react.common.annotations.VisibleForTesting; import com.facebook.react.module.annotations.ReactModule; import com.facebook.react.uimanager.common.ViewUtil; import com.facebook.react.uimanager.debug.NotThreadSafeViewHierarchyUpdateDebugListener; @@ -243,8 +242,8 @@ public class UIManagerModule extends ReactContextBaseJavaModule } /** - * This method is intended to reuse the {@link ViewManagerRegistry} with FabricUIManager. - * Do not use this method as this will be removed in the near future. + * This method is intended to reuse the {@link ViewManagerRegistry} with FabricUIManager. Do not + * use this method as this will be removed in the near future. */ @Deprecated public ViewManagerRegistry getViewManagerRegistry_DO_NOT_USE() { @@ -377,22 +376,22 @@ public class UIManagerModule extends ReactContextBaseJavaModule return mUIImplementation.getProfiledBatchPerfCounters(); } - public int addRootView( - final T rootView) { - return addRootView(rootView, null, null); - } + public int addRootView(final T rootView) { + return addRootView(rootView, null, null); + } /** * Used by native animated module to bypass the process of updating the values through the shadow * view hierarchy. This method will directly update native views, which means that updates for - * layout-related propertied won't be handled properly. - * Make sure you know what you're doing before calling this method :) + * layout-related propertied won't be handled properly. Make sure you know what you're doing + * before calling this method :) */ @Override public void synchronouslyUpdateViewOnUIThread(int tag, ReadableMap props) { int uiManagerType = ViewUtil.getUIManagerType(tag); if (uiManagerType == FABRIC) { - UIManager fabricUIManager = UIManagerHelper.getUIManager(getReactApplicationContext(), uiManagerType); + UIManager fabricUIManager = + UIManagerHelper.getUIManager(getReactApplicationContext(), uiManagerType); fabricUIManager.synchronouslyUpdateViewOnUIThread(tag, props); } else { mUIImplementation.synchronouslyUpdateViewOnUIThread(tag, new ReactStylesDiffMap(props)); @@ -475,7 +474,8 @@ public class UIManagerModule extends ReactContextBaseJavaModule } int uiManagerType = ViewUtil.getUIManagerType(tag); if (uiManagerType == FABRIC) { - UIManager fabricUIManager = UIManagerHelper.getUIManager(getReactApplicationContext(), uiManagerType); + UIManager fabricUIManager = + UIManagerHelper.getUIManager(getReactApplicationContext(), uiManagerType); fabricUIManager.synchronouslyUpdateViewOnUIThread(tag, props); } else { mUIImplementation.updateView(tag, className, props); @@ -646,16 +646,17 @@ public class UIManagerModule extends ReactContextBaseJavaModule int reactTag, Dynamic commandId, @Nullable ReadableArray commandArgs) { // TODO: this is a temporary approach to support ViewManagerCommands in Fabric until // the dispatchViewManagerCommand() method is supported by Fabric JS API. - if(commandId.getType() == ReadableType.Number) { + if (commandId.getType() == ReadableType.Number) { final int commandIdNum = commandId.asInt(); - UIManagerHelper.getUIManager(getReactApplicationContext(), ViewUtil.getUIManagerType(reactTag)) + UIManagerHelper.getUIManager( + getReactApplicationContext(), ViewUtil.getUIManagerType(reactTag)) .dispatchCommand(reactTag, commandIdNum, commandArgs); } else if (commandId.getType() == ReadableType.String) { final String commandIdStr = commandId.asString(); - UIManagerHelper.getUIManager(getReactApplicationContext(), ViewUtil.getUIManagerType(reactTag)) + UIManagerHelper.getUIManager( + getReactApplicationContext(), ViewUtil.getUIManagerType(reactTag)) .dispatchCommand(reactTag, commandIdStr, commandArgs); } - } @Override @@ -870,6 +871,9 @@ public class UIManagerModule extends ReactContextBaseJavaModule public View resolveView(int tag) { UiThreadUtil.assertOnUiThread(); - return mUIImplementation.getUIViewOperationQueue().getNativeViewHierarchyManager().resolveView(tag); + return mUIImplementation + .getUIViewOperationQueue() + .getNativeViewHierarchyManager() + .resolveView(tag); } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerModuleConstants.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerModuleConstants.java index 6ca9380ba64..0a42948bf7e 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerModuleConstants.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerModuleConstants.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; import android.view.accessibility.AccessibilityEvent; @@ -13,10 +12,7 @@ import com.facebook.react.common.MapBuilder; import com.facebook.react.uimanager.events.TouchEventType; import java.util.Map; - -/** - * Constants exposed to JS from {@link UIManagerModule}. - */ +/** Constants exposed to JS from {@link UIManagerModule}. */ /* package */ class UIManagerModuleConstants { public static final String ACTION_DISMISSED = "dismissed"; @@ -38,38 +34,22 @@ import java.util.Map; TouchEventType.getJSEventName(TouchEventType.START), MapBuilder.of( "phasedRegistrationNames", - MapBuilder.of( - "bubbled", - "onTouchStart", - "captured", - "onTouchStartCapture"))) + MapBuilder.of("bubbled", "onTouchStart", "captured", "onTouchStartCapture"))) .put( TouchEventType.getJSEventName(TouchEventType.MOVE), MapBuilder.of( "phasedRegistrationNames", - MapBuilder.of( - "bubbled", - "onTouchMove", - "captured", - "onTouchMoveCapture"))) + MapBuilder.of("bubbled", "onTouchMove", "captured", "onTouchMoveCapture"))) .put( TouchEventType.getJSEventName(TouchEventType.END), MapBuilder.of( "phasedRegistrationNames", - MapBuilder.of( - "bubbled", - "onTouchEnd", - "captured", - "onTouchEndCapture"))) + MapBuilder.of("bubbled", "onTouchEnd", "captured", "onTouchEndCapture"))) .put( TouchEventType.getJSEventName(TouchEventType.CANCEL), MapBuilder.of( "phasedRegistrationNames", - MapBuilder.of( - "bubbled", - "onTouchCancel", - "captured", - "onTouchCancelCapture"))) + MapBuilder.of("bubbled", "onTouchCancel", "captured", "onTouchCancelCapture"))) .build(); } @@ -125,20 +105,17 @@ import java.util.Map; constants.put( "PopupMenu", MapBuilder.of( - ACTION_DISMISSED, - ACTION_DISMISSED, - ACTION_ITEM_SELECTED, - ACTION_ITEM_SELECTED)); + ACTION_DISMISSED, ACTION_DISMISSED, ACTION_ITEM_SELECTED, ACTION_ITEM_SELECTED)); constants.put( - "AccessibilityEventTypes", - MapBuilder.of( - "typeWindowStateChanged", - AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED, - "typeViewFocused", - AccessibilityEvent.TYPE_VIEW_FOCUSED, - "typeViewClicked", - AccessibilityEvent.TYPE_VIEW_CLICKED)); + "AccessibilityEventTypes", + MapBuilder.of( + "typeWindowStateChanged", + AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED, + "typeViewFocused", + AccessibilityEvent.TYPE_VIEW_FOCUSED, + "typeViewClicked", + AccessibilityEvent.TYPE_VIEW_CLICKED)); return constants; } diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerModuleConstantsHelper.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerModuleConstantsHelper.java index 8e993c1935c..bcc650f94cd 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerModuleConstantsHelper.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerModuleConstantsHelper.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; import static com.facebook.systrace.Systrace.TRACE_TAG_REACT_JAVA_BRIDGE; @@ -28,8 +27,8 @@ import javax.annotation.Nullable; /** * Generates a lazy discovery enabled version of {@link UIManagerModule} constants. It only * contains a list of view manager names, so that JS side is aware of the managers there are. - * Actual ViewManager instantiation happens when - * {@code UIManager.getViewManagerConfig('SpecificViewManager')} call happens. The View Manager is then + * Actual ViewManager instantiation happens when {@code + * UIManager.getViewManagerConfig('SpecificViewManager')} call happens. The View Manager is then * registered on the JS side with the help of {@code UIManagerModule.getConstantsForViewManager}. */ /* package */ static Map createConstants( @@ -49,21 +48,19 @@ import javax.annotation.Nullable; } /** - * Generates map of constants that is then exposed by {@link UIManagerModule}. - * Provided list of {@param viewManagers} is then used to populate content of - * those predefined fields using - * {@link ViewManager#getExportedCustomBubblingEventTypeConstants} and - * {@link ViewManager#getExportedCustomDirectEventTypeConstants} respectively. Each view manager - * is in addition allowed to expose viewmanager-specific constants that are placed under the key - * that corresponds to the view manager's name (see {@link ViewManager#getName}). Constants are - * merged into the map of {@link UIManagerModule} base constants that is stored in - * {@link UIManagerModuleConstants}. - * TODO(6845124): Create a test for this + * Generates map of constants that is then exposed by {@link UIManagerModule}. Provided list of + * {@param viewManagers} is then used to populate content of those predefined fields using {@link + * ViewManager#getExportedCustomBubblingEventTypeConstants} and {@link + * ViewManager#getExportedCustomDirectEventTypeConstants} respectively. Each view manager is in + * addition allowed to expose viewmanager-specific constants that are placed under the key that + * corresponds to the view manager's name (see {@link ViewManager#getName}). Constants are merged + * into the map of {@link UIManagerModule} base constants that is stored in {@link + * UIManagerModuleConstants}. TODO(6845124): Create a test for this */ /* package */ static Map createConstants( - List viewManagers, - @Nullable Map allBubblingEventTypes, - @Nullable Map allDirectEventTypes) { + List viewManagers, + @Nullable Map allBubblingEventTypes, + @Nullable Map allDirectEventTypes) { Map constants = UIManagerModuleConstants.getConstants(); // Generic/default event types: @@ -92,12 +89,9 @@ import javax.annotation.Nullable; .flush(); try { - Map viewManagerConstants = createConstantsForViewManager( - viewManager, - null, - null, - allBubblingEventTypes, - allDirectEventTypes); + Map viewManagerConstants = + createConstantsForViewManager( + viewManager, null, null, allBubblingEventTypes, allDirectEventTypes); if (!viewManagerConstants.isEmpty()) { constants.put(viewManagerName, viewManagerConstants); } @@ -153,9 +147,7 @@ import javax.annotation.Nullable; return viewManagerConstants; } - /** - * Merges {@param source} map into {@param dest} map recursively - */ + /** Merges {@param source} map into {@param dest} map recursively */ private static void recursiveMerge(@Nullable Map dest, @Nullable Map source) { if (dest == null || source == null || source.isEmpty()) { return; diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerModuleListener.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerModuleListener.java index e6d5c840016..b2a68c59c0b 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerModuleListener.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerModuleListener.java @@ -1,15 +1,12 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; -/** - * Listener used to hook into the UIManager update process. - */ +/** Listener used to hook into the UIManager update process. */ public interface UIManagerModuleListener { /** * Called right before view updates are dispatched at the end of a batch. This is useful if a diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIViewOperationQueue.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIViewOperationQueue.java index 80efe29ffdc..1623ac7f86b 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIViewOperationQueue.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIViewOperationQueue.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; import android.os.SystemClock; @@ -31,15 +30,14 @@ import javax.annotation.Nullable; import javax.annotation.concurrent.GuardedBy; /** - * This class acts as a buffer for command executed on {@link NativeViewHierarchyManager}. - * It expose similar methods as mentioned classes but instead of executing commands - * immediately it enqueues those operations in a queue that is then flushed from - * {@link UIManagerModule} once JS batch of ui operations is finished. This is to make sure that we - * execute all the JS operation coming from a single batch a single loop of the main (UI) android - * looper. + * This class acts as a buffer for command executed on {@link NativeViewHierarchyManager}. It expose + * similar methods as mentioned classes but instead of executing commands immediately it enqueues + * those operations in a queue that is then flushed from {@link UIManagerModule} once JS batch of ui + * operations is finished. This is to make sure that we execute all the JS operation coming from a + * single batch a single loop of the main (UI) android looper. * - * TODO(7135923): Pooling of operation objects - * TODO(5694019): Consider a better data structure for operations queue to save on allocations + *

TODO(7135923): Pooling of operation objects TODO(5694019): Consider a better data structure + * for operations queue to save on allocations */ public class UIViewOperationQueue { @@ -47,17 +45,13 @@ public class UIViewOperationQueue { private final int[] mMeasureBuffer = new int[4]; - /** - * A mutation or animation operation on the view hierarchy. - */ + /** A mutation or animation operation on the view hierarchy. */ public interface UIOperation { void execute(); } - /** - * A spec for an operation on the native View hierarchy. - */ + /** A spec for an operation on the native View hierarchy. */ private abstract class ViewOperation implements UIOperation { public int mTag; @@ -102,11 +96,7 @@ public class UIViewOperationQueue { private final int mScreenHeight; public EmitOnLayoutEventOperation( - int tag, - int screenX, - int screenY, - int screenWidth, - int screenHeight) { + int tag, int screenX, int screenY, int screenWidth, int screenHeight) { super(tag); mScreenX = screenX; mScreenY = screenY; @@ -116,14 +106,11 @@ public class UIViewOperationQueue { @Override public void execute() { - mReactApplicationContext.getNativeModule(UIManagerModule.class) - .getEventDispatcher() - .dispatchEvent(OnLayoutEvent.obtain( - mTag, - mScreenX, - mScreenY, - mScreenWidth, - mScreenHeight)); + mReactApplicationContext + .getNativeModule(UIManagerModule.class) + .getEventDispatcher() + .dispatchEvent( + OnLayoutEvent.obtain(mTag, mScreenX, mScreenY, mScreenWidth, mScreenHeight)); } } @@ -144,20 +131,14 @@ public class UIViewOperationQueue { /** * Operation for updating native view's position and size. The operation is not created directly - * by a {@link UIManagerModule} call from JS. Instead it gets inflated using computed position - * and size values by CSSNodeDEPRECATED hierarchy. + * by a {@link UIManagerModule} call from JS. Instead it gets inflated using computed position and + * size values by CSSNodeDEPRECATED hierarchy. */ private final class UpdateLayoutOperation extends ViewOperation { private final int mParentTag, mX, mY, mWidth, mHeight; - public UpdateLayoutOperation( - int parentTag, - int tag, - int x, - int y, - int width, - int height) { + public UpdateLayoutOperation(int parentTag, int tag, int x, int y, int width, int height) { super(tag); mParentTag = parentTag; mX = x; @@ -195,11 +176,7 @@ public class UIViewOperationQueue { @Override public void execute() { Systrace.endAsyncFlow(Systrace.TRACE_TAG_REACT_VIEW, "createView", mTag); - mNativeViewHierarchyManager.createView( - mThemedContext, - mTag, - mClassName, - mInitialProps); + mNativeViewHierarchyManager.createView(mThemedContext, mTag, mClassName, mInitialProps); } } @@ -226,11 +203,7 @@ public class UIViewOperationQueue { @Override public void execute() { mNativeViewHierarchyManager.manageChildren( - mTag, - mIndicesToRemove, - mViewsToAdd, - mTagsToDelete, - mIndicesToDelete); + mTag, mIndicesToRemove, mViewsToAdd, mTagsToDelete, mIndicesToDelete); } } @@ -238,18 +211,14 @@ public class UIViewOperationQueue { private final ReadableArray mChildrenTags; - public SetChildrenOperation( - int tag, - ReadableArray childrenTags) { + public SetChildrenOperation(int tag, ReadableArray childrenTags) { super(tag); mChildrenTags = childrenTags; } @Override public void execute() { - mNativeViewHierarchyManager.setChildren( - mTag, - mChildrenTags); + mNativeViewHierarchyManager.setChildren(mTag, mChildrenTags); } } @@ -275,10 +244,7 @@ public class UIViewOperationQueue { private final boolean mClearResponder; public ChangeJSResponderOperation( - int tag, - int initialTag, - boolean clearResponder, - boolean blockNativeResponder) { + int tag, int initialTag, boolean clearResponder, boolean blockNativeResponder) { super(tag); mInitialTag = initialTag; mClearResponder = clearResponder; @@ -335,11 +301,7 @@ public class UIViewOperationQueue { private final Callback mError; private final Callback mSuccess; - public ShowPopupMenuOperation( - int tag, - ReadableArray items, - Callback error, - Callback success) { + public ShowPopupMenuOperation(int tag, ReadableArray items, Callback error, Callback success) { super(tag); mItems = items; mError = error; @@ -359,10 +321,8 @@ public class UIViewOperationQueue { } } - /** - * A spec for animation operations (add/remove) - */ - private static abstract class AnimationOperation implements UIViewOperationQueue.UIOperation { + /** A spec for animation operations (add/remove) */ + private abstract static class AnimationOperation implements UIViewOperationQueue.UIOperation { protected final int mAnimationID; @@ -388,7 +348,8 @@ public class UIViewOperationQueue { private final ReadableMap mConfig; private final Callback mAnimationComplete; - private ConfigureLayoutAnimationOperation(final ReadableMap config, final Callback animationComplete) { + private ConfigureLayoutAnimationOperation( + final ReadableMap config, final Callback animationComplete) { mConfig = config; mAnimationComplete = animationComplete; } @@ -404,9 +365,7 @@ public class UIViewOperationQueue { private final int mReactTag; private final Callback mCallback; - private MeasureOperation( - final int reactTag, - final Callback callback) { + private MeasureOperation(final int reactTag, final Callback callback) { super(); mReactTag = reactTag; mCallback = callback; @@ -436,9 +395,7 @@ public class UIViewOperationQueue { private final int mReactTag; private final Callback mCallback; - private MeasureInWindowOperation( - final int reactTag, - final Callback callback) { + private MeasureInWindowOperation(final int reactTag, final Callback callback) { super(); mReactTag = reactTag; mCallback = callback; @@ -471,10 +428,7 @@ public class UIViewOperationQueue { private final Callback mCallback; private FindTargetForTouchOperation( - final int reactTag, - final float targetX, - final float targetY, - final Callback callback) { + final int reactTag, final float targetX, final float targetY, final Callback callback) { super(); mReactTag = reactTag; mTargetX = targetX; @@ -485,9 +439,7 @@ public class UIViewOperationQueue { @Override public void execute() { try { - mNativeViewHierarchyManager.measure( - mReactTag, - mMeasureBuffer); + mNativeViewHierarchyManager.measure(mReactTag, mMeasureBuffer); } catch (IllegalViewOperationException e) { mCallback.invoke(); return; @@ -498,15 +450,11 @@ public class UIViewOperationQueue { final float containerX = (float) mMeasureBuffer[0]; final float containerY = (float) mMeasureBuffer[1]; - final int touchTargetReactTag = mNativeViewHierarchyManager.findTargetTagForTouch( - mReactTag, - mTargetX, - mTargetY); + final int touchTargetReactTag = + mNativeViewHierarchyManager.findTargetTagForTouch(mReactTag, mTargetX, mTargetY); try { - mNativeViewHierarchyManager.measure( - touchTargetReactTag, - mMeasureBuffer); + mNativeViewHierarchyManager.measure(touchTargetReactTag, mMeasureBuffer); } catch (IllegalViewOperationException e) { mCallback.invoke(); return; @@ -525,7 +473,8 @@ public class UIViewOperationQueue { private final ReactShadowNode mNode; private final UIImplementation.LayoutUpdateListener mListener; - private LayoutUpdateFinishedOperation(ReactShadowNode node, UIImplementation.LayoutUpdateListener listener) { + private LayoutUpdateFinishedOperation( + ReactShadowNode node, UIImplementation.LayoutUpdateListener listener) { mNode = node; mListener = listener; } @@ -538,7 +487,8 @@ public class UIViewOperationQueue { private class UIBlockOperation implements UIOperation { private final UIBlock mBlock; - public UIBlockOperation (UIBlock block) { + + public UIBlockOperation(UIBlock block) { mBlock = block; } @@ -652,16 +602,10 @@ public class UIViewOperationQueue { mOperations.add(new RemoveRootViewOperation(rootViewTag)); } - public void enqueueSetJSResponder( - int tag, - int initialTag, - boolean blockNativeResponder) { + public void enqueueSetJSResponder(int tag, int initialTag, boolean blockNativeResponder) { mOperations.add( new ChangeJSResponderOperation( - tag, - initialTag, - false /*clearResponder*/, - blockNativeResponder)); + tag, initialTag, false /*clearResponder*/, blockNativeResponder)); } public void enqueueClearJSResponder() { @@ -670,16 +614,12 @@ public class UIViewOperationQueue { } public void enqueueDispatchCommand( - int reactTag, - int commandId, - @Nullable ReadableArray commandArgs) { + int reactTag, int commandId, @Nullable ReadableArray commandArgs) { mOperations.add(new DispatchCommandOperation(reactTag, commandId, commandArgs)); } public void enqueueDispatchCommand( - int reactTag, - String commandId, - @Nullable ReadableArray commandArgs) { + int reactTag, String commandId, @Nullable ReadableArray commandArgs) { mOperations.add(new DispatchStringCommandOperation(reactTag, commandId, commandArgs)); } @@ -688,10 +628,7 @@ public class UIViewOperationQueue { } public void enqueueShowPopupMenu( - int reactTag, - ReadableArray items, - Callback error, - Callback success) { + int reactTag, ReadableArray items, Callback error, Callback success) { mOperations.add(new ShowPopupMenuOperation(reactTag, items, error, success)); } @@ -706,11 +643,7 @@ public class UIViewOperationQueue { @Nullable ReactStylesDiffMap initialProps) { synchronized (mNonBatchedOperationsLock) { mNonBatchedOperations.addLast( - new CreateViewOperation( - themedContext, - viewReactTag, - viewClassName, - initialProps)); + new CreateViewOperation(themedContext, viewReactTag, viewClassName, initialProps)); } } @@ -723,24 +656,14 @@ public class UIViewOperationQueue { } public void enqueueOnLayoutEvent( - int tag, - int screenX, - int screenY, - int screenWidth, - int screenHeight) { - mOperations.add(new EmitOnLayoutEventOperation(tag, screenX, screenY, screenWidth, screenHeight)); + int tag, int screenX, int screenY, int screenWidth, int screenHeight) { + mOperations.add( + new EmitOnLayoutEventOperation(tag, screenX, screenY, screenWidth, screenHeight)); } - public void enqueueUpdateLayout( - int parentTag, - int reactTag, - int x, - int y, - int width, - int height) { - mOperations.add( - new UpdateLayoutOperation(parentTag, reactTag, x, y, width, height)); + int parentTag, int reactTag, int x, int y, int width, int height) { + mOperations.add(new UpdateLayoutOperation(parentTag, reactTag, x, y, width, height)); } public void enqueueManageChildren( @@ -750,55 +673,42 @@ public class UIViewOperationQueue { @Nullable int[] tagsToDelete, @Nullable int[] indicesToDelete) { mOperations.add( - new ManageChildrenOperation(reactTag, indicesToRemove, viewsToAdd, tagsToDelete, indicesToDelete)); + new ManageChildrenOperation( + reactTag, indicesToRemove, viewsToAdd, tagsToDelete, indicesToDelete)); } - public void enqueueSetChildren( - int reactTag, - ReadableArray childrenTags) { - mOperations.add( - new SetChildrenOperation(reactTag, childrenTags)); + public void enqueueSetChildren(int reactTag, ReadableArray childrenTags) { + mOperations.add(new SetChildrenOperation(reactTag, childrenTags)); } - public void enqueueSetLayoutAnimationEnabled( - final boolean enabled) { + public void enqueueSetLayoutAnimationEnabled(final boolean enabled) { mOperations.add(new SetLayoutAnimationEnabledOperation(enabled)); } public void enqueueConfigureLayoutAnimation( - final ReadableMap config, - final Callback onAnimationComplete) { + final ReadableMap config, final Callback onAnimationComplete) { mOperations.add(new ConfigureLayoutAnimationOperation(config, onAnimationComplete)); } - public void enqueueMeasure( - final int reactTag, - final Callback callback) { - mOperations.add( - new MeasureOperation(reactTag, callback)); + public void enqueueMeasure(final int reactTag, final Callback callback) { + mOperations.add(new MeasureOperation(reactTag, callback)); } - public void enqueueMeasureInWindow( - final int reactTag, - final Callback callback) { - mOperations.add( - new MeasureInWindowOperation(reactTag, callback)); + public void enqueueMeasureInWindow(final int reactTag, final Callback callback) { + mOperations.add(new MeasureInWindowOperation(reactTag, callback)); } public void enqueueFindTargetForTouch( - final int reactTag, - final float targetX, - final float targetY, - final Callback callback) { - mOperations.add( - new FindTargetForTouchOperation(reactTag, targetX, targetY, callback)); + final int reactTag, final float targetX, final float targetY, final Callback callback) { + mOperations.add(new FindTargetForTouchOperation(reactTag, targetX, targetY, callback)); } public void enqueueSendAccessibilityEvent(int tag, int eventType) { mOperations.add(new SendAccessibilityEvent(tag, eventType)); } - public void enqueueLayoutUpdateFinished(ReactShadowNode node, UIImplementation.LayoutUpdateListener listener) { + public void enqueueLayoutUpdateFinished( + ReactShadowNode node, UIImplementation.LayoutUpdateListener listener) { mOperations.add(new LayoutUpdateFinishedOperation(node, listener)); } @@ -813,10 +723,9 @@ public class UIViewOperationQueue { public void dispatchViewUpdates( final int batchId, final long commitStartTime, final long layoutTime) { SystraceMessage.beginSection( - Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, - "UIViewOperationQueue.dispatchViewUpdates") - .arg("batchId", batchId) - .flush(); + Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "UIViewOperationQueue.dispatchViewUpdates") + .arg("batchId", batchId) + .flush(); try { final long dispatchViewUpdatesTime = SystemClock.uptimeMillis(); final long nativeModulesThreadCpuTime = SystemClock.currentThreadTimeMillis(); @@ -914,26 +823,27 @@ public class UIViewOperationQueue { }; SystraceMessage.beginSection( - Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, - "acquiring mDispatchRunnablesLock") - .arg("batchId", batchId) - .flush(); + Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "acquiring mDispatchRunnablesLock") + .arg("batchId", batchId) + .flush(); synchronized (mDispatchRunnablesLock) { Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); mDispatchUIRunnables.add(runOperations); } - // In the case where the frame callback isn't enqueued, the UI isn't being displayed or is being - // destroyed. In this case it's no longer important to align to frames, but it is important to make + // In the case where the frame callback isn't enqueued, the UI isn't being displayed or is + // being + // destroyed. In this case it's no longer important to align to frames, but it is important to + // make // sure any late-arriving UI commands are executed. if (!mIsDispatchUIFrameCallbackEnqueued) { UiThreadUtil.runOnUiThread( - new GuardedRunnable(mReactApplicationContext) { - @Override - public void runGuarded() { - flushPendingBatches(); - } - }); + new GuardedRunnable(mReactApplicationContext) { + @Override + public void runGuarded() { + flushPendingBatches(); + } + }); } } finally { Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); @@ -956,8 +866,8 @@ public class UIViewOperationQueue { private void flushPendingBatches() { if (mIsInIllegalUIState) { FLog.w( - ReactConstants.TAG, - "Not flushing pending UI operations because of previously thrown Exception"); + ReactConstants.TAG, + "Not flushing pending UI operations because of previously thrown Exception"); return; } @@ -997,14 +907,14 @@ public class UIViewOperationQueue { * directly to the UI thread from that method is to make sure our Runnables actually run before * the next traversals happen: * - * ViewRootImpl#scheduleTraversals (which is called from invalidate, requestLayout, etc) calls + *

ViewRootImpl#scheduleTraversals (which is called from invalidate, requestLayout, etc) calls * Looper#postSyncBarrier which keeps any UI thread looper messages from being processed until * that barrier is removed during the next traversal. That means, depending on when we get updates * from JS and what else is happening on the UI thread, we can sometimes try to post this runnable * after ViewRootImpl has posted a barrier. * - * Using a Choreographer callback (which runs immediately before traversals), we guarantee we run - * before the next traversal. + *

Using a Choreographer callback (which runs immediately before traversals), we guarantee we + * run before the next traversal. */ private class DispatchUIFrameCallback extends GuardedFrameCallback { @@ -1021,8 +931,8 @@ public class UIViewOperationQueue { public void doFrameGuarded(long frameTimeNanos) { if (mIsInIllegalUIState) { FLog.w( - ReactConstants.TAG, - "Not flushing pending UI operations because of previously thrown Exception"); + ReactConstants.TAG, + "Not flushing pending UI operations because of previously thrown Exception"); return; } @@ -1035,8 +945,8 @@ public class UIViewOperationQueue { flushPendingBatches(); - ReactChoreographer.getInstance().postFrameCallback( - ReactChoreographer.CallbackType.DISPATCH_UI, this); + ReactChoreographer.getInstance() + .postFrameCallback(ReactChoreographer.CallbackType.DISPATCH_UI, this); } private void dispatchPendingNonBatchedOperations(long frameTimeNanos) { diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewAtIndex.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewAtIndex.java index 685da777a72..562f025b2d3 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewAtIndex.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewAtIndex.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; import java.util.Comparator; @@ -14,12 +13,13 @@ import java.util.Comparator; * operation. */ public class ViewAtIndex { - public static Comparator COMPARATOR = new Comparator() { - @Override - public int compare(ViewAtIndex lhs, ViewAtIndex rhs) { - return lhs.mIndex - rhs.mIndex; - } - }; + public static Comparator COMPARATOR = + new Comparator() { + @Override + public int compare(ViewAtIndex lhs, ViewAtIndex rhs) { + return lhs.mIndex - rhs.mIndex; + } + }; public final int mTag; public final int mIndex; diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewDefaults.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewDefaults.java index 5583e2e9702..69b8216459f 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewDefaults.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewDefaults.java @@ -1,15 +1,12 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; -/** - * Default property values for Views to be shared between Views and ShadowViews. - */ +/** Default property values for Views to be shared between Views and ShadowViews. */ public class ViewDefaults { public static final float FONT_SIZE_SP = 14.0f; diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewGroupDrawingOrderHelper.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewGroupDrawingOrderHelper.java index 457fd227b56..c8872dcee85 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewGroupDrawingOrderHelper.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewGroupDrawingOrderHelper.java @@ -1,24 +1,19 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; import android.view.View; import android.view.ViewGroup; - import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; - import javax.annotation.Nullable; -/** - * Helper to handle implementing ViewGroups with custom drawing order based on z-index. - */ +/** Helper to handle implementing ViewGroups with custom drawing order based on z-index. */ public class ViewGroupDrawingOrderHelper { private final ViewGroup mViewGroup; private int mNumberOfChildrenWithZIndex = 0; @@ -30,6 +25,7 @@ public class ViewGroupDrawingOrderHelper { /** * This should be called every time a view is added to the ViewGroup in {@link ViewGroup#addView}. + * * @param view The view that is being added */ public void handleAddView(View view) { @@ -41,8 +37,9 @@ public class ViewGroupDrawingOrderHelper { } /** - * This should be called every time a view is removed from the ViewGroup in {@link ViewGroup#removeView} - * and {@link ViewGroup#removeViewAt}. + * This should be called every time a view is removed from the ViewGroup in {@link + * ViewGroup#removeView} and {@link ViewGroup#removeViewAt}. + * * @param view The view that is being removed. */ public void handleRemoveView(View view) { @@ -54,17 +51,17 @@ public class ViewGroupDrawingOrderHelper { } /** - * If the ViewGroup should enable drawing order. ViewGroups should call - * {@link ViewGroup#setChildrenDrawingOrderEnabled} with the value returned from this method when - * a view is added or removed. + * If the ViewGroup should enable drawing order. ViewGroups should call {@link + * ViewGroup#setChildrenDrawingOrderEnabled} with the value returned from this method when a view + * is added or removed. */ public boolean shouldEnableCustomDrawingOrder() { return mNumberOfChildrenWithZIndex > 0; } /** - * The index of the child view that should be drawn. This should be used in - * {@link ViewGroup#getChildDrawingOrder}. + * The index of the child view that should be drawn. This should be used in {@link + * ViewGroup#getChildDrawingOrder}. */ public int getChildDrawingOrder(int childCount, int index) { if (mDrawingOrderIndices == null) { @@ -73,22 +70,24 @@ public class ViewGroupDrawingOrderHelper { viewsToSort.add(mViewGroup.getChildAt(i)); } // Sort the views by zIndex - Collections.sort(viewsToSort, new Comparator() { - @Override - public int compare(View view1, View view2) { - Integer view1ZIndex = ViewGroupManager.getViewZIndex(view1); - if (view1ZIndex == null) { - view1ZIndex = 0; - } + Collections.sort( + viewsToSort, + new Comparator() { + @Override + public int compare(View view1, View view2) { + Integer view1ZIndex = ViewGroupManager.getViewZIndex(view1); + if (view1ZIndex == null) { + view1ZIndex = 0; + } - Integer view2ZIndex = ViewGroupManager.getViewZIndex(view2); - if (view2ZIndex == null) { - view2ZIndex = 0; - } + Integer view2ZIndex = ViewGroupManager.getViewZIndex(view2); + if (view2ZIndex == null) { + view2ZIndex = 0; + } - return view1ZIndex - view2ZIndex; - } - }); + return view1ZIndex - view2ZIndex; + } + }); mDrawingOrderIndices = new int[childCount]; for (int i = 0; i < childCount; i++) { @@ -99,9 +98,7 @@ public class ViewGroupDrawingOrderHelper { return mDrawingOrderIndices[index]; } - /** - * Recheck all children for z-index changes. - */ + /** Recheck all children for z-index changes. */ public void update() { mNumberOfChildrenWithZIndex = 0; for (int i = 0; i < mViewGroup.getChildCount(); i++) { diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewGroupManager.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewGroupManager.java index 253c3ef0a94..d72a98edea5 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewGroupManager.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewGroupManager.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; import android.view.View; @@ -13,12 +12,9 @@ import java.util.List; import java.util.WeakHashMap; import javax.annotation.Nullable; -/** - * Class providing children management API for view managers of classes extending ViewGroup. - */ -public abstract class ViewGroupManager - extends BaseViewManager - implements IViewManagerWithChildren { +/** Class providing children management API for view managers of classes extending ViewGroup. */ +public abstract class ViewGroupManager + extends BaseViewManager implements IViewManagerWithChildren { private static WeakHashMap mZIndexHash = new WeakHashMap<>(); @@ -33,16 +29,15 @@ public abstract class ViewGroupManager } @Override - public void updateExtraData(T root, Object extraData) { - } + public void updateExtraData(T root, Object extraData) {} public void addView(T parent, View child, int index) { parent.addView(child, index); } /** - * Convenience method for batching a set of addView calls - * Note that this adds the views to the beginning of the ViewGroup + * Convenience method for batching a set of addView calls Note that this adds the views to the + * beginning of the ViewGroup * * @param parent the parent ViewGroup * @param views the set of views to add @@ -89,14 +84,12 @@ public abstract class ViewGroupManager } /** - * Returns whether this View type needs to handle laying out its own children instead of - * deferring to the standard css-layout algorithm. - * Returns true for the layout to *not* be automatically invoked. Instead onLayout will be - * invoked as normal and it is the View instance's responsibility to properly call layout on its - * children. - * Returns false for the default behavior of automatically laying out children without going - * through the ViewGroup's onLayout method. In that case, onLayout for this View type must *not* - * call layout on its children. + * Returns whether this View type needs to handle laying out its own children instead of deferring + * to the standard css-layout algorithm. Returns true for the layout to *not* be automatically + * invoked. Instead onLayout will be invoked as normal and it is the View instance's + * responsibility to properly call layout on its children. Returns false for the default behavior + * of automatically laying out children without going through the ViewGroup's onLayout method. In + * that case, onLayout for this View type must *not* call layout on its children. */ @Override public boolean needsCustomLayoutForChildren() { @@ -106,8 +99,8 @@ public abstract class ViewGroupManager /** * Returns whether or not this View type should promote its grandchildren as Views. This is an * optimization for Scrollable containers when using Nodes, where instead of having one ViewGroup - * containing a large number of draw commands (and thus being more expensive in the case of - * an invalidate or re-draw), we split them up into several draw commands. + * containing a large number of draw commands (and thus being more expensive in the case of an + * invalidate or re-draw), we split them up into several draw commands. */ public boolean shouldPromoteGrandchildren() { return false; diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewHierarchyDumper.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewHierarchyDumper.java index 2825dd57642..3c3a316430b 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewHierarchyDumper.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewHierarchyDumper.java @@ -1,17 +1,14 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; import android.view.View; import android.view.ViewGroup; - import com.facebook.react.bridge.UiThreadUtil; - import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewManager.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewManager.java index e589954f69f..488efd005fc 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewManager.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewManager.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; import android.content.Context; @@ -20,22 +19,21 @@ import com.facebook.react.uimanager.annotations.ReactPropGroup; import com.facebook.react.uimanager.annotations.ReactPropertyHolder; import com.facebook.yoga.YogaMeasureMode; import java.util.Map; - import javax.annotation.Nonnull; import javax.annotation.Nullable; /** * Class responsible for knowing how to create and update catalyst Views of a given type. It is also - * responsible for creating and updating CSSNodeDEPRECATED subclasses used for calculating position and size - * for the corresponding native view. + * responsible for creating and updating CSSNodeDEPRECATED subclasses used for calculating position + * and size for the corresponding native view. */ @ReactPropertyHolder public abstract class ViewManager - extends BaseJavaModule { + extends BaseJavaModule { /** - * For the vast majority of ViewManagers, you will not need to override this. Only - * override this if you really know what you're doing and have a very unique use-case. + * For the vast majority of ViewManagers, you will not need to override this. Only override this + * if you really know what you're doing and have a very unique use-case. * * @param viewToUpdate * @param props @@ -46,23 +44,18 @@ public abstract class ViewManager onAfterUpdateTransaction(viewToUpdate); } - /** - * Creates a view and installs event emitters on it. - */ + /** Creates a view and installs event emitters on it. */ private final @Nonnull T createView( - @Nonnull ThemedReactContext reactContext, - JSResponderHandler jsResponderHandler) { + @Nonnull ThemedReactContext reactContext, JSResponderHandler jsResponderHandler) { return createView(reactContext, null, null, jsResponderHandler); } - /** - * Creates a view with knowledge of props. - */ + /** Creates a view with knowledge of props. */ public @Nonnull T createView( - @Nonnull ThemedReactContext reactContext, - @Nullable ReactStylesDiffMap props, - @Nullable StateWrapper stateWrapper, - JSResponderHandler jsResponderHandler) { + @Nonnull ThemedReactContext reactContext, + @Nullable ReactStylesDiffMap props, + @Nullable StateWrapper stateWrapper, + JSResponderHandler jsResponderHandler) { T view = createViewInstance(reactContext, props, stateWrapper); addEventEmitters(reactContext, view); if (view instanceof ReactInterceptingViewGroup) { @@ -71,10 +64,9 @@ public abstract class ViewManager return view; } - /** * @return the name of this view manager. This will be the name used to reference this view - * manager from JavaScript in createReactNativeComponentClass. + * manager from JavaScript in createReactNativeComponentClass. */ public abstract @Nonnull String getName(); @@ -95,8 +87,8 @@ public abstract class ViewManager * This method should return {@link Class} instance that represent type of shadow node that this * manager will return from {@link #createShadowNodeInstance}. * - * This method will be used in the bridge initialization phase to collect properties exposed using - * {@link ReactProp} (or {@link ReactPropGroup}) annotation from the {@link ReactShadowNode} + *

This method will be used in the bridge initialization phase to collect properties exposed + * using {@link ReactProp} (or {@link ReactPropGroup}) annotation from the {@link ReactShadowNode} * subclass specific for native view this manager provides. * * @return {@link Class} object that represents type of shadow node used by this view manager. @@ -105,17 +97,22 @@ public abstract class ViewManager /** * Subclasses should return a new View instance of the proper type. + * * @param reactContext */ protected abstract @Nonnull T createViewInstance(@Nonnull ThemedReactContext reactContext); /** - * Subclasses should return a new View instance of the proper type. - * This is an optional method that will call createViewInstance for you. - * Override it if you need props upon creation of the view. + * Subclasses should return a new View instance of the proper type. This is an optional method + * that will call createViewInstance for you. Override it if you need props upon creation of the + * view. + * * @param reactContext */ - protected @Nonnull T createViewInstance(@Nonnull ThemedReactContext reactContext, @Nullable ReactStylesDiffMap initialProps, @Nullable StateWrapper stateWrapper) { + protected @Nonnull T createViewInstance( + @Nonnull ThemedReactContext reactContext, + @Nullable ReactStylesDiffMap initialProps, + @Nullable StateWrapper stateWrapper) { T view = createViewInstance(reactContext); if (initialProps != null) { updateProperties(view, initialProps); @@ -124,70 +121,65 @@ public abstract class ViewManager } /** - * Called when view is detached from view hierarchy and allows for some additional cleanup by - * the {@link ViewManager} subclass. + * Called when view is detached from view hierarchy and allows for some additional cleanup by the + * {@link ViewManager} subclass. */ - public void onDropViewInstance(@Nonnull T view) { - } + public void onDropViewInstance(@Nonnull T view) {} /** * Subclasses can override this method to install custom event emitters on the given View. You * might want to override this method if your view needs to emit events besides basic touch events * to JS (e.g. scroll events). */ - protected void addEventEmitters(@Nonnull ThemedReactContext reactContext, @Nonnull T view) { - } + protected void addEventEmitters(@Nonnull ThemedReactContext reactContext, @Nonnull T view) {} /** * Callback that will be triggered after all properties are updated in current update transaction * (all @ReactProp handlers for properties updated in current transaction have been called). If - * you want to override this method you should call super.onAfterUpdateTransaction from it as - * the parent class of the ViewManager may rely on callback being executed. + * you want to override this method you should call super.onAfterUpdateTransaction from it as the + * parent class of the ViewManager may rely on callback being executed. */ - protected void onAfterUpdateTransaction(@Nonnull T view) { - } + protected void onAfterUpdateTransaction(@Nonnull T view) {} /** * Subclasses can implement this method to receive an optional extra data enqueued from the - * corresponding instance of {@link ReactShadowNode} in - * {@link ReactShadowNode#onCollectExtraUpdates}. + * corresponding instance of {@link ReactShadowNode} in {@link + * ReactShadowNode#onCollectExtraUpdates}. * - * Since css layout step and ui updates can be executed in separate thread apart of setting + *

Since css layout step and ui updates can be executed in separate thread apart of setting * x/y/width/height this is the recommended and thread-safe way of passing extra data from css * node to the native view counterpart. * - * TODO(7247021): Replace updateExtraData with generic update props mechanism after D2086999 + *

TODO(7247021): Replace updateExtraData with generic update props mechanism after D2086999 */ public abstract void updateExtraData(@Nonnull T root, Object extraData); /** - * Subclasses may use this method to receive events/commands directly from JS through the - * {@link UIManager}. Good example of such a command would be {@code scrollTo} request with - * coordinates for a {@link ScrollView} instance. + * Subclasses may use this method to receive events/commands directly from JS through the {@link + * UIManager}. Good example of such a command would be {@code scrollTo} request with coordinates + * for a {@link ScrollView} instance. * * @param root View instance that should receive the command * @param commandId code of the command * @param args optional arguments for the command */ - public void receiveCommand(@Nonnull T root, int commandId, @Nullable ReadableArray args) { - } + public void receiveCommand(@Nonnull T root, int commandId, @Nullable ReadableArray args) {} /** - * Subclasses may use this method to receive events/commands directly from JS through the - * {@link UIManager}. Good example of such a command would be {@code scrollTo} request with - * coordinates for a {@link ScrollView} instance. + * Subclasses may use this method to receive events/commands directly from JS through the {@link + * UIManager}. Good example of such a command would be {@code scrollTo} request with coordinates + * for a {@link ScrollView} instance. * * @param root View instance that should receive the command * @param commandId code of the command * @param args optional arguments for the command */ - public void receiveCommand(@Nonnull T root, String commandId, @Nullable ReadableArray args) { - } + public void receiveCommand(@Nonnull T root, String commandId, @Nullable ReadableArray args) {} /** - * Subclasses of {@link ViewManager} that expect to receive commands through - * {@link UIManagerModule#dispatchViewManagerCommand} should override this method returning the - * map between names of the commands and IDs that are then used in {@link #receiveCommand} method + * Subclasses of {@link ViewManager} that expect to receive commands through {@link + * UIManagerModule#dispatchViewManagerCommand} should override this method returning the map + * between names of the commands and IDs that are then used in {@link #receiveCommand} method * whenever the command is dispatched for this particular {@link ViewManager}. * * @return map of string to int mapping of the expected commands @@ -201,15 +193,8 @@ public abstract class ViewManager * native views. This should return bubbling directly-dispatched event types and specify what * names should be used to subscribe to either form (bubbling/capturing). * - * Returned map should be of the form: - * { - * "onTwirl": { - * "phasedRegistrationNames": { - * "bubbled": "onTwirl", - * "captured": "onTwirlCaptured" - * } - * } - * } + *

Returned map should be of the form: { "onTwirl": { "phasedRegistrationNames": { "bubbled": + * "onTwirl", "captured": "onTwirlCaptured" } } } */ public @Nullable Map getExportedCustomBubblingEventTypeConstants() { return null; @@ -219,12 +204,7 @@ public abstract class ViewManager * Returns a map of config data passed to JS that defines eligible events that can be placed on * native views. This should return non-bubbling directly-dispatched event types. * - * Returned map should be of the form: - * { - * "onTwirl": { - * "registrationName": "onTwirl" - * } - * } + *

Returned map should be of the form: { "onTwirl": { "registrationName": "onTwirl" } } */ public @Nullable Map getExportedCustomDirectEventTypeConstants() { return null; @@ -242,16 +222,16 @@ public abstract class ViewManager return ViewManagerPropertyUpdater.getNativeProps(getClass(), getShadowNodeClass()); } - public @Nullable Object updateLocalData( @Nonnull T view, ReactStylesDiffMap props, ReactStylesDiffMap localData) { + public @Nullable Object updateLocalData( + @Nonnull T view, ReactStylesDiffMap props, ReactStylesDiffMap localData) { return null; } /** - * Subclasses can implement this method to receive state updates shared between all instances - * of this component type. + * Subclasses can implement this method to receive state updates shared between all instances of + * this component type. */ - public void updateState(@Nonnull T view, StateWrapper stateWrapper) { - } + public void updateState(@Nonnull T view, StateWrapper stateWrapper) {} public long measure( Context context, diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewManagerPropertyUpdater.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewManagerPropertyUpdater.java index 6ab0cdb7a00..bb1d5588d69 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewManagerPropertyUpdater.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewManagerPropertyUpdater.java @@ -5,18 +5,12 @@ package com.facebook.react.uimanager; +import android.view.View; +import com.facebook.common.logging.FLog; import java.util.HashMap; import java.util.Iterator; import java.util.Map; -import android.view.View; - -import com.facebook.common.logging.FLog; -import com.facebook.react.bridge.Dynamic; -import com.facebook.react.bridge.ReadableArray; -import com.facebook.react.bridge.ReadableMap; -import com.facebook.react.bridge.ReadableMapKeySetIterator; - public class ViewManagerPropertyUpdater { public interface Settable { void getProperties(Map props); diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewManagerRegistry.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewManagerRegistry.java index b657eb5918c..fb202d48e7b 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewManagerRegistry.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewManagerRegistry.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; import com.facebook.react.common.MapBuilder; diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewManagersPropertyCache.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewManagersPropertyCache.java index 20e48f91902..f4fe8a45ee4 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewManagersPropertyCache.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewManagersPropertyCache.java @@ -163,7 +163,7 @@ import javax.annotation.Nullable; @Override protected Object getValueOrDefault(Object value) { // All numbers from JS are Doubles which can't be simply cast to Integer - return value == null ? mDefaultValue : (Integer) ((Double)value).intValue(); + return value == null ? mDefaultValue : (Integer) ((Double) value).intValue(); } } @@ -220,7 +220,7 @@ import javax.annotation.Nullable; @Override protected Object getValueOrDefault(Object value) { // All numbers from JS are Doubles which can't be simply cast to Float - return value == null ? mDefaultValue : (Float) ((Double)value).floatValue(); + return value == null ? mDefaultValue : (Float) ((Double) value).floatValue(); } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewProps.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewProps.java index 6f0feb0302a..2828dce3f77 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewProps.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewProps.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; import android.graphics.Color; @@ -12,9 +11,7 @@ import com.facebook.react.bridge.ReadableMap; import java.util.Arrays; import java.util.HashSet; -/** - * Keys for props that need to be shared across multiple classes. - */ +/** Keys for props that need to be shared across multiple classes. */ public class ViewProps { public static final String VIEW_CLASS_NAME = "RCTView"; @@ -231,19 +228,21 @@ public class ViewProps { return false; } if (map.hasKey(BORDER_WIDTH) - && !map.isNull(BORDER_WIDTH) - && map.getDouble(BORDER_WIDTH) != 0d) { + && !map.isNull(BORDER_WIDTH) + && map.getDouble(BORDER_WIDTH) != 0d) { return false; } return true; case BORDER_LEFT_COLOR: return !map.isNull(BORDER_LEFT_COLOR) && map.getInt(BORDER_LEFT_COLOR) == Color.TRANSPARENT; case BORDER_RIGHT_COLOR: - return !map.isNull(BORDER_RIGHT_COLOR) && map.getInt(BORDER_RIGHT_COLOR) == Color.TRANSPARENT; + return !map.isNull(BORDER_RIGHT_COLOR) + && map.getInt(BORDER_RIGHT_COLOR) == Color.TRANSPARENT; case BORDER_TOP_COLOR: return !map.isNull(BORDER_TOP_COLOR) && map.getInt(BORDER_TOP_COLOR) == Color.TRANSPARENT; case BORDER_BOTTOM_COLOR: - return !map.isNull(BORDER_BOTTOM_COLOR) && map.getInt(BORDER_BOTTOM_COLOR) == Color.TRANSPARENT; + return !map.isNull(BORDER_BOTTOM_COLOR) + && map.getInt(BORDER_BOTTOM_COLOR) == Color.TRANSPARENT; case BORDER_WIDTH: return map.isNull(BORDER_WIDTH) || map.getDouble(BORDER_WIDTH) == 0d; case BORDER_LEFT_WIDTH: @@ -258,6 +257,6 @@ public class ViewProps { return map.isNull(OVERFLOW) || VISIBLE.equals(map.getString(OVERFLOW)); default: return false; - } + } } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/YogaNodePool.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/YogaNodePool.java index 5b235cb4bf2..82ed49fbbaf 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/YogaNodePool.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/YogaNodePool.java @@ -5,12 +5,10 @@ package com.facebook.react.uimanager; -import com.facebook.yoga.YogaNode; import com.facebook.react.common.ClearableSynchronizedPool; +import com.facebook.yoga.YogaNode; -/** - * Static holder for a recycling pool of YogaNodes. - */ +/** Static holder for a recycling pool of YogaNodes. */ public class YogaNodePool { private static final Object sInitLock = new Object(); diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/annotations/ReactProp.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/annotations/ReactProp.java index 3a57c319891..0dbee5697c9 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/annotations/ReactProp.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/annotations/ReactProp.java @@ -5,40 +5,36 @@ package com.facebook.react.uimanager.annotations; -import javax.annotation.Nullable; +import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.Target; - -import static java.lang.annotation.RetentionPolicy.RUNTIME; +import javax.annotation.Nullable; /** * Use this annotation to annotate properties of native views that should be exposed to JS. This - * annotation should only be used for setter methods of subclasses of - * {@link com.facebook.react.uimanager.ViewManager}. + * annotation should only be used for setter methods of subclasses of {@link + * com.facebook.react.uimanager.ViewManager}. * - * Each annotated method should return {@code void} and take exactly two arguments: first being - * a view instance to be updated and second a value that should be set. + *

Each annotated method should return {@code void} and take exactly two arguments: first being a + * view instance to be updated and second a value that should be set. * - * Allowed types of values are: - * - primitives (int, boolean, double, float) - * - {@link String} - * - {@link Boolean} - * - {@link com.facebook.react.bridge.ReadableArray} - * - {@link com.facebook.react.bridge.ReadableMap} + *

Allowed types of values are: - primitives (int, boolean, double, float) - {@link String} - + * {@link Boolean} - {@link com.facebook.react.bridge.ReadableArray} - {@link + * com.facebook.react.bridge.ReadableMap} * - * When property gets removed from the corresponding component in React, annotated setter will be + *

When property gets removed from the corresponding component in React, annotated setter will be * called with {@code null} in case of non-primitive value type or with a default value in case when * the value type is a primitive (use appropriate default field of this annotation to customize * default value that is going to be used: {@link #defaultBoolean}, {@link #defaultDouble}, etc.) * - * Since in case of property removal for non-primitive value type setter will be called with value - * set to {@code null} it's required that value type is annotated with {@link Nullable}. + *

Since in case of property removal for non-primitive value type setter will be called with + * value set to {@code null} it's required that value type is annotated with {@link Nullable}. * - * Note: Since boolean property type can be represented both as primitive and wrapped default value - * set through {@link #defaultBoolean} is only respected for primitive type and for the wrapped type - * {@code null} will be used as a default. + *

Note: Since boolean property type can be represented both as primitive and wrapped default + * value set through {@link #defaultBoolean} is only respected for primitive type and for the + * wrapped type {@code null} will be used as a default. */ @Retention(RUNTIME) @Target(ElementType.METHOD) @@ -51,47 +47,48 @@ public @interface ReactProp { String USE_DEFAULT_TYPE = "__default_type__"; /** - * Name of the property exposed to JS that will be updated using setter method annotated with - * the given instance of {@code ReactProp} annotation + * Name of the property exposed to JS that will be updated using setter method annotated with the + * given instance of {@code ReactProp} annotation */ String name(); /** * Type of property that will be send to JS. In most of the cases {@code customType} should not be * set in which case default type will be send to JS based on the type of value argument from the - * setter method (e.g. for {@code int}, {@code double} default is "number", for - * {@code ReadableArray} it's "Array"). Custom type may be used when additional processing of the - * value needs to be done in JS before sending it over the bridge. A good example of that would be - * backgroundColor property, which is expressed as a {@code String} in JS, but we use - * {@code processColor} JS module to convert it to {@code int} before sending over the bridge. + * setter method (e.g. for {@code int}, {@code double} default is "number", for {@code + * ReadableArray} it's "Array"). Custom type may be used when additional processing of the value + * needs to be done in JS before sending it over the bridge. A good example of that would be + * backgroundColor property, which is expressed as a {@code String} in JS, but we use {@code + * processColor} JS module to convert it to {@code int} before sending over the bridge. */ - @Nullable String customType() default USE_DEFAULT_TYPE; + @Nullable + String customType() default USE_DEFAULT_TYPE; /** * Default value for property of type {@code double}. This value will be provided to property - * setter method annotated with {@link ReactProp} if property with a given name gets removed - * from the component description in JS + * setter method annotated with {@link ReactProp} if property with a given name gets removed from + * the component description in JS */ double defaultDouble() default 0.0; /** * Default value for property of type {@code float}. This value will be provided to property - * setter method annotated with {@link ReactProp} if property with a given name gets removed - * from the component description in JS + * setter method annotated with {@link ReactProp} if property with a given name gets removed from + * the component description in JS */ float defaultFloat() default 0.0f; /** - * Default value for property of type {@code int}. This value will be provided to property - * setter method annotated with {@link ReactProp} if property with a given name gets removed - * from the component description in JS + * Default value for property of type {@code int}. This value will be provided to property setter + * method annotated with {@link ReactProp} if property with a given name gets removed from the + * component description in JS */ int defaultInt() default 0; /** * Default value for property of type {@code boolean}. This value will be provided to property - * setter method annotated with {@link ReactProp} if property with a given name gets removed - * from the component description in JS + * setter method annotated with {@link ReactProp} if property with a given name gets removed from + * the component description in JS */ boolean defaultBoolean() default false; } diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/annotations/ReactPropGroup.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/annotations/ReactPropGroup.java index fb623dd50c0..55c64dccfaf 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/annotations/ReactPropGroup.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/annotations/ReactPropGroup.java @@ -5,39 +5,37 @@ package com.facebook.react.uimanager.annotations; -import javax.annotation.Nullable; +import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.Target; - -import static java.lang.annotation.RetentionPolicy.RUNTIME; +import javax.annotation.Nullable; /** * Use this annotation to annotate group of properties of native views that should be exposed to JS. - * This annotation should only be used for setter methods of subclasses of - * {@link com.facebook.react.uimanager.ViewManager}. It's a batched version of {@link ReactProp} - * annotation (please see documentation of {@link ReactProp} for more details about how this - * annotation can be used). + * This annotation should only be used for setter methods of subclasses of {@link + * com.facebook.react.uimanager.ViewManager}. It's a batched version of {@link ReactProp} annotation + * (please see documentation of {@link ReactProp} for more details about how this annotation can be + * used). * - * This annotation is meant to be used for a group of similar properties. That's why it support only - * a set of properties of the same type. A good example is supporting "border", where we have 7 + *

This annotation is meant to be used for a group of similar properties. That's why it support + * only a set of properties of the same type. A good example is supporting "border", where we have 7 * variations of that property ("borderLeft", "borderHorizontal", etc.) and very similar code for * handling each of those. * - * Each annotated method should return {@code void} and take exactly three arguments: first being - * a view instance to be updated, second should be of type int and will represent index in the - * group of the property being updated. Last, third argument represent the value that should be set. + *

Each annotated method should return {@code void} and take exactly three arguments: first being + * a view instance to be updated, second should be of type int and will represent index in the group + * of the property being updated. Last, third argument represent the value that should be set. * - * - * Currently only {@code int}, {@code float}, {@code double} and {@link String} value types are + *

Currently only {@code int}, {@code float}, {@code double} and {@link String} value types are * supported. * - * In case when property has been removed from the corresponding react component annotated setter + *

In case when property has been removed from the corresponding react component annotated setter * will be called and default value will be provided as a value parameter. Default value can be - * customize using {@link #defaultInt} or {@link #defaultFloat} in the case when property is of - * one of primitive types. In case when {@link String} is the property type {@code null} value will - * be provided as a default. + * customize using {@link #defaultInt} or {@link #defaultFloat} in the case when property is of one + * of primitive types. In case when {@link String} is the property type {@code null} value will be + * provided as a default. */ @Retention(RUNTIME) @Target(ElementType.METHOD) @@ -64,7 +62,8 @@ public @interface ReactPropGroup { * {@code String} in JS, but we use {@code processColor} JS module to convert it to {@code int} * before sending over the bridge. */ - @Nullable String customType() default USE_DEFAULT_TYPE; + @Nullable + String customType() default USE_DEFAULT_TYPE; /** * Default value for property of type {@code float}. This value will be provided to property @@ -81,9 +80,9 @@ public @interface ReactPropGroup { double defaultDouble() default 0.0; /** - * Default value for property of type {@code int}. This value will be provided to property - * setter method annotated with {@link ReactPropGroup} if property with a given name gets removed - * from the component description in JS + * Default value for property of type {@code int}. This value will be provided to property setter + * method annotated with {@link ReactPropGroup} if property with a given name gets removed from + * the component description in JS */ int defaultInt() default 0; } diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/annotations/ReactPropertyHolder.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/annotations/ReactPropertyHolder.java index 7b6476187db..ba940ddf93e 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/annotations/ReactPropertyHolder.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/annotations/ReactPropertyHolder.java @@ -14,5 +14,4 @@ import java.lang.annotation.Target; @Inherited @Retention(RetentionPolicy.CLASS) @Target(ElementType.TYPE) -public @interface ReactPropertyHolder { -} +public @interface ReactPropertyHolder {} diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/common/UIManagerType.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/common/UIManagerType.java index 9d8f920b84f..03c4e94f5b5 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/common/UIManagerType.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/common/UIManagerType.java @@ -1,17 +1,17 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ package com.facebook.react.uimanager.common; -import static com.facebook.react.uimanager.common.UIManagerType.FABRIC; import static com.facebook.react.uimanager.common.UIManagerType.DEFAULT; +import static com.facebook.react.uimanager.common.UIManagerType.FABRIC; import static java.lang.annotation.RetentionPolicy.SOURCE; -import java.lang.annotation.Retention; import androidx.annotation.IntDef; +import java.lang.annotation.Retention; @Retention(SOURCE) @IntDef({DEFAULT, FABRIC}) diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/common/ViewUtil.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/common/ViewUtil.java index 2333fccc10f..bae8db66330 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/common/ViewUtil.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/common/ViewUtil.java @@ -1,21 +1,19 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager.common; -import static com.facebook.react.uimanager.common.UIManagerType.FABRIC; import static com.facebook.react.uimanager.common.UIManagerType.DEFAULT; +import static com.facebook.react.uimanager.common.UIManagerType.FABRIC; public class ViewUtil { /** - * Counter for uniquely identifying views. - * - % 2 === 0 means it is a Fabric tag. - * See https://github.com/facebook/react/pull/12587 + * Counter for uniquely identifying views. - % 2 === 0 means it is a Fabric tag. See + * https://github.com/facebook/react/pull/12587 * * @param reactTag {@link } */ @@ -33,5 +31,4 @@ public class ViewUtil { public static boolean isRootTag(int reactTag) { return reactTag % 10 == 1; } - } diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/debug/NotThreadSafeViewHierarchyUpdateDebugListener.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/debug/NotThreadSafeViewHierarchyUpdateDebugListener.java index ff695b8db11..f45769b1d69 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/debug/NotThreadSafeViewHierarchyUpdateDebugListener.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/debug/NotThreadSafeViewHierarchyUpdateDebugListener.java @@ -1,19 +1,18 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager.debug; import com.facebook.react.uimanager.UIManagerModule; /** - * A listener that is notified about view hierarchy update events. This listener should only be - * used for debug purposes and should not affect application state. + * A listener that is notified about view hierarchy update events. This listener should only be used + * for debug purposes and should not affect application state. * - * NB: while onViewHierarchyUpdateFinished will always be called from the UI thread, there are no + *

NB: while onViewHierarchyUpdateFinished will always be called from the UI thread, there are no * guarantees what thread onViewHierarchyUpdateEnqueued is called on. */ public interface NotThreadSafeViewHierarchyUpdateDebugListener { @@ -23,8 +22,6 @@ public interface NotThreadSafeViewHierarchyUpdateDebugListener { */ void onViewHierarchyUpdateEnqueued(); - /** - * Called from the main thread after a UI batch has been applied to all root views. - */ + /** Called from the main thread after a UI batch has been applied to all root views. */ void onViewHierarchyUpdateFinished(); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/BatchEventDispatchedListener.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/BatchEventDispatchedListener.java index f7ce2baccf9..f6bf5ad291a 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/BatchEventDispatchedListener.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/BatchEventDispatchedListener.java @@ -1,16 +1,13 @@ /** * Copyright (c) 2014-present, Facebook, Inc. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ package com.facebook.react.uimanager.events; public interface BatchEventDispatchedListener { - /** - * Called after a batch of low priority events has been dispatched. - */ + /** Called after a batch of low priority events has been dispatched. */ void onBatchEventDispatched(); - } diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/ContentSizeChangeEvent.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/ContentSizeChangeEvent.java index 9462bcf6264..7fbea7976c0 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/ContentSizeChangeEvent.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/ContentSizeChangeEvent.java @@ -9,9 +9,7 @@ import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.WritableMap; import com.facebook.react.uimanager.PixelUtil; -/** - * Event dispatched when total width or height of a view's children changes - */ +/** Event dispatched when total width or height of a view's children changes */ public class ContentSizeChangeEvent extends Event { public static final String EVENT_NAME = "topContentSizeChange"; diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/Event.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/Event.java index 8d5b3aaa97c..9204943c461 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/Event.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/Event.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager.events; import com.facebook.react.common.SystemClock; @@ -12,9 +11,9 @@ import com.facebook.react.common.SystemClock; /** * A UI event that can be dispatched to JS. * - * For dispatching events {@link EventDispatcher#dispatchEvent} should be used. Once event object - * is passed to the EventDispatched it should no longer be used as EventDispatcher may decide - * to recycle that object (by calling {@link #dispose}). + *

For dispatching events {@link EventDispatcher#dispatchEvent} should be used. Once event object + * is passed to the EventDispatched it should no longer be used as EventDispatcher may decide to + * recycle that object (by calling {@link #dispose}). */ public abstract class Event { @@ -25,49 +24,43 @@ public abstract class Event { private long mTimestampMs; private int mUniqueID = sUniqueID++; - protected Event() { - } + protected Event() {} protected Event(int viewTag) { init(viewTag); } - /** - * This method needs to be called before event is sent to event dispatcher. - */ + /** This method needs to be called before event is sent to event dispatcher. */ protected void init(int viewTag) { mViewTag = viewTag; mTimestampMs = SystemClock.uptimeMillis(); mInitialized = true; } - /** - * @return the view id for the view that generated this event - */ + /** @return the view id for the view that generated this event */ public final int getViewTag() { return mViewTag; } /** * @return the time at which the event happened in the {@link android.os.SystemClock#uptimeMillis} - * base. + * base. */ public final long getTimestampMs() { return mTimestampMs; } - /** - * @return false if this Event can *never* be coalesced - */ + /** @return false if this Event can *never* be coalesced */ public boolean canCoalesce() { return true; } /** * Given two events, coalesce them into a single event that will be sent to JS instead of two - * separate events. By default, just chooses the one the is more recent, or {@code this} if timestamps are the same. + * separate events. By default, just chooses the one the is more recent, or {@code this} if + * timestamps are the same. * - * Two events will only ever try to be coalesced if they have the same event name, view id, and + *

Two events will only ever try to be coalesced if they have the same event name, view id, and * coalescing key. */ public T coalesce(T otherEvent) { @@ -76,16 +69,14 @@ public abstract class Event { /** * @return a key used to determine which other events of this type this event can be coalesced - * with. For example, touch move events should only be coalesced within a single gesture so a - * coalescing key there would be the unique gesture id. + * with. For example, touch move events should only be coalesced within a single gesture so a + * coalescing key there would be the unique gesture id. */ public short getCoalescingKey() { return 0; } - /** - * @return The unique id of this event. - */ + /** @return The unique id of this event. */ public int getUniqueID() { return mUniqueID; } @@ -94,8 +85,7 @@ public abstract class Event { * Called when the EventDispatcher is done with an event, either because it was dispatched or * because it was coalesced with another Event. */ - public void onDispose() { - } + public void onDispose() {} /*package*/ boolean isInitialized() { return mInitialized; @@ -106,13 +96,9 @@ public abstract class Event { onDispose(); } - /** - * @return the name of this event as registered in JS - */ + /** @return the name of this event as registered in JS */ public abstract String getEventName(); - /** - * Dispatch this event to JS using the given event emitter. - */ + /** Dispatch this event to JS using the given event emitter. */ public abstract void dispatch(RCTEventEmitter rctEventEmitter); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/EventDispatcher.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/EventDispatcher.java index d322e3eccfc..d72f4b36f41 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/EventDispatcher.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/EventDispatcher.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager.events; import android.util.LongSparseArray; @@ -29,58 +28,57 @@ import java.util.concurrent.atomic.AtomicInteger; * intermediary between UI code generating events and JS, making sure we don't send more events than * JS can process. * - * To use it, create a subclass of {@link Event} and call {@link #dispatchEvent(Event)} whenever + *

To use it, create a subclass of {@link Event} and call {@link #dispatchEvent(Event)} whenever * there's a UI event to dispatch. * - * This class works by installing a Choreographer frame callback on the main thread. This callback - * then enqueues a runnable on the JS thread (if one is not already pending) that is responsible for - * actually dispatch events to JS. This implementation depends on the properties that - * 1) FrameCallbacks run after UI events have been processed in Choreographer.java - * 2) when we enqueue a runnable on the JS queue thread, it won't be called until after any - * previously enqueued JS jobs have finished processing + *

This class works by installing a Choreographer frame callback on the main thread. This + * callback then enqueues a runnable on the JS thread (if one is not already pending) that is + * responsible for actually dispatch events to JS. This implementation depends on the properties + * that 1) FrameCallbacks run after UI events have been processed in Choreographer.java 2) when we + * enqueue a runnable on the JS queue thread, it won't be called until after any previously enqueued + * JS jobs have finished processing * - * If JS is taking a long time processing events, then the UI events generated on the UI thread can - * be coalesced into fewer events so that when the runnable runs, we don't overload JS with a ton - * of events and make it get even farther behind. + *

If JS is taking a long time processing events, then the UI events generated on the UI thread + * can be coalesced into fewer events so that when the runnable runs, we don't overload JS with a + * ton of events and make it get even farther behind. * - * Ideally, we don't need this and JS is fast enough to process all the events each frame, but bad - * things happen, including load on CPUs from the system, and we should handle this case well. + *

Ideally, we don't need this and JS is fast enough to process all the events each frame, but + * bad things happen, including load on CPUs from the system, and we should handle this case well. * - * == Event Cookies == + *

== Event Cookies == * - * An event cookie is made up of the event type id, view tag, and a custom coalescing key. Only + *

An event cookie is made up of the event type id, view tag, and a custom coalescing key. Only * Events that have the same cookie can be coalesced. * - * Event Cookie Composition: - * VIEW_TAG_MASK = 0x00000000ffffffff - * EVENT_TYPE_ID_MASK = 0x0000ffff00000000 - * COALESCING_KEY_MASK = 0xffff000000000000 + *

Event Cookie Composition: VIEW_TAG_MASK = 0x00000000ffffffff EVENT_TYPE_ID_MASK = + * 0x0000ffff00000000 COALESCING_KEY_MASK = 0xffff000000000000 */ public class EventDispatcher implements LifecycleEventListener { - private static final Comparator EVENT_COMPARATOR = new Comparator() { - @Override - public int compare(Event lhs, Event rhs) { - if (lhs == null && rhs == null) { - return 0; - } - if (lhs == null) { - return -1; - } - if (rhs == null) { - return 1; - } + private static final Comparator EVENT_COMPARATOR = + new Comparator() { + @Override + public int compare(Event lhs, Event rhs) { + if (lhs == null && rhs == null) { + return 0; + } + if (lhs == null) { + return -1; + } + if (rhs == null) { + return 1; + } - long diff = lhs.getTimestampMs() - rhs.getTimestampMs(); - if (diff == 0) { - return 0; - } else if (diff < 0) { - return -1; - } else { - return 1; - } - } - }; + long diff = lhs.getTimestampMs() - rhs.getTimestampMs(); + if (diff == 0) { + return 0; + } else if (diff < 0) { + return -1; + } else { + return 1; + } + } + }; private final Object mEventsStagingLock = new Object(); private final Object mEventsToDispatchLock = new Object(); @@ -92,7 +90,7 @@ public class EventDispatcher implements LifecycleEventListener { private final ArrayList mListeners = new ArrayList<>(); private final List mPostEventDispatchListeners = new ArrayList<>(); private final ScheduleDispatchFrameCallback mCurrentFrameCallback = - new ScheduleDispatchFrameCallback(); + new ScheduleDispatchFrameCallback(); private final AtomicInteger mHasDispatchScheduledCount = new AtomicInteger(); private Event[] mEventsToDispatch = new Event[16]; @@ -107,9 +105,7 @@ public class EventDispatcher implements LifecycleEventListener { mReactEventEmitter = new ReactEventEmitter(mReactContext); } - /** - * Sends the given Event to JS, coalescing eligible events if JS is backed up. - */ + /** Sends the given Event to JS, coalescing eligible events if JS is backed up. */ public void dispatchEvent(Event event) { Assertions.assertCondition(event.isInitialized(), "Dispatched event hasn't been initialized"); @@ -120,9 +116,7 @@ public class EventDispatcher implements LifecycleEventListener { synchronized (mEventsStagingLock) { mEventStaging.add(event); Systrace.startAsyncFlow( - Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, - event.getEventName(), - event.getUniqueID()); + Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, event.getEventName(), event.getUniqueID()); } maybePostFrameCallbackFromNonUI(); } @@ -144,16 +138,12 @@ public class EventDispatcher implements LifecycleEventListener { } } - /** - * Add a listener to this EventDispatcher. - */ + /** Add a listener to this EventDispatcher. */ public void addListener(EventDispatcherListener listener) { mListeners.add(listener); } - /** - * Remove a listener from this EventDispatcher. - */ + /** Remove a listener from this EventDispatcher. */ public void removeListener(EventDispatcherListener listener) { mListeners.remove(listener); } @@ -182,12 +172,13 @@ public class EventDispatcher implements LifecycleEventListener { } public void onCatalystInstanceDestroyed() { - UiThreadUtil.runOnUiThread(new Runnable() { - @Override - public void run() { - stopFrameCallback(); - } - }); + UiThreadUtil.runOnUiThread( + new Runnable() { + @Override + public void run() { + stopFrameCallback(); + } + }); } private void stopFrameCallback() { @@ -212,10 +203,8 @@ public class EventDispatcher implements LifecycleEventListener { continue; } - long eventCookie = getEventCookie( - event.getViewTag(), - event.getEventName(), - event.getCoalescingKey()); + long eventCookie = + getEventCookie(event.getViewTag(), event.getEventName(), event.getCoalescingKey()); Event eventToAdd = null; Event eventToDispose = null; @@ -262,9 +251,9 @@ public class EventDispatcher implements LifecycleEventListener { } private static long getEventCookie(int viewTag, short eventTypeId, short coalescingKey) { - return viewTag | - (((long) eventTypeId) & 0xffff) << 32 | - (((long) coalescingKey) & 0xffff) << 48; + return viewTag + | (((long) eventTypeId) & 0xffff) << 32 + | (((long) coalescingKey) & 0xffff) << 48; } public void registerEventEmitter(@UIManagerType int uiManagerType, RCTEventEmitter eventEmitter) { @@ -331,12 +320,13 @@ public class EventDispatcher implements LifecycleEventListener { if (mReactContext.isOnUiQueueThread()) { maybePost(); } else { - mReactContext.runOnUiQueueThread(new Runnable() { - @Override - public void run() { - maybePost(); - } - }); + mReactContext.runOnUiQueueThread( + new Runnable() { + @Override + public void run() { + maybePost(); + } + }); } } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/EventDispatcherListener.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/EventDispatcherListener.java index 524b39ecb63..00ba043e229 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/EventDispatcherListener.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/EventDispatcherListener.java @@ -5,13 +5,12 @@ package com.facebook.react.uimanager.events; -/** - * Interface used to intercept events dispatched by {#link EventDispatcher} - */ +/** Interface used to intercept events dispatched by {#link EventDispatcher} */ public interface EventDispatcherListener { /** - * Called on every time an event is dispatched using {#link EventDispatcher#dispatchEvent}. Will be - * called from the same thread that the event is being dispatched from. + * Called on every time an event is dispatched using {#link EventDispatcher#dispatchEvent}. Will + * be called from the same thread that the event is being dispatched from. + * * @param event Event that was dispatched */ void onEventDispatch(Event event); diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/NativeGestureUtil.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/NativeGestureUtil.java index 1604b951aa3..db9df9aef20 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/NativeGestureUtil.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/NativeGestureUtil.java @@ -1,20 +1,16 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager.events; import android.view.MotionEvent; import android.view.View; - import com.facebook.react.uimanager.RootViewUtil; -/** - * Utilities for native Views that interpret native gestures (e.g. ScrollView, ViewPager, etc.). - */ +/** Utilities for native Views that interpret native gestures (e.g. ScrollView, ViewPager, etc.). */ public class NativeGestureUtil { /** diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/RCTEventEmitter.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/RCTEventEmitter.java index e3e9a03fcb7..8102b36da3b 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/RCTEventEmitter.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/RCTEventEmitter.java @@ -1,22 +1,18 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager.events; -import javax.annotation.Nullable; - import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.bridge.WritableArray; import com.facebook.react.bridge.WritableMap; +import javax.annotation.Nullable; public interface RCTEventEmitter extends JavaScriptModule { void receiveEvent(int targetTag, String eventName, @Nullable WritableMap event); - void receiveTouches( - String eventName, - WritableArray touches, - WritableArray changedIndices); + + void receiveTouches(String eventName, WritableArray touches, WritableArray changedIndices); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/ReactEventEmitter.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/ReactEventEmitter.java index 61e3e95cd4f..5e73266613f 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/ReactEventEmitter.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/ReactEventEmitter.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager.events; import static com.facebook.react.uimanager.events.TouchesHelper.TARGET_KEY; @@ -43,9 +42,7 @@ public class ReactEventEmitter implements RCTEventEmitter { @Override public void receiveTouches( - String eventName, - WritableArray touches, - WritableArray changedIndices) { + String eventName, WritableArray touches, WritableArray changedIndices) { Assertions.assertCondition(touches.size() > 0); diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/TouchEvent.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/TouchEvent.java index 59418f77035..cd0166cfff3 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/TouchEvent.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/TouchEvent.java @@ -1,27 +1,24 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager.events; -import javax.annotation.Nullable; - -import androidx.core.util.Pools; import android.view.MotionEvent; - +import androidx.core.util.Pools; import com.facebook.infer.annotation.Assertions; import com.facebook.react.bridge.SoftAssertions; +import javax.annotation.Nullable; /** - * An event representing the start, end or movement of a touch. Corresponds to a single - * {@link android.view.MotionEvent}. + * An event representing the start, end or movement of a touch. Corresponds to a single {@link + * android.view.MotionEvent}. * - * TouchEvent coalescing can happen for move events if two move events have the same target view and - * coalescing key. See {@link TouchEventCoalescingKeyHelper} for more information about how these - * coalescing keys are determined. + *

TouchEvent coalescing can happen for move events if two move events have the same target view + * and coalescing key. See {@link TouchEventCoalescingKeyHelper} for more information about how + * these coalescing keys are determined. */ public class TouchEvent extends Event { @@ -45,13 +42,13 @@ public class TouchEvent extends Event { event = new TouchEvent(); } event.init( - viewTag, - touchEventType, - motionEventToCopy, - gestureStartTime, - viewX, - viewY, - touchEventCoalescingKeyHelper); + viewTag, + touchEventType, + motionEventToCopy, + gestureStartTime, + viewX, + viewY, + touchEventCoalescingKeyHelper); return event; } @@ -63,8 +60,7 @@ public class TouchEvent extends Event { private float mViewX; private float mViewY; - private TouchEvent() { - } + private TouchEvent() {} private void init( int viewTag, @@ -76,8 +72,8 @@ public class TouchEvent extends Event { TouchEventCoalescingKeyHelper touchEventCoalescingKeyHelper) { super.init(viewTag); - SoftAssertions.assertCondition(gestureStartTime != UNSET, - "Gesture start time must be initialized"); + SoftAssertions.assertCondition( + gestureStartTime != UNSET, "Gesture start time must be initialized"); short coalescingKey = 0; int action = (motionEventToCopy.getAction() & MotionEvent.ACTION_MASK); switch (action) { @@ -92,8 +88,7 @@ public class TouchEvent extends Event { touchEventCoalescingKeyHelper.incrementCoalescingKey(gestureStartTime); break; case MotionEvent.ACTION_MOVE: - coalescingKey = - touchEventCoalescingKeyHelper.getCoalescingKey(gestureStartTime); + coalescingKey = touchEventCoalescingKeyHelper.getCoalescingKey(gestureStartTime); break; case MotionEvent.ACTION_CANCEL: touchEventCoalescingKeyHelper.removeCoalescingKey(gestureStartTime); @@ -145,10 +140,7 @@ public class TouchEvent extends Event { @Override public void dispatch(RCTEventEmitter rctEventEmitter) { TouchesHelper.sendTouchEvent( - rctEventEmitter, - Assertions.assertNotNull(mTouchEventType), - getViewTag(), - this); + rctEventEmitter, Assertions.assertNotNull(mTouchEventType), getViewTag(), this); } public MotionEvent getMotionEvent() { diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/TouchEventCoalescingKeyHelper.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/TouchEventCoalescingKeyHelper.java index 79e8b7bf1ca..b552c1bc353 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/TouchEventCoalescingKeyHelper.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/TouchEventCoalescingKeyHelper.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager.events; import android.util.SparseIntArray; @@ -16,46 +15,41 @@ import android.util.SparseIntArray; * gesture). To illustrate to kind of coalescing we want, imagine we are coalescing the following * touch stream: * - * (U = finger up, D = finger down, M = move) - * D MMMMM D MMMMMMMMMMMMMM U MMMMM D MMMMMM U U + *

(U = finger up, D = finger down, M = move) D MMMMM D MMMMMMMMMMMMMM U MMMMM D MMMMMM U U * - * We want to make sure to coalesce this as + *

We want to make sure to coalesce this as * - * D M D M U M D U U + *

D M D M U M D U U * - * and *not* + *

and *not* * - * D D U M D U U + *

D D U M D U U * - * To accomplish this, this class provides a way to initialize a coalescing key for a gesture and + *

To accomplish this, this class provides a way to initialize a coalescing key for a gesture and * then increment it for every pointer up/down that occurs during that single gesture. * - * We identify a single gesture based on {@link android.view.MotionEvent#getDownTime()} which will - * stay constant for a given set of related touches on a single view. + *

We identify a single gesture based on {@link android.view.MotionEvent#getDownTime()} which + * will stay constant for a given set of related touches on a single view. * - * NB: even though down time is a long, we cast as an int using the least significant bits as the + *

NB: even though down time is a long, we cast as an int using the least significant bits as the * identifier. In practice, we will not be coalescing over a time range where the most significant * bits of that time range matter. This would require a gesture that lasts Integer.MAX_VALUE * 2 ms, * or ~48 days. * - * NB: we assume two gestures cannot begin at the same time. + *

NB: we assume two gestures cannot begin at the same time. * - * NB: this class should only be used from the UI thread. + *

NB: this class should only be used from the UI thread. */ public class TouchEventCoalescingKeyHelper { private final SparseIntArray mDownTimeToCoalescingKey = new SparseIntArray(); - /** - * Starts tracking a new coalescing key corresponding to the gesture with this down time. - */ + /** Starts tracking a new coalescing key corresponding to the gesture with this down time. */ public void addCoalescingKey(long downTime) { mDownTimeToCoalescingKey.put((int) downTime, 0); } - /** - * Increments the coalescing key corresponding to the gesture with this down time. - */ + /** Increments the coalescing key corresponding to the gesture with this down time. */ public void incrementCoalescingKey(long downTime) { int currentValue = mDownTimeToCoalescingKey.get((int) downTime, -1); if (currentValue == -1) { @@ -64,9 +58,7 @@ public class TouchEventCoalescingKeyHelper { mDownTimeToCoalescingKey.put((int) downTime, currentValue + 1); } - /** - * Gets the coalescing key corresponding to the gesture with this down time. - */ + /** Gets the coalescing key corresponding to the gesture with this down time. */ public short getCoalescingKey(long downTime) { int currentValue = mDownTimeToCoalescingKey.get((int) downTime, -1); if (currentValue == -1) { @@ -75,9 +67,7 @@ public class TouchEventCoalescingKeyHelper { return ((short) (0xffff & currentValue)); } - /** - * Stops tracking a new coalescing key corresponding to the gesture with this down time. - */ + /** Stops tracking a new coalescing key corresponding to the gesture with this down time. */ public void removeCoalescingKey(long downTime) { mDownTimeToCoalescingKey.delete((int) downTime); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/TouchEventType.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/TouchEventType.java index 04439c41269..d7d3fa2ad48 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/TouchEventType.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/TouchEventType.java @@ -1,15 +1,12 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager.events; -/** - * Touch event types that JS module RCTEventEmitter can understand - */ +/** Touch event types that JS module RCTEventEmitter can understand */ public enum TouchEventType { START, END, diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/TouchesHelper.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/TouchesHelper.java index 4907870d637..9b1903f742c 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/TouchesHelper.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/TouchesHelper.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager.events; import android.view.MotionEvent; @@ -13,9 +12,7 @@ import com.facebook.react.bridge.WritableArray; import com.facebook.react.bridge.WritableMap; import com.facebook.react.uimanager.PixelUtil; -/** - * Class responsible for generating catalyst touch events based on android {@link MotionEvent}. - */ +/** Class responsible for generating catalyst touch events based on android {@link MotionEvent}. */ public class TouchesHelper { public static final String TARGET_KEY = "target"; @@ -72,8 +69,8 @@ public class TouchesHelper { } /** - * Generate and send touch event to RCTEventEmitter JS module associated with the given - * {@param context}. Touch event can encode multiple concurrent touches (pointers). + * Generate and send touch event to RCTEventEmitter JS module associated with the given {@param + * context}. Touch event can encode multiple concurrent touches (pointers). * * @param rctEventEmitter Event emitter used to execute JS module call * @param type type of the touch event (see {@link TouchEventType}) @@ -102,9 +99,6 @@ public class TouchesHelper { throw new RuntimeException("Unknown touch type: " + type); } - rctEventEmitter.receiveTouches( - TouchEventType.getJSEventName(type), - pointers, - changedIndices); + rctEventEmitter.receiveTouches(TouchEventType.getJSEventName(type), pointers, changedIndices); } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/AbstractLayoutAnimation.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/AbstractLayoutAnimation.java index ca9bb385324..8f6eb5ab6b0 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/AbstractLayoutAnimation.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/AbstractLayoutAnimation.java @@ -37,11 +37,12 @@ import javax.annotation.Nullable; */ abstract @Nullable Animation createAnimationImpl(View view, int x, int y, int width, int height); - private static final Map INTERPOLATOR = MapBuilder.of( - InterpolatorType.LINEAR, new LinearInterpolator(), - InterpolatorType.EASE_IN, new AccelerateInterpolator(), - InterpolatorType.EASE_OUT, new DecelerateInterpolator(), - InterpolatorType.EASE_IN_EASE_OUT, new AccelerateDecelerateInterpolator()); + private static final Map INTERPOLATOR = + MapBuilder.of( + InterpolatorType.LINEAR, new LinearInterpolator(), + InterpolatorType.EASE_IN, new AccelerateInterpolator(), + InterpolatorType.EASE_OUT, new DecelerateInterpolator(), + InterpolatorType.EASE_IN_EASE_OUT, new AccelerateDecelerateInterpolator()); private @Nullable Interpolator mInterpolator; private int mDelayMs; @@ -57,8 +58,10 @@ import javax.annotation.Nullable; } public void initializeFromConfig(ReadableMap data, int globalDuration) { - mAnimatedProperty = data.hasKey("property") ? - AnimatedPropertyType.fromString(data.getString("property")) : null; + mAnimatedProperty = + data.hasKey("property") + ? AnimatedPropertyType.fromString(data.getString("property")) + : null; mDurationMs = data.hasKey("duration") ? data.getInt("duration") : globalDuration; mDelayMs = data.hasKey("delay") ? data.getInt("delay") : 0; if (!data.hasKey("type")) { @@ -81,12 +84,7 @@ import javax.annotation.Nullable; * @param width the new width value for the view * @param height the new height value for the view */ - public final @Nullable Animation createAnimation( - View view, - int x, - int y, - int width, - int height) { + public final @Nullable Animation createAnimation(View view, int x, int y, int width, int height) { if (!isValid()) { return null; } @@ -101,12 +99,13 @@ import javax.annotation.Nullable; } private static Interpolator getInterpolator(InterpolatorType type, ReadableMap params) { - Interpolator interpolator; - if (type.equals(InterpolatorType.SPRING)) { - interpolator = new SimpleSpringInterpolator(SimpleSpringInterpolator.getSpringDamping(params)); - } else { - interpolator = INTERPOLATOR.get(type); - } + Interpolator interpolator; + if (type.equals(InterpolatorType.SPRING)) { + interpolator = + new SimpleSpringInterpolator(SimpleSpringInterpolator.getSpringDamping(params)); + } else { + interpolator = INTERPOLATOR.get(type); + } if (interpolator == null) { throw new IllegalArgumentException("Missing interpolator for type : " + type); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/AnimatedPropertyType.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/AnimatedPropertyType.java index a8e569fbe91..54c572cf8c9 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/AnimatedPropertyType.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/AnimatedPropertyType.java @@ -6,8 +6,8 @@ package com.facebook.react.uimanager.layoutanimation; /** - * Enum representing the different view properties that can be used when animating layout for - * view creation. + * Enum representing the different view properties that can be used when animating layout for view + * creation. */ /* package */ enum AnimatedPropertyType { OPACITY, diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/BaseLayoutAnimation.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/BaseLayoutAnimation.java index 0c586fb5ba2..8d73bd63ff6 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/BaseLayoutAnimation.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/BaseLayoutAnimation.java @@ -8,12 +8,9 @@ package com.facebook.react.uimanager.layoutanimation; import android.view.View; import android.view.animation.Animation; import android.view.animation.ScaleAnimation; - import com.facebook.react.uimanager.IllegalViewOperationException; -/** - * Class responsible for default layout animation, i.e animation of view creation and deletion. - */ +/** Class responsible for default layout animation, i.e animation of view creation and deletion. */ /* package */ abstract class BaseLayoutAnimation extends AbstractLayoutAnimation { abstract boolean isReverse(); @@ -27,50 +24,54 @@ import com.facebook.react.uimanager.IllegalViewOperationException; Animation createAnimationImpl(View view, int x, int y, int width, int height) { if (mAnimatedProperty != null) { switch (mAnimatedProperty) { - case OPACITY: { - float fromValue = isReverse() ? view.getAlpha() : 0.0f; - float toValue = isReverse() ? 0.0f : view.getAlpha(); - return new OpacityAnimation(view, fromValue, toValue); - } - case SCALE_XY: { - float fromValue = isReverse() ? 1.0f : 0.0f; - float toValue = isReverse() ? 0.0f : 1.0f; - return new ScaleAnimation( - fromValue, - toValue, - fromValue, - toValue, - Animation.RELATIVE_TO_SELF, - .5f, - Animation.RELATIVE_TO_SELF, - .5f); - } - case SCALE_X: { - float fromValue = isReverse() ? 1.0f : 0.0f; - float toValue = isReverse() ? 0.0f : 1.0f; - return new ScaleAnimation( - fromValue, - toValue, - 1f, - 1f, - Animation.RELATIVE_TO_SELF, - .5f, - Animation.RELATIVE_TO_SELF, - 0f); - } - case SCALE_Y: { - float fromValue = isReverse() ? 1.0f : 0.0f; - float toValue = isReverse() ? 0.0f : 1.0f; - return new ScaleAnimation( - 1f, - 1f, - fromValue, - toValue, - Animation.RELATIVE_TO_SELF, - 0f, - Animation.RELATIVE_TO_SELF, - .5f); - } + case OPACITY: + { + float fromValue = isReverse() ? view.getAlpha() : 0.0f; + float toValue = isReverse() ? 0.0f : view.getAlpha(); + return new OpacityAnimation(view, fromValue, toValue); + } + case SCALE_XY: + { + float fromValue = isReverse() ? 1.0f : 0.0f; + float toValue = isReverse() ? 0.0f : 1.0f; + return new ScaleAnimation( + fromValue, + toValue, + fromValue, + toValue, + Animation.RELATIVE_TO_SELF, + .5f, + Animation.RELATIVE_TO_SELF, + .5f); + } + case SCALE_X: + { + float fromValue = isReverse() ? 1.0f : 0.0f; + float toValue = isReverse() ? 0.0f : 1.0f; + return new ScaleAnimation( + fromValue, + toValue, + 1f, + 1f, + Animation.RELATIVE_TO_SELF, + .5f, + Animation.RELATIVE_TO_SELF, + 0f); + } + case SCALE_Y: + { + float fromValue = isReverse() ? 1.0f : 0.0f; + float toValue = isReverse() ? 0.0f : 1.0f; + return new ScaleAnimation( + 1f, + 1f, + fromValue, + toValue, + Animation.RELATIVE_TO_SELF, + 0f, + Animation.RELATIVE_TO_SELF, + .5f); + } default: throw new IllegalViewOperationException( "Missing animation for property : " + mAnimatedProperty); diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/LayoutAnimationController.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/LayoutAnimationController.java index 232cb01f907..092db347283 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/LayoutAnimationController.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/LayoutAnimationController.java @@ -5,19 +5,17 @@ package com.facebook.react.uimanager.layoutanimation; -import javax.annotation.Nullable; -import javax.annotation.concurrent.NotThreadSafe; - import android.os.Handler; import android.os.Looper; import android.util.SparseArray; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; - import com.facebook.react.bridge.Callback; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.UiThreadUtil; +import javax.annotation.Nullable; +import javax.annotation.concurrent.NotThreadSafe; /** * Class responsible for animation layout changes, if a valid layout animation config has been @@ -38,7 +36,8 @@ public class LayoutAnimationController { @Nullable private static Handler sCompletionHandler; - public void initializeFromConfig(final @Nullable ReadableMap config, final Callback completionCallback) { + public void initializeFromConfig( + final @Nullable ReadableMap config, final Callback completionCallback) { if (config == null) { reset(); return; @@ -63,12 +62,13 @@ public class LayoutAnimationController { } if (mShouldAnimateLayout && completionCallback != null) { - mCompletionRunnable = new Runnable() { - @Override - public void run() { - completionCallback.invoke(Boolean.TRUE); - } - }; + mCompletionRunnable = + new Runnable() { + @Override + public void run() { + completionCallback.invoke(Boolean.TRUE); + } + }; } } @@ -87,7 +87,7 @@ public class LayoutAnimationController { // If there's a layout handling animation going on, it should be animated nonetheless since the // ongoing animation needs to be updated. return (mShouldAnimateLayout && viewToAnimate.getParent() != null) - || mLayoutHandlers.get(viewToAnimate.getId()) != null; + || mLayoutHandlers.get(viewToAnimate.getId()) != null; } /** @@ -117,27 +117,29 @@ public class LayoutAnimationController { // Determine which animation to use : if view is initially invisible, use create animation, // otherwise use update animation. This approach is easier than maintaining a list of tags // for recently created views. - AbstractLayoutAnimation layoutAnimation = (view.getWidth() == 0 || view.getHeight() == 0) ? - mLayoutCreateAnimation : - mLayoutUpdateAnimation; + AbstractLayoutAnimation layoutAnimation = + (view.getWidth() == 0 || view.getHeight() == 0) + ? mLayoutCreateAnimation + : mLayoutUpdateAnimation; Animation animation = layoutAnimation.createAnimation(view, x, y, width, height); if (animation instanceof LayoutHandlingAnimation) { - animation.setAnimationListener(new Animation.AnimationListener() { - @Override - public void onAnimationStart(Animation animation) { - mLayoutHandlers.put(reactTag, (LayoutHandlingAnimation) animation); - } + animation.setAnimationListener( + new Animation.AnimationListener() { + @Override + public void onAnimationStart(Animation animation) { + mLayoutHandlers.put(reactTag, (LayoutHandlingAnimation) animation); + } - @Override - public void onAnimationEnd(Animation animation) { - mLayoutHandlers.remove(reactTag); - } + @Override + public void onAnimationEnd(Animation animation) { + mLayoutHandlers.remove(reactTag); + } - @Override - public void onAnimationRepeat(Animation animation) {} - }); + @Override + public void onAnimationRepeat(Animation animation) {} + }); } else { view.layout(x, y, x + width, y + height); } @@ -154,33 +156,36 @@ public class LayoutAnimationController { } /** - * Animate a view deletion using the layout animation configuration supplied during initialization. + * Animate a view deletion using the layout animation configuration supplied during + * initialization. * - * @param view The view to animate. - * @param listener Called once the animation is finished, should be used to - * completely remove the view. + * @param view The view to animate. + * @param listener Called once the animation is finished, should be used to completely remove the + * view. */ public void deleteView(final View view, final LayoutAnimationListener listener) { UiThreadUtil.assertOnUiThread(); - Animation animation = mLayoutDeleteAnimation.createAnimation( - view, view.getLeft(), view.getTop(), view.getWidth(), view.getHeight()); + Animation animation = + mLayoutDeleteAnimation.createAnimation( + view, view.getLeft(), view.getTop(), view.getWidth(), view.getHeight()); if (animation != null) { disableUserInteractions(view); - animation.setAnimationListener(new Animation.AnimationListener() { - @Override - public void onAnimationStart(Animation anim) {} + animation.setAnimationListener( + new Animation.AnimationListener() { + @Override + public void onAnimationStart(Animation anim) {} - @Override - public void onAnimationRepeat(Animation anim) {} + @Override + public void onAnimationRepeat(Animation anim) {} - @Override - public void onAnimationEnd(Animation anim) { - listener.onAnimationEnd(); - } - }); + @Override + public void onAnimationEnd(Animation anim) { + listener.onAnimationEnd(); + } + }); long animationDuration = animation.getDuration(); if (animationDuration > mMaxAnimationDuration) { @@ -194,13 +199,11 @@ public class LayoutAnimationController { } } - /** - * Disables user interactions for a view and all it's subviews. - */ + /** Disables user interactions for a view and all it's subviews. */ private void disableUserInteractions(View view) { view.setClickable(false); if (view instanceof ViewGroup) { - ViewGroup viewGroup = (ViewGroup)view; + ViewGroup viewGroup = (ViewGroup) view; for (int i = 0; i < viewGroup.getChildCount(); i++) { disableUserInteractions(viewGroup.getChildAt(i)); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/LayoutAnimationListener.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/LayoutAnimationListener.java index 328e0dc6eeb..f830774282a 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/LayoutAnimationListener.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/LayoutAnimationListener.java @@ -5,9 +5,7 @@ package com.facebook.react.uimanager.layoutanimation; -/** - * Listener invoked when a layout animation has completed. - */ +/** Listener invoked when a layout animation has completed. */ public interface LayoutAnimationListener { void onAnimationEnd(); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/LayoutCreateAnimation.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/LayoutCreateAnimation.java index 9259142e956..c7d1205b5df 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/LayoutCreateAnimation.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/LayoutCreateAnimation.java @@ -6,8 +6,8 @@ package com.facebook.react.uimanager.layoutanimation; /** - * Class responsible for handling layout view creation animation, applied to view whenever a - * valid config was supplied for the layout animation of CREATE type. + * Class responsible for handling layout view creation animation, applied to view whenever a valid + * config was supplied for the layout animation of CREATE type. */ /* package */ class LayoutCreateAnimation extends BaseLayoutAnimation { diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/LayoutDeleteAnimation.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/LayoutDeleteAnimation.java index e4db29c7be3..6196a484baa 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/LayoutDeleteAnimation.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/LayoutDeleteAnimation.java @@ -6,8 +6,8 @@ package com.facebook.react.uimanager.layoutanimation; /** - * Class responsible for handling layout view deletion animation, applied to view whenever a - * valid config was supplied for the layout animation of DELETE type. + * Class responsible for handling layout view deletion animation, applied to view whenever a valid + * config was supplied for the layout animation of DELETE type. */ /* package */ class LayoutDeleteAnimation extends BaseLayoutAnimation { diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/LayoutHandlingAnimation.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/LayoutHandlingAnimation.java index 7021d6978f0..a50c49b01db 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/LayoutHandlingAnimation.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/LayoutHandlingAnimation.java @@ -5,19 +5,17 @@ package com.facebook.react.uimanager.layoutanimation; -/** - * Interface for an animation type that takes care of updating the view layout. - */ +/** Interface for an animation type that takes care of updating the view layout. */ /* package */ interface LayoutHandlingAnimation { - /** - * Notifies the animation of a layout update in case one occurs during the animation. This - * avoids animating the view to the old layout since it's no longer correct; instead the - * animation should update and do whatever it can so that the final layout is correct. - * - * @param x the new X position for the view - * @param y the new Y position for the view - * @param width the new width value for the view - * @param height the new height value for the view - */ - void onLayoutUpdate(int x, int y, int width, int height); + /** + * Notifies the animation of a layout update in case one occurs during the animation. This avoids + * animating the view to the old layout since it's no longer correct; instead the animation should + * update and do whatever it can so that the final layout is correct. + * + * @param x the new X position for the view + * @param y the new Y position for the view + * @param width the new width value for the view + * @param height the new height value for the view + */ + void onLayoutUpdate(int x, int y, int width, int height); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/LayoutUpdateAnimation.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/LayoutUpdateAnimation.java index 2bd025db96d..549281daa16 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/LayoutUpdateAnimation.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/LayoutUpdateAnimation.java @@ -5,11 +5,10 @@ package com.facebook.react.uimanager.layoutanimation; -import javax.annotation.Nullable; - import android.view.View; import android.view.animation.Animation; import android.view.animation.TranslateAnimation; +import javax.annotation.Nullable; /** * Class responsible for handling layout update animation, applied to view whenever a valid config @@ -27,7 +26,8 @@ import android.view.animation.TranslateAnimation; } @Override - @Nullable Animation createAnimationImpl(View view, int x, int y, int width, int height) { + @Nullable + Animation createAnimationImpl(View view, int x, int y, int width, int height) { boolean animateLocation = view.getX() != x || view.getY() != y; boolean animateSize = view.getWidth() != width || view.getHeight() != height; if (!animateLocation && !animateSize) { diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/OpacityAnimation.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/OpacityAnimation.java index 053598f977d..623184adea4 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/OpacityAnimation.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/OpacityAnimation.java @@ -10,8 +10,8 @@ import android.view.animation.Animation; import android.view.animation.Transformation; /** - * Animation responsible for updating opacity of a view. It should ideally use hardware texture - * to optimize rendering performances. + * Animation responsible for updating opacity of a view. It should ideally use hardware texture to + * optimize rendering performances. */ /* package */ class OpacityAnimation extends Animation { @@ -26,8 +26,7 @@ import android.view.animation.Transformation; @Override public void onAnimationStart(Animation animation) { - if (mView.hasOverlappingRendering() && - mView.getLayerType() == View.LAYER_TYPE_NONE) { + if (mView.hasOverlappingRendering() && mView.getLayerType() == View.LAYER_TYPE_NONE) { mLayerTypeChanged = true; mView.setLayerType(View.LAYER_TYPE_HARDWARE, null); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/PositionAndSizeAnimation.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/PositionAndSizeAnimation.java index f1d3c691fea..b7ad46c9d7f 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/PositionAndSizeAnimation.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/PositionAndSizeAnimation.java @@ -11,9 +11,9 @@ import android.view.animation.Transformation; /** * Animation responsible for updating size and position of a view. We can't use scaling as view - * content may not necessarily stretch. As a result, this approach is inefficient because of - * layout passes occurring on every frame. - * What we might want to try to do instead is use a combined ScaleAnimation and TranslateAnimation. + * content may not necessarily stretch. As a result, this approach is inefficient because of layout + * passes occurring on every frame. What we might want to try to do instead is use a combined + * ScaleAnimation and TranslateAnimation. */ /* package */ class PositionAndSizeAnimation extends Animation implements LayoutHandlingAnimation { diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/SimpleSpringInterpolator.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/SimpleSpringInterpolator.java index b83f0974d56..c6110d39754 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/SimpleSpringInterpolator.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/SimpleSpringInterpolator.java @@ -9,18 +9,16 @@ import android.view.animation.Interpolator; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.ReadableType; -/** - * Simple spring interpolator - */ -//TODO(7613736): Improve spring interpolator with friction and damping variable support -/* package */ class SimpleSpringInterpolator implements Interpolator { +/** Simple spring interpolator */ +// TODO(7613736): Improve spring interpolator with friction and damping variable support +/* package */ class SimpleSpringInterpolator implements Interpolator { private static final float FACTOR = 0.5f; public static final String PARAM_SPRING_DAMPING = "springDamping"; private final float mSpringDamping; - public static float getSpringDamping(ReadableMap params){ - if (params.getType(PARAM_SPRING_DAMPING).equals(ReadableType.Number)){ + public static float getSpringDamping(ReadableMap params) { + if (params.getType(PARAM_SPRING_DAMPING).equals(ReadableType.Number)) { return (float) params.getDouble(PARAM_SPRING_DAMPING); } else { return FACTOR; @@ -31,15 +29,18 @@ import com.facebook.react.bridge.ReadableType; mSpringDamping = FACTOR; } - public SimpleSpringInterpolator(float springDamping){ + public SimpleSpringInterpolator(float springDamping) { mSpringDamping = springDamping; } @Override public float getInterpolation(float input) { - // Using mSpringDamping in this equation is not really the exact mathematical springDamping, but a good approximation + // Using mSpringDamping in this equation is not really the exact mathematical springDamping, but + // a good approximation // We need to replace this equation with the right Factor that accounts for damping and friction return (float) - (1 + Math.pow(2, -10 * input) * Math.sin((input - mSpringDamping / 4) * Math.PI * 2 / mSpringDamping)); + (1 + + Math.pow(2, -10 * input) + * Math.sin((input - mSpringDamping / 4) * Math.PI * 2 / mSpringDamping)); } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/util/ReactFindViewUtil.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/util/ReactFindViewUtil.java index 84a98b1f7f8..f696dcac9db 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/util/ReactFindViewUtil.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/util/ReactFindViewUtil.java @@ -16,47 +16,42 @@ import java.util.Map; import java.util.Set; import javax.annotation.Nullable; -/** - * Finds views in React Native view hierarchies - */ +/** Finds views in React Native view hierarchies */ public class ReactFindViewUtil { private static final List mOnViewFoundListeners = new ArrayList<>(); private static final Map> mOnMultipleViewsFoundListener = new HashMap<>(); - /** - * Callback to be invoked when a react native view has been found - */ + /** Callback to be invoked when a react native view has been found */ public interface OnViewFoundListener { - /** - * Returns the native id of the view of interest - */ + /** Returns the native id of the view of interest */ String getNativeId(); /** * Called when the view has been found + * * @param view */ void onViewFound(View view); } - /** - * Callback to be invoked when all react native views with geiven NativeIds have been found - */ - public interface OnMultipleViewsFoundListener{ + /** Callback to be invoked when all react native views with geiven NativeIds have been found */ + public interface OnMultipleViewsFoundListener { void onViewFound(View view, String nativeId); /** * Called when all teh views have been found + * * @param map */ } /** - * Finds a view that is tagged with {@param nativeId} as its nativeID prop - * under the {@param root} view hierarchy. Returns the view if found, null otherwise. + * Finds a view that is tagged with {@param nativeId} as its nativeID prop under the {@param root} + * view hierarchy. Returns the view if found, null otherwise. + * * @param root root of the view hierarchy from which to find the view */ public static @Nullable View findView(View root, String nativeId) { @@ -82,6 +77,7 @@ public class ReactFindViewUtil { * Finds a view tagged with {@param onViewFoundListener}'s nativeID in the given {@param root} * view hierarchy. If the view does not exist yet due to React Native's async layout, a listener * will be added. When the view is found, the {@param onViewFoundListener} will be invoked. + * * @param root root of the view hierarchy from which to find the view */ public static void findView(View root, OnViewFoundListener onViewFoundListener) { @@ -100,9 +96,7 @@ public class ReactFindViewUtil { mOnViewFoundListeners.add(onViewFoundListener); } - /** - * Removes an OnViewFoundListener previously registered with addViewListener(). - */ + /** Removes an OnViewFoundListener previously registered with addViewListener(). */ public static void removeViewListener(OnViewFoundListener onViewFoundListener) { mOnViewFoundListeners.remove(onViewFoundListener); } @@ -115,9 +109,7 @@ public class ReactFindViewUtil { mOnMultipleViewsFoundListener.remove(listener); } - /** - * Invokes any listeners that are listening on this {@param view}'s native id - */ + /** Invokes any listeners that are listening on this {@param view}'s native id */ public static void notifyViewRendered(View view) { String nativeId = getNativeId(view); if (nativeId == null) { @@ -132,11 +124,12 @@ public class ReactFindViewUtil { } } - for (Map.Entry> entry : mOnMultipleViewsFoundListener.entrySet()) { - Set nativeIds = entry.getValue(); - if (nativeIds != null && nativeIds.contains(nativeId)) { - entry.getKey().onViewFound(view, nativeId); - } + for (Map.Entry> entry : + mOnMultipleViewsFoundListener.entrySet()) { + Set nativeIds = entry.getValue(); + if (nativeIds != null && nativeIds.contains(nativeId)) { + entry.getKey().onViewFound(view, nativeId); + } } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/util/JSStackTrace.java b/ReactAndroid/src/main/java/com/facebook/react/util/JSStackTrace.java index 1a58a8f1684..3ba32b91038 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/util/JSStackTrace.java +++ b/ReactAndroid/src/main/java/com/facebook/react/util/JSStackTrace.java @@ -1,49 +1,42 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ package com.facebook.react.util; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.ReadableType; +import java.util.regex.Matcher; +import java.util.regex.Pattern; public class JSStackTrace { - private static final Pattern FILE_ID_PATTERN = Pattern.compile("\\b((?:seg-\\d+(?:_\\d+)?|\\d+)\\.js)"); + private static final Pattern FILE_ID_PATTERN = + Pattern.compile("\\b((?:seg-\\d+(?:_\\d+)?|\\d+)\\.js)"); public static String format(String message, ReadableArray stack) { StringBuilder stringBuilder = new StringBuilder(message).append(", stack:\n"); for (int i = 0; i < stack.size(); i++) { ReadableMap frame = stack.getMap(i); - stringBuilder - .append(frame.getString("methodName")) - .append("@") - .append(parseFileId(frame)); - - if (frame.hasKey("lineNumber") && - !frame.isNull("lineNumber") && - frame.getType("lineNumber") == ReadableType.Number) { - stringBuilder - .append(frame.getInt("lineNumber")); + stringBuilder.append(frame.getString("methodName")).append("@").append(parseFileId(frame)); + + if (frame.hasKey("lineNumber") + && !frame.isNull("lineNumber") + && frame.getType("lineNumber") == ReadableType.Number) { + stringBuilder.append(frame.getInt("lineNumber")); } else { - stringBuilder - .append(-1); + stringBuilder.append(-1); } - - if (frame.hasKey("column") && - !frame.isNull("column") && - frame.getType("column") == ReadableType.Number) { - stringBuilder - .append(":") - .append(frame.getInt("column")); + + if (frame.hasKey("column") + && !frame.isNull("column") + && frame.getType("column") == ReadableType.Number) { + stringBuilder.append(":").append(frame.getInt("column")); } - + stringBuilder.append("\n"); } return stringBuilder.toString(); @@ -57,9 +50,9 @@ public class JSStackTrace { // stack traces with a single source map file. // NOTE: The ".js" suffix is kept to avoid ambiguities between "module-id:line" and "line:column". private static String parseFileId(ReadableMap frame) { - if (frame.hasKey("file") && - !frame.isNull("file") && - frame.getType("file") == ReadableType.String) { + if (frame.hasKey("file") + && !frame.isNull("file") + && frame.getType("file") == ReadableType.String) { final Matcher matcher = FILE_ID_PATTERN.matcher(frame.getString("file")); if (matcher.find()) { return matcher.group(1) + ":"; diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/art/ARTGroupShadowNode.java b/ReactAndroid/src/main/java/com/facebook/react/views/art/ARTGroupShadowNode.java index 9c97a61277b..29b98be36c8 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/art/ARTGroupShadowNode.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/art/ARTGroupShadowNode.java @@ -1,32 +1,26 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.art; -import com.facebook.react.uimanager.ReactShadowNodeImpl; -import javax.annotation.Nullable; - import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.RectF; import android.graphics.Region; - import com.facebook.react.bridge.JSApplicationIllegalArgumentException; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.uimanager.annotations.ReactProp; +import javax.annotation.Nullable; -/** - * Shadow node for virtual ARTGroup view - */ +/** Shadow node for virtual ARTGroup view */ public class ARTGroupShadowNode extends ARTVirtualNode { protected @Nullable RectF mClipping; - public ARTGroupShadowNode() { } + public ARTGroupShadowNode() {} @ReactProp(name = "clipping") public void setClipping(@Nullable ReadableArray clippingDims) { @@ -49,11 +43,11 @@ public class ARTGroupShadowNode extends ARTVirtualNode { if (mClipping != null) { canvas.clipRect( - mClipping.left * mScale, - mClipping.top * mScale, - mClipping.right * mScale, - mClipping.bottom * mScale, - Region.Op.REPLACE); + mClipping.left * mScale, + mClipping.top * mScale, + mClipping.right * mScale, + mClipping.bottom * mScale, + Region.Op.REPLACE); } for (int i = 0; i < getChildCount(); i++) { @@ -67,8 +61,7 @@ public class ARTGroupShadowNode extends ARTVirtualNode { } /** - * Creates a {@link RectF} from an array of dimensions - * (e.g. [x, y, width, height]) + * Creates a {@link RectF} from an array of dimensions (e.g. [x, y, width, height]) * * @param data the array of dimensions * @return the {@link RectF} that can used to clip the canvas @@ -78,8 +71,7 @@ public class ARTGroupShadowNode extends ARTVirtualNode { throw new JSApplicationIllegalArgumentException( "Clipping should be array of length 4 (e.g. [x, y, width, height])"); } - RectF clippingRect = new RectF( - data[0], data[1], data[0] + data[2], data[1] + data[3]); + RectF clippingRect = new RectF(data[0], data[1], data[0] + data[2], data[1] + data[3]); return clippingRect; } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/art/ARTGroupViewManager.java b/ReactAndroid/src/main/java/com/facebook/react/views/art/ARTGroupViewManager.java index e80835607b5..3bd08c23182 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/art/ARTGroupViewManager.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/art/ARTGroupViewManager.java @@ -7,9 +7,7 @@ package com.facebook.react.views.art; import com.facebook.react.module.annotations.ReactModule; -/** - * ViewManager for shadowed ART group views. - */ +/** ViewManager for shadowed ART group views. */ @ReactModule(name = ARTRenderableViewManager.CLASS_GROUP) public class ARTGroupViewManager extends ARTRenderableViewManager { diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/art/ARTRenderableViewManager.java b/ReactAndroid/src/main/java/com/facebook/react/views/art/ARTRenderableViewManager.java index 60ac57ed039..8d9511e2ee4 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/art/ARTRenderableViewManager.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/art/ARTRenderableViewManager.java @@ -1,14 +1,12 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.art; import android.view.View; - import com.facebook.react.uimanager.ReactShadowNode; import com.facebook.react.uimanager.ThemedReactContext; import com.facebook.react.uimanager.ViewManager; diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/art/ARTShapeShadowNode.java b/ReactAndroid/src/main/java/com/facebook/react/views/art/ARTShapeShadowNode.java index 5cd54338bd1..2f3111c88d9 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/art/ARTShapeShadowNode.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/art/ARTShapeShadowNode.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.art; import android.graphics.Canvas; @@ -22,11 +21,7 @@ import com.facebook.react.common.ReactConstants; import com.facebook.react.uimanager.annotations.ReactProp; import javax.annotation.Nullable; -import static com.facebook.react.common.ArrayUtils.copyArray; - -/** - * Shadow node for virtual ARTShape view - */ +/** Shadow node for virtual ARTShape view */ public class ARTShapeShadowNode extends ARTVirtualNode { private static final int CAP_BUTT = 0; @@ -58,7 +53,7 @@ public class ARTShapeShadowNode extends ARTVirtualNode { private int mStrokeCap = CAP_ROUND; private int mStrokeJoin = JOIN_ROUND; - public ARTShapeShadowNode() { } + public ARTShapeShadowNode() {} @ReactProp(name = "d") public void setShapePath(@Nullable ReadableArray shapePath) { @@ -109,8 +104,7 @@ public class ARTShapeShadowNode extends ARTVirtualNode { if (opacity > MIN_OPACITY_FOR_DRAW) { saveAndSetupCanvas(canvas); if (mPath == null) { - throw new JSApplicationIllegalArgumentException( - "Shapes should have a valid path (d) prop"); + throw new JSApplicationIllegalArgumentException("Shapes should have a valid path (d) prop"); } if (setupFillPaint(paint, opacity)) { canvas.drawPath(mPath, paint); @@ -124,8 +118,8 @@ public class ARTShapeShadowNode extends ARTVirtualNode { } /** - * Sets up {@link #mPaint} according to the props set on a shadow view. Returns {@code true} - * if the stroke should be drawn, {@code false} if not. + * Sets up {@link #mPaint} according to the props set on a shadow view. Returns {@code true} if + * the stroke should be drawn, {@code false} if not. */ protected boolean setupStrokePaint(Paint paint, float opacity) { if (mStrokeWidth == 0 || mStrokeColor == null || mStrokeColor.length == 0) { @@ -175,8 +169,8 @@ public class ARTShapeShadowNode extends ARTVirtualNode { } /** - * Sets up {@link #mPaint} according to the props set on a shadow view. Returns {@code true} - * if the fill should be drawn, {@code false} if not. + * Sets up {@link #mPaint} according to the props set on a shadow view. Returns {@code true} if + * the fill should be drawn, {@code false} if not. */ protected boolean setupFillPaint(Paint paint, float opacity) { if (mBrushData != null && mBrushData.length > 0) { @@ -193,11 +187,13 @@ public class ARTShapeShadowNode extends ARTVirtualNode { (int) (mBrushData[3] * 255)); break; case COLOR_TYPE_LINEAR_GRADIENT: - // For mBrushData format refer to LinearGradient and insertColorStopsIntoArray functions in ReactNativeART.js + // For mBrushData format refer to LinearGradient and insertColorStopsIntoArray functions + // in ReactNativeART.js if (mBrushData.length < 5) { - FLog.w(ReactConstants.TAG, - "[ARTShapeShadowNode setupFillPaint] expects 5 elements, received " - + mBrushData.length); + FLog.w( + ReactConstants.TAG, + "[ARTShapeShadowNode setupFillPaint] expects 5 elements, received " + + mBrushData.length); return false; } float gradientStartX = mBrushData[1] * mScale; @@ -210,23 +206,24 @@ public class ARTShapeShadowNode extends ARTVirtualNode { if (stops > 0) { colors = new int[stops]; positions = new float[stops]; - for (int i=0; i= 360) { - path.addCircle(x, y, r, counterClockwise ? Path.Direction.CCW : Path.Direction.CW); - } else { - sweep = modulus(sweep, 360); - if (counterClockwise && sweep < 360) { - // Counter-clockwise sweeps are negative - sweep = -1 * (360 - sweep); + boolean counterClockwise = !(data[i++] == 1f); + float sweep = end - start; + if (Math.abs(sweep) >= 360) { + path.addCircle(x, y, r, counterClockwise ? Path.Direction.CCW : Path.Direction.CW); + } else { + sweep = modulus(sweep, 360); + if (counterClockwise && sweep < 360) { + // Counter-clockwise sweeps are negative + sweep = -1 * (360 - sweep); + } + + RectF oval = new RectF(x - r, y - r, x + r, y + r); + path.arcTo(oval, start, sweep); } - - RectF oval = new RectF(x - r, y - r, x + r, y + r); - path.arcTo(oval, start, sweep); + break; } - break; - } default: throw new JSApplicationIllegalArgumentException( "Unrecognized drawing instruction " + type); diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/art/ARTShapeViewManager.java b/ReactAndroid/src/main/java/com/facebook/react/views/art/ARTShapeViewManager.java index d980eaac68d..65da0f9894a 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/art/ARTShapeViewManager.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/art/ARTShapeViewManager.java @@ -7,9 +7,7 @@ package com.facebook.react.views.art; import com.facebook.react.module.annotations.ReactModule; -/** - * ViewManager for shadowed ART shape views. - */ +/** ViewManager for shadowed ART shape views. */ @ReactModule(name = ARTRenderableViewManager.CLASS_SHAPE) public class ARTShapeViewManager extends ARTRenderableViewManager { diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/art/ARTSurfaceView.java b/ReactAndroid/src/main/java/com/facebook/react/views/art/ARTSurfaceView.java index 190cbe74606..a3531e08217 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/art/ARTSurfaceView.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/art/ARTSurfaceView.java @@ -1,18 +1,15 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.art; import android.content.Context; import android.view.TextureView; -/** - * Custom {@link View} implementation that draws an ARTSurface React view and its children. - */ +/** Custom {@link View} implementation that draws an ARTSurface React view and its children. */ public class ARTSurfaceView extends TextureView { public ARTSurfaceView(Context context) { super(context); diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/art/ARTSurfaceViewManager.java b/ReactAndroid/src/main/java/com/facebook/react/views/art/ARTSurfaceViewManager.java index e7cc4c652f6..aa8ee1d46aa 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/art/ARTSurfaceViewManager.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/art/ARTSurfaceViewManager.java @@ -1,40 +1,40 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.art; -import com.facebook.yoga.YogaMeasureMode; -import com.facebook.yoga.YogaMeasureFunction; -import com.facebook.yoga.YogaNode; import com.facebook.react.module.annotations.ReactModule; import com.facebook.react.uimanager.BaseViewManager; import com.facebook.react.uimanager.ThemedReactContext; +import com.facebook.yoga.YogaMeasureFunction; +import com.facebook.yoga.YogaMeasureMode; +import com.facebook.yoga.YogaNode; /** * ViewManager for ARTSurfaceView React views. Renders as a {@link ARTSurfaceView} and handles * invalidating the native view on shadow view updates happening in the underlying tree. */ @ReactModule(name = ARTSurfaceViewManager.REACT_CLASS) -public class ARTSurfaceViewManager extends - BaseViewManager { +public class ARTSurfaceViewManager + extends BaseViewManager { public static final String REACT_CLASS = "ARTSurfaceView"; - private static final YogaMeasureFunction MEASURE_FUNCTION = new YogaMeasureFunction() { - @Override - public long measure( - YogaNode node, - float width, - YogaMeasureMode widthMode, - float height, - YogaMeasureMode heightMode) { - throw new IllegalStateException("SurfaceView should have explicit width and height set"); - } - }; + private static final YogaMeasureFunction MEASURE_FUNCTION = + new YogaMeasureFunction() { + @Override + public long measure( + YogaNode node, + float width, + YogaMeasureMode widthMode, + float height, + YogaMeasureMode heightMode) { + throw new IllegalStateException("SurfaceView should have explicit width and height set"); + } + }; @Override public String getName() { diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/art/ARTSurfaceViewShadowNode.java b/ReactAndroid/src/main/java/com/facebook/react/views/art/ARTSurfaceViewShadowNode.java index b154c0c4d05..576dd05facd 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/art/ARTSurfaceViewShadowNode.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/art/ARTSurfaceViewShadowNode.java @@ -1,38 +1,33 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.art; -import javax.annotation.Nullable; - import android.graphics.Canvas; -import android.graphics.Paint; import android.graphics.Color; -import android.view.Surface; +import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.SurfaceTexture; -import android.view.TextureView; import android.os.Build; - +import android.view.Surface; +import android.view.TextureView; import com.facebook.common.logging.FLog; +import com.facebook.react.bridge.LifecycleEventListener; import com.facebook.react.common.ReactConstants; import com.facebook.react.uimanager.LayoutShadowNode; -import com.facebook.react.uimanager.UIViewOperationQueue; import com.facebook.react.uimanager.ReactShadowNode; -import com.facebook.react.uimanager.ViewProps; import com.facebook.react.uimanager.ThemedReactContext; +import com.facebook.react.uimanager.UIViewOperationQueue; +import com.facebook.react.uimanager.ViewProps; import com.facebook.react.uimanager.annotations.ReactProp; -import com.facebook.react.bridge.LifecycleEventListener; +import javax.annotation.Nullable; -/** - * Shadow node for ART virtual tree root - ARTSurfaceView - */ +/** Shadow node for ART virtual tree root - ARTSurfaceView */ public class ARTSurfaceViewShadowNode extends LayoutShadowNode - implements TextureView.SurfaceTextureListener, LifecycleEventListener { + implements TextureView.SurfaceTextureListener, LifecycleEventListener { private @Nullable Surface mSurface; diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/art/ARTTextShadowNode.java b/ReactAndroid/src/main/java/com/facebook/react/views/art/ARTTextShadowNode.java index c5e60563a73..139ab5f6c69 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/art/ARTTextShadowNode.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/art/ARTTextShadowNode.java @@ -1,26 +1,21 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.art; -import javax.annotation.Nullable; - import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Typeface; import android.text.TextUtils; - import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.uimanager.annotations.ReactProp; +import javax.annotation.Nullable; -/** - * Shadow node for virtual ARTText view - */ +/** Shadow node for virtual ARTText view */ public class ARTTextShadowNode extends ARTShapeShadowNode { private static final String PROP_LINES = "lines"; @@ -40,7 +35,7 @@ public class ARTTextShadowNode extends ARTShapeShadowNode { private @Nullable ReadableMap mFrame; private int mTextAlignment = TEXT_ALIGNMENT_LEFT; - public ARTTextShadowNode() { } + public ARTTextShadowNode() {} @ReactProp(name = "frame") public void setFrame(@Nullable ReadableMap frame) { diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/art/ARTTextViewManager.java b/ReactAndroid/src/main/java/com/facebook/react/views/art/ARTTextViewManager.java index 5b82b13d879..460a7a1d6c6 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/art/ARTTextViewManager.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/art/ARTTextViewManager.java @@ -7,9 +7,7 @@ package com.facebook.react.views.art; import com.facebook.react.module.annotations.ReactModule; -/** - * ViewManager for shadowed ART text views. - */ +/** ViewManager for shadowed ART text views. */ @ReactModule(name = ARTRenderableViewManager.CLASS_TEXT) public class ARTTextViewManager extends ARTRenderableViewManager { diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/art/ARTVirtualNode.java b/ReactAndroid/src/main/java/com/facebook/react/views/art/ARTVirtualNode.java index cb1a304fe9f..403cf21c5a8 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/art/ARTVirtualNode.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/art/ARTVirtualNode.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.art; import android.graphics.Canvas; @@ -47,7 +46,7 @@ public abstract class ARTVirtualNode extends ReactShadowNodeImpl { /** * Sets up the transform matrix on the canvas before an element is drawn. * - * NB: for perf reasons this does not apply opacity, as that would mean creating a new canvas + *

NB: for perf reasons this does not apply opacity, as that would mean creating a new canvas * layer (which allocates an offscreen bitmap) and having it composited afterwards. Instead, the * drawing code should apply opacity recursively. * @@ -61,8 +60,8 @@ public abstract class ARTVirtualNode extends ReactShadowNodeImpl { } /** - * Restore the canvas after an element was drawn. This is always called in mirror with - * {@link #saveAndSetupCanvas}. + * Restore the canvas after an element was drawn. This is always called in mirror with {@link + * #saveAndSetupCanvas}. * * @param canvas the canvas to restore */ diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/art/PropHelper.java b/ReactAndroid/src/main/java/com/facebook/react/views/art/PropHelper.java index 8c4b03f58bc..f883211f005 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/art/PropHelper.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/art/PropHelper.java @@ -1,27 +1,22 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.art; +import com.facebook.react.bridge.ReadableArray; import javax.annotation.Nullable; -import com.facebook.react.bridge.ReadableArray; -import com.facebook.react.uimanager.ReactStylesDiffMap; - -/** - * Contains static helper methods for accessing props. - */ +/** Contains static helper methods for accessing props. */ /* package */ class PropHelper { /** * Converts {@link ReadableArray} to an array of {@code float}. Returns newly created array. * * @return a {@code float[]} if converted successfully, or {@code null} if {@param value} was - * {@code null}. + * {@code null}. */ /*package*/ static @Nullable float[] toFloatArray(@Nullable ReadableArray value) { if (value != null) { diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/checkbox/ReactCheckBox.java b/ReactAndroid/src/main/java/com/facebook/react/views/checkbox/ReactCheckBox.java index 594cd74ccff..54bfdbd3215 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/checkbox/ReactCheckBox.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/checkbox/ReactCheckBox.java @@ -1,8 +1,8 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ package com.facebook.react.views.checkbox; diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/checkbox/ReactCheckBoxEvent.java b/ReactAndroid/src/main/java/com/facebook/react/views/checkbox/ReactCheckBoxEvent.java index fa2cffc8afa..34b4bc560f6 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/checkbox/ReactCheckBoxEvent.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/checkbox/ReactCheckBoxEvent.java @@ -1,8 +1,8 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ package com.facebook.react.views.checkbox; diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/checkbox/ReactCheckBoxManager.java b/ReactAndroid/src/main/java/com/facebook/react/views/checkbox/ReactCheckBoxManager.java index 0839fb723fe..bc9a8d3455c 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/checkbox/ReactCheckBoxManager.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/checkbox/ReactCheckBoxManager.java @@ -1,18 +1,17 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ package com.facebook.react.views.checkbox; import android.content.Context; import android.content.res.ColorStateList; -import androidx.core.widget.CompoundButtonCompat; -import androidx.appcompat.widget.TintContextWrapper; import android.util.TypedValue; import android.widget.CompoundButton; - +import androidx.appcompat.widget.TintContextWrapper; +import androidx.core.widget.CompoundButtonCompat; import com.facebook.react.bridge.ReactContext; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.uimanager.SimpleViewManager; @@ -20,7 +19,6 @@ import com.facebook.react.uimanager.ThemedReactContext; import com.facebook.react.uimanager.UIManagerModule; import com.facebook.react.uimanager.ViewProps; import com.facebook.react.uimanager.annotations.ReactProp; - import javax.annotation.Nullable; /** View manager for {@link ReactCheckBox} components. */ @@ -34,7 +32,8 @@ public class ReactCheckBoxManager extends SimpleViewManager { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { ReactContext reactContext = getReactContext(buttonView); reactContext - .getNativeModule(UIManagerModule.class).getEventDispatcher() + .getNativeModule(UIManagerModule.class) + .getEventDispatcher() .dispatchEvent(new ReactCheckBoxEvent(buttonView.getId(), isChecked)); } @@ -88,8 +87,8 @@ public class ReactCheckBoxManager extends SimpleViewManager { /** * The appcompat-v7 BUCK dep is listed as a provided_dep, which complains that - * com.facebook.react.R doesn't exist. Since the attributes are provided from a parent, we can access - * those attributes dynamically. + * com.facebook.react.R doesn't exist. Since the attributes are provided from a parent, we can + * access those attributes dynamically. */ private static int getIdentifier(Context context, String name) { return context.getResources().getIdentifier(name, "attr", context.getPackageName()); @@ -98,25 +97,26 @@ public class ReactCheckBoxManager extends SimpleViewManager { @ReactProp(name = "tintColors") public void setTintColors(ReactCheckBox view, @Nullable ReadableMap colorsMap) { String defaultColorIdOfCheckedState = "colorAccent"; - int trueColor = colorsMap == null || !colorsMap.hasKey("true") ? - getThemeColor(view.getContext(), defaultColorIdOfCheckedState) : colorsMap.getInt("true"); + int trueColor = + colorsMap == null || !colorsMap.hasKey("true") + ? getThemeColor(view.getContext(), defaultColorIdOfCheckedState) + : colorsMap.getInt("true"); String defaultColorIdOfUncheckedState = "colorPrimaryDark"; - int falseColor = colorsMap == null || !colorsMap.hasKey("false") ? - getThemeColor(view.getContext(), defaultColorIdOfUncheckedState) : colorsMap.getInt("false"); + int falseColor = + colorsMap == null || !colorsMap.hasKey("false") + ? getThemeColor(view.getContext(), defaultColorIdOfUncheckedState) + : colorsMap.getInt("false"); - ColorStateList csl = new ColorStateList( - new int[][]{ - new int[]{android.R.attr.state_checked}, - new int[]{-android.R.attr.state_checked} + ColorStateList csl = + new ColorStateList( + new int[][] { + new int[] {android.R.attr.state_checked}, new int[] {-android.R.attr.state_checked} }, - new int[]{ - trueColor, - falseColor, - } - ); + new int[] { + trueColor, falseColor, + }); CompoundButtonCompat.setButtonTintList(view, csl); } - } diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/common/ContextUtils.java b/ReactAndroid/src/main/java/com/facebook/react/views/common/ContextUtils.java index e2bb7393f4e..682b92395fb 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/common/ContextUtils.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/common/ContextUtils.java @@ -1,8 +1,8 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ package com.facebook.react.views.common; @@ -25,7 +25,7 @@ public class ContextUtils { * @return the first context which is an instance of the specified class, or null if none exists */ public static @Nullable T findContextOfType( - @Nullable Context context, Class clazz) { + @Nullable Context context, Class clazz) { while (!(clazz.isInstance(context))) { if (context instanceof ContextWrapper) { Context baseContext = ((ContextWrapper) context).getBaseContext(); diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/drawer/ReactDrawerLayout.java b/ReactAndroid/src/main/java/com/facebook/react/views/drawer/ReactDrawerLayout.java index 52391c82d63..da333131e3c 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/drawer/ReactDrawerLayout.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/drawer/ReactDrawerLayout.java @@ -1,21 +1,18 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.drawer; -import androidx.drawerlayout.widget.DrawerLayout; -import android.view.Gravity; import android.util.Log; +import android.view.Gravity; import android.view.MotionEvent; import android.view.View; - +import androidx.drawerlayout.widget.DrawerLayout; import com.facebook.react.bridge.ReactContext; import com.facebook.react.common.ReactConstants; -import com.facebook.react.uimanager.PixelUtil; import com.facebook.react.uimanager.events.NativeGestureUtil; /** diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/drawer/ReactDrawerLayoutManager.java b/ReactAndroid/src/main/java/com/facebook/react/views/drawer/ReactDrawerLayoutManager.java index e3ebc37b918..003bfca0842 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/drawer/ReactDrawerLayoutManager.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/drawer/ReactDrawerLayoutManager.java @@ -1,16 +1,15 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.drawer; import android.os.Build; -import androidx.drawerlayout.widget.DrawerLayout; import android.view.Gravity; import android.view.View; +import androidx.drawerlayout.widget.DrawerLayout; import com.facebook.common.logging.FLog; import com.facebook.react.bridge.Dynamic; import com.facebook.react.bridge.JSApplicationIllegalArgumentException; @@ -33,9 +32,7 @@ import java.lang.reflect.Method; import java.util.Map; import javax.annotation.Nullable; -/** - * View Manager for {@link ReactDrawerLayout} components. - */ +/** View Manager for {@link ReactDrawerLayout} components. */ @ReactModule(name = ReactDrawerLayoutManager.REACT_CLASS) public class ReactDrawerLayoutManager extends ViewGroupManager { @@ -53,8 +50,7 @@ public class ReactDrawerLayoutManager extends ViewGroupManager= 2) { - throw new - JSApplicationIllegalArgumentException("The Drawer cannot have more than two children"); + throw new JSApplicationIllegalArgumentException( + "The Drawer cannot have more than two children"); } if (index != 0 && index != 1) { throw new JSApplicationIllegalArgumentException( @@ -216,26 +209,22 @@ public class ReactDrawerLayoutManager extends ViewGroupManagerThis source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.drawer.events; import com.facebook.react.bridge.Arguments; @@ -34,5 +33,4 @@ public class DrawerClosedEvent extends Event { public void dispatch(RCTEventEmitter rctEventEmitter) { rctEventEmitter.receiveEvent(getViewTag(), getEventName(), Arguments.createMap()); } - } diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/drawer/events/DrawerOpenedEvent.java b/ReactAndroid/src/main/java/com/facebook/react/views/drawer/events/DrawerOpenedEvent.java index abbcc115602..56dfbe23f29 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/drawer/events/DrawerOpenedEvent.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/drawer/events/DrawerOpenedEvent.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.drawer.events; import com.facebook.react.bridge.Arguments; @@ -34,5 +33,4 @@ public class DrawerOpenedEvent extends Event { public void dispatch(RCTEventEmitter rctEventEmitter) { rctEventEmitter.receiveEvent(getViewTag(), getEventName(), Arguments.createMap()); } - } diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/drawer/events/DrawerSlideEvent.java b/ReactAndroid/src/main/java/com/facebook/react/views/drawer/events/DrawerSlideEvent.java index 84b4aee192b..0babaaac68c 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/drawer/events/DrawerSlideEvent.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/drawer/events/DrawerSlideEvent.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.drawer.events; import com.facebook.react.bridge.Arguments; @@ -12,9 +11,7 @@ import com.facebook.react.bridge.WritableMap; import com.facebook.react.uimanager.events.Event; import com.facebook.react.uimanager.events.RCTEventEmitter; -/** - * Event emitted by a DrawerLayout as it is being moved open/closed. - */ +/** Event emitted by a DrawerLayout as it is being moved open/closed. */ public class DrawerSlideEvent extends Event { public static final String EVENT_NAME = "topDrawerSlide"; diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/drawer/events/DrawerStateChangedEvent.java b/ReactAndroid/src/main/java/com/facebook/react/views/drawer/events/DrawerStateChangedEvent.java index 96472f1f3fc..e6bc63fb1ae 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/drawer/events/DrawerStateChangedEvent.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/drawer/events/DrawerStateChangedEvent.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.drawer.events; import com.facebook.react.bridge.Arguments; diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/image/ImageLoadEvent.java b/ReactAndroid/src/main/java/com/facebook/react/views/image/ImageLoadEvent.java index 00b85a2aed5..fc19da7291b 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/image/ImageLoadEvent.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/image/ImageLoadEvent.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.image; import androidx.annotation.IntDef; @@ -48,21 +47,17 @@ public class ImageLoadEvent extends Event { } public ImageLoadEvent( - int viewId, - @ImageEventType int eventType, - @Nullable String imageUri, - int width, - int height) { + int viewId, @ImageEventType int eventType, @Nullable String imageUri, int width, int height) { this(viewId, eventType, imageUri, width, height, null); } public ImageLoadEvent( - int viewId, - @ImageEventType int eventType, - @Nullable String imageUri, - int width, - int height, - @Nullable String message) { + int viewId, + @ImageEventType int eventType, + @Nullable String imageUri, + int width, + int height, + @Nullable String message) { super(viewId); mEventType = eventType; mImageUri = imageUri; diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/image/ImageResizeMethod.java b/ReactAndroid/src/main/java/com/facebook/react/views/image/ImageResizeMethod.java index 52edd666570..bff4b6718ff 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/image/ImageResizeMethod.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/image/ImageResizeMethod.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.image; public enum ImageResizeMethod { diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/image/ImageResizeMode.java b/ReactAndroid/src/main/java/com/facebook/react/views/image/ImageResizeMode.java index a04b2adf678..77dc796274c 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/image/ImageResizeMode.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/image/ImageResizeMode.java @@ -1,26 +1,21 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.image; +import android.graphics.Shader; +import com.facebook.drawee.drawable.ScalingUtils; +import com.facebook.react.bridge.JSApplicationIllegalArgumentException; import javax.annotation.Nullable; -import android.graphics.Shader; -import com.facebook.react.bridge.JSApplicationIllegalArgumentException; -import com.facebook.drawee.drawable.ScalingUtils; - -/** - * Converts JS resize modes into Android-specific scale type. - */ +/** Converts JS resize modes into Android-specific scale type. */ public class ImageResizeMode { /** - * Converts JS resize modes into {@code ScalingUtils.ScaleType}. - * See {@code ImageResizeMode.js}. + * Converts JS resize modes into {@code ScalingUtils.ScaleType}. See {@code ImageResizeMode.js}. */ public static ScalingUtils.ScaleType toScaleType(@Nullable String resizeModeValue) { if ("contain".equals(resizeModeValue)) { @@ -47,10 +42,7 @@ public class ImageResizeMode { "Invalid resize mode: '" + resizeModeValue + "'"); } - /** - * Converts JS resize modes into {@code Shader.TileMode}. - * See {@code ImageResizeMode.js}. - */ + /** Converts JS resize modes into {@code Shader.TileMode}. See {@code ImageResizeMode.js}. */ public static Shader.TileMode toTileMode(@Nullable String resizeModeValue) { if ("contain".equals(resizeModeValue) || "cover".equals(resizeModeValue) @@ -70,10 +62,7 @@ public class ImageResizeMode { "Invalid resize mode: '" + resizeModeValue + "'"); } - /** - * This is the default as per web and iOS. - * We want to be consistent across platforms. - */ + /** This is the default as per web and iOS. We want to be consistent across platforms. */ public static ScalingUtils.ScaleType defaultValue() { return ScalingUtils.ScaleType.CENTER_CROP; } diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/image/MultiPostprocessor.java b/ReactAndroid/src/main/java/com/facebook/react/views/image/MultiPostprocessor.java index e1df87fcb7a..0630e80f581 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/image/MultiPostprocessor.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/image/MultiPostprocessor.java @@ -1,20 +1,17 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.image; import android.graphics.Bitmap; - import com.facebook.cache.common.CacheKey; import com.facebook.cache.common.MultiCacheKey; import com.facebook.common.references.CloseableReference; import com.facebook.imagepipeline.bitmaps.PlatformBitmapFactory; import com.facebook.imagepipeline.request.Postprocessor; - import java.util.LinkedList; import java.util.List; @@ -33,13 +30,13 @@ public class MultiPostprocessor implements Postprocessor { } private MultiPostprocessor(List postprocessors) { - mPostprocessors = new LinkedList<>(postprocessors); + mPostprocessors = new LinkedList<>(postprocessors); } @Override - public String getName () { + public String getName() { StringBuilder name = new StringBuilder(); - for (Postprocessor p: mPostprocessors) { + for (Postprocessor p : mPostprocessors) { if (name.length() > 0) { name.append(","); } @@ -51,16 +48,17 @@ public class MultiPostprocessor implements Postprocessor { } @Override - public CacheKey getPostprocessorCacheKey () { + public CacheKey getPostprocessorCacheKey() { LinkedList keys = new LinkedList<>(); - for (Postprocessor p: mPostprocessors) { + for (Postprocessor p : mPostprocessors) { keys.push(p.getPostprocessorCacheKey()); } return new MultiCacheKey(keys); } @Override - public CloseableReference process(Bitmap sourceBitmap, PlatformBitmapFactory bitmapFactory) { + public CloseableReference process( + Bitmap sourceBitmap, PlatformBitmapFactory bitmapFactory) { CloseableReference prevBitmap = null, nextBitmap = null; try { diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/image/ReactImageManager.java b/ReactAndroid/src/main/java/com/facebook/react/views/image/ReactImageManager.java index 57b4853f369..f6dd953518a 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/image/ReactImageManager.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/image/ReactImageManager.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.image; import android.graphics.Color; @@ -123,13 +122,15 @@ public class ReactImageManager extends SimpleViewManager { view.setBorderWidth(borderWidth); } - @ReactPropGroup(names = { - ViewProps.BORDER_RADIUS, - ViewProps.BORDER_TOP_LEFT_RADIUS, - ViewProps.BORDER_TOP_RIGHT_RADIUS, - ViewProps.BORDER_BOTTOM_RIGHT_RADIUS, - ViewProps.BORDER_BOTTOM_LEFT_RADIUS - }, defaultFloat = YogaConstants.UNDEFINED) + @ReactPropGroup( + names = { + ViewProps.BORDER_RADIUS, + ViewProps.BORDER_TOP_LEFT_RADIUS, + ViewProps.BORDER_TOP_RIGHT_RADIUS, + ViewProps.BORDER_BOTTOM_RIGHT_RADIUS, + ViewProps.BORDER_BOTTOM_LEFT_RADIUS + }, + defaultFloat = YogaConstants.UNDEFINED) public void setBorderRadius(ReactImageView view, int index, float borderRadius) { if (!YogaConstants.isUndefined(borderRadius)) { borderRadius = PixelUtil.toPixelFromDIP(borderRadius); @@ -157,7 +158,8 @@ public class ReactImageManager extends SimpleViewManager { } else if ("scale".equals(resizeMethod)) { view.setResizeMethod(ImageResizeMethod.SCALE); } else { - throw new JSApplicationIllegalArgumentException("Invalid resize method: '" + resizeMethod+ "'"); + throw new JSApplicationIllegalArgumentException( + "Invalid resize method: '" + resizeMethod + "'"); } } @@ -193,14 +195,14 @@ public class ReactImageManager extends SimpleViewManager { @Override public @Nullable Map getExportedCustomDirectEventTypeConstants() { return MapBuilder.of( - ImageLoadEvent.eventNameForType(ImageLoadEvent.ON_LOAD_START), - MapBuilder.of("registrationName", "onLoadStart"), - ImageLoadEvent.eventNameForType(ImageLoadEvent.ON_LOAD), - MapBuilder.of("registrationName", "onLoad"), - ImageLoadEvent.eventNameForType(ImageLoadEvent.ON_ERROR), - MapBuilder.of("registrationName", "onError"), - ImageLoadEvent.eventNameForType(ImageLoadEvent.ON_LOAD_END), - MapBuilder.of("registrationName", "onLoadEnd")); + ImageLoadEvent.eventNameForType(ImageLoadEvent.ON_LOAD_START), + MapBuilder.of("registrationName", "onLoadStart"), + ImageLoadEvent.eventNameForType(ImageLoadEvent.ON_LOAD), + MapBuilder.of("registrationName", "onLoad"), + ImageLoadEvent.eventNameForType(ImageLoadEvent.ON_ERROR), + MapBuilder.of("registrationName", "onError"), + ImageLoadEvent.eventNameForType(ImageLoadEvent.ON_LOAD_END), + MapBuilder.of("registrationName", "onLoadEnd")); } @Override diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/image/ReactImageView.java b/ReactAndroid/src/main/java/com/facebook/react/views/image/ReactImageView.java index 305f69526a3..38a53e20966 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/image/ReactImageView.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/image/ReactImageView.java @@ -1,11 +1,9 @@ - /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.image; import android.content.Context; @@ -72,7 +70,7 @@ public class ReactImageView extends GenericDraweeView { public static final int REMOTE_IMAGE_FADE_DURATION_MS = 300; public static final String REMOTE_TRANSPARENT_BITMAP_URI = - "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="; + "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="; private static float[] sComputedCornerRadii = new float[4]; @@ -95,12 +93,12 @@ public class ReactImageView extends GenericDraweeView { void getRadii(Bitmap source, float[] computedCornerRadii, float[] mappedRadii) { mScaleType.getTransform( - sMatrix, - new Rect(0, 0, source.getWidth(), source.getHeight()), - source.getWidth(), - source.getHeight(), - 0.0f, - 0.0f); + sMatrix, + new Rect(0, 0, source.getWidth(), source.getHeight()), + source.getWidth(), + source.getHeight(), + 0.0f, + 0.0f); sMatrix.invert(sInverse); mappedRadii[0] = sInverse.mapRadius(computedCornerRadii[0]); @@ -121,10 +119,10 @@ public class ReactImageView extends GenericDraweeView { cornerRadii(sComputedCornerRadii); output.setHasAlpha(true); - if (FloatUtil.floatsEqual(sComputedCornerRadii[0], 0f) && - FloatUtil.floatsEqual(sComputedCornerRadii[1], 0f) && - FloatUtil.floatsEqual(sComputedCornerRadii[2], 0f) && - FloatUtil.floatsEqual(sComputedCornerRadii[3], 0f)) { + if (FloatUtil.floatsEqual(sComputedCornerRadii[0], 0f) + && FloatUtil.floatsEqual(sComputedCornerRadii[1], 0f) + && FloatUtil.floatsEqual(sComputedCornerRadii[2], 0f) + && FloatUtil.floatsEqual(sComputedCornerRadii[3], 0f)) { super.process(output, source); return; } @@ -140,9 +138,7 @@ public class ReactImageView extends GenericDraweeView { Path pathForBorderRadius = new Path(); pathForBorderRadius.addRoundRect( - new RectF(0, 0, source.getWidth(), source.getHeight()), - radii, - Path.Direction.CW); + new RectF(0, 0, source.getWidth(), source.getHeight()), radii, Path.Direction.CW); canvas.drawPath(pathForBorderRadius, paint); } @@ -158,12 +154,7 @@ public class ReactImageView extends GenericDraweeView { final Rect destRect = new Rect(0, 0, getWidth(), getHeight()); mScaleType.getTransform( - sTileMatrix, - destRect, - source.getWidth(), - source.getHeight(), - 0.0f, - 0.0f); + sTileMatrix, destRect, source.getWidth(), source.getHeight(), 0.0f, 0.0f); Paint paint = new Paint(); paint.setAntiAlias(true); @@ -213,15 +204,15 @@ public class ReactImageView extends GenericDraweeView { // We can't specify rounding in XML, so have to do so here private static GenericDraweeHierarchy buildHierarchy(Context context) { return new GenericDraweeHierarchyBuilder(context.getResources()) - .setRoundingParams(RoundingParams.fromCornersRadius(0)) - .build(); + .setRoundingParams(RoundingParams.fromCornersRadius(0)) + .build(); } public ReactImageView( - Context context, - AbstractDraweeControllerBuilder draweeControllerBuilder, - @Nullable GlobalImageLoadListener globalImageLoadListener, - @Nullable Object callerContext) { + Context context, + AbstractDraweeControllerBuilder draweeControllerBuilder, + @Nullable GlobalImageLoadListener globalImageLoadListener, + @Nullable Object callerContext) { super(context, buildHierarchy(context)); mScaleType = ImageResizeMode.defaultValue(); mDraweeControllerBuilder = draweeControllerBuilder; @@ -236,36 +227,40 @@ public class ReactImageView extends GenericDraweeView { if (!shouldNotify) { mControllerListener = null; } else { - final EventDispatcher mEventDispatcher = ((ReactContext) getContext()).getNativeModule(UIManagerModule.class).getEventDispatcher(); + final EventDispatcher mEventDispatcher = + ((ReactContext) getContext()).getNativeModule(UIManagerModule.class).getEventDispatcher(); - mControllerListener = new BaseControllerListener() { - @Override - public void onSubmit(String id, Object callerContext) { - mEventDispatcher.dispatchEvent( - new ImageLoadEvent(getId(), ImageLoadEvent.ON_LOAD_START)); - } + mControllerListener = + new BaseControllerListener() { + @Override + public void onSubmit(String id, Object callerContext) { + mEventDispatcher.dispatchEvent( + new ImageLoadEvent(getId(), ImageLoadEvent.ON_LOAD_START)); + } - @Override - public void onFinalImageSet( - String id, - @Nullable final ImageInfo imageInfo, - @Nullable Animatable animatable) { - if (imageInfo != null) { - mEventDispatcher.dispatchEvent( - new ImageLoadEvent(getId(), ImageLoadEvent.ON_LOAD, - mImageSource.getSource(), imageInfo.getWidth(), imageInfo.getHeight())); - mEventDispatcher.dispatchEvent( - new ImageLoadEvent(getId(), ImageLoadEvent.ON_LOAD_END)); - } - } + @Override + public void onFinalImageSet( + String id, @Nullable final ImageInfo imageInfo, @Nullable Animatable animatable) { + if (imageInfo != null) { + mEventDispatcher.dispatchEvent( + new ImageLoadEvent( + getId(), + ImageLoadEvent.ON_LOAD, + mImageSource.getSource(), + imageInfo.getWidth(), + imageInfo.getHeight())); + mEventDispatcher.dispatchEvent( + new ImageLoadEvent(getId(), ImageLoadEvent.ON_LOAD_END)); + } + } - @Override - public void onFailure(String id, Throwable throwable) { - mEventDispatcher.dispatchEvent( - new ImageLoadEvent(getId(), ImageLoadEvent.ON_ERROR, - true, throwable.getMessage())); - } - }; + @Override + public void onFailure(String id, Throwable throwable) { + mEventDispatcher.dispatchEvent( + new ImageLoadEvent( + getId(), ImageLoadEvent.ON_ERROR, true, throwable.getMessage())); + } + }; } mIsDirty = true; @@ -283,7 +278,7 @@ public class ReactImageView extends GenericDraweeView { @Override public void setBackgroundColor(int backgroundColor) { - if(mBackgroundColor != backgroundColor) { + if (mBackgroundColor != backgroundColor) { mBackgroundColor = backgroundColor; mBackgroundImageDrawable = new RoundedColorDrawable(backgroundColor); mIsDirty = true; @@ -358,11 +353,9 @@ public class ReactImageView extends GenericDraweeView { for (int idx = 0; idx < sources.size(); idx++) { ReadableMap source = sources.getMap(idx); String uri = source.getString("uri"); - ImageSource imageSource = new ImageSource( - getContext(), - uri, - source.getDouble("width"), - source.getDouble("height")); + ImageSource imageSource = + new ImageSource( + getContext(), uri, source.getDouble("width"), source.getDouble("height")); mSources.add(imageSource); if (Uri.EMPTY.equals(imageSource.getUri())) { warnImageSource(uri); @@ -374,14 +367,16 @@ public class ReactImageView extends GenericDraweeView { } public void setDefaultSource(@Nullable String name) { - mDefaultImageDrawable = ResourceDrawableIdHelper.getInstance().getResourceDrawable(getContext(), name); + mDefaultImageDrawable = + ResourceDrawableIdHelper.getInstance().getResourceDrawable(getContext(), name); mIsDirty = true; } public void setLoadingIndicatorSource(@Nullable String name) { - Drawable drawable = ResourceDrawableIdHelper.getInstance().getResourceDrawable(getContext(), name); + Drawable drawable = + ResourceDrawableIdHelper.getInstance().getResourceDrawable(getContext(), name); mLoadingImageDrawable = - drawable != null ? (Drawable) new AutoRotateDrawable(drawable, 1000) : null; + drawable != null ? (Drawable) new AutoRotateDrawable(drawable, 1000) : null; mIsDirty = true; } @@ -398,10 +393,22 @@ public class ReactImageView extends GenericDraweeView { private void cornerRadii(float[] computedCorners) { float defaultBorderRadius = !YogaConstants.isUndefined(mBorderRadius) ? mBorderRadius : 0; - computedCorners[0] = mBorderCornerRadii != null && !YogaConstants.isUndefined(mBorderCornerRadii[0]) ? mBorderCornerRadii[0] : defaultBorderRadius; - computedCorners[1] = mBorderCornerRadii != null && !YogaConstants.isUndefined(mBorderCornerRadii[1]) ? mBorderCornerRadii[1] : defaultBorderRadius; - computedCorners[2] = mBorderCornerRadii != null && !YogaConstants.isUndefined(mBorderCornerRadii[2]) ? mBorderCornerRadii[2] : defaultBorderRadius; - computedCorners[3] = mBorderCornerRadii != null && !YogaConstants.isUndefined(mBorderCornerRadii[3]) ? mBorderCornerRadii[3] : defaultBorderRadius; + computedCorners[0] = + mBorderCornerRadii != null && !YogaConstants.isUndefined(mBorderCornerRadii[0]) + ? mBorderCornerRadii[0] + : defaultBorderRadius; + computedCorners[1] = + mBorderCornerRadii != null && !YogaConstants.isUndefined(mBorderCornerRadii[1]) + ? mBorderCornerRadii[1] + : defaultBorderRadius; + computedCorners[2] = + mBorderCornerRadii != null && !YogaConstants.isUndefined(mBorderCornerRadii[2]) + ? mBorderCornerRadii[2] + : defaultBorderRadius; + computedCorners[3] = + mBorderCornerRadii != null && !YogaConstants.isUndefined(mBorderCornerRadii[3]) + ? mBorderCornerRadii[3] + : defaultBorderRadius; } public void setHeaders(ReadableMap headers) { @@ -446,14 +453,18 @@ public class ReactImageView extends GenericDraweeView { } boolean usePostprocessorScaling = - mScaleType != ScalingUtils.ScaleType.CENTER_CROP && - mScaleType != ScalingUtils.ScaleType.FOCUS_CROP; + mScaleType != ScalingUtils.ScaleType.CENTER_CROP + && mScaleType != ScalingUtils.ScaleType.FOCUS_CROP; RoundingParams roundingParams = hierarchy.getRoundingParams(); cornerRadii(sComputedCornerRadii); - roundingParams.setCornersRadii(sComputedCornerRadii[0], sComputedCornerRadii[1], sComputedCornerRadii[2], sComputedCornerRadii[3]); + roundingParams.setCornersRadii( + sComputedCornerRadii[0], + sComputedCornerRadii[1], + sComputedCornerRadii[2], + sComputedCornerRadii[3]); if (mBackgroundImageDrawable != null) { mBackgroundImageDrawable.setBorder(mBorderColor, mBorderWidth); @@ -474,9 +485,9 @@ public class ReactImageView extends GenericDraweeView { } hierarchy.setRoundingParams(roundingParams); hierarchy.setFadeDuration( - mFadeDurationMs >= 0 - ? mFadeDurationMs - : mImageSource.isResource() ? 0 : REMOTE_IMAGE_FADE_DURATION_MS); + mFadeDurationMs >= 0 + ? mFadeDurationMs + : mImageSource.isResource() ? 0 : REMOTE_IMAGE_FADE_DURATION_MS); List postprocessors = new LinkedList<>(); if (usePostprocessorScaling) { @@ -492,13 +503,15 @@ public class ReactImageView extends GenericDraweeView { ResizeOptions resizeOptions = doResize ? new ResizeOptions(getWidth(), getHeight()) : null; - ImageRequestBuilder imageRequestBuilder = ImageRequestBuilder.newBuilderWithSource(mImageSource.getUri()) - .setPostprocessor(postprocessor) - .setResizeOptions(resizeOptions) - .setAutoRotateEnabled(true) - .setProgressiveRenderingEnabled(mProgressiveRenderingEnabled); + ImageRequestBuilder imageRequestBuilder = + ImageRequestBuilder.newBuilderWithSource(mImageSource.getUri()) + .setPostprocessor(postprocessor) + .setResizeOptions(resizeOptions) + .setAutoRotateEnabled(true) + .setProgressiveRenderingEnabled(mProgressiveRenderingEnabled); - ImageRequest imageRequest = ReactNetworkImageRequest.fromBuilderWithHeaders(imageRequestBuilder, mHeaders); + ImageRequest imageRequest = + ReactNetworkImageRequest.fromBuilderWithHeaders(imageRequestBuilder, mHeaders); if (mGlobalImageLoadListener != null) { mGlobalImageLoadListener.onLoadAttempt(mImageSource.getUri()); @@ -508,19 +521,19 @@ public class ReactImageView extends GenericDraweeView { mDraweeControllerBuilder.reset(); mDraweeControllerBuilder - .setAutoPlayAnimations(true) - .setCallerContext(mCallerContext) - .setOldController(getController()) - .setImageRequest(imageRequest); + .setAutoPlayAnimations(true) + .setCallerContext(mCallerContext) + .setOldController(getController()) + .setImageRequest(imageRequest); if (mCachedImageSource != null) { ImageRequest cachedImageRequest = - ImageRequestBuilder.newBuilderWithSource(mCachedImageSource.getUri()) - .setPostprocessor(postprocessor) - .setResizeOptions(resizeOptions) - .setAutoRotateEnabled(true) - .setProgressiveRenderingEnabled(mProgressiveRenderingEnabled) - .build(); + ImageRequestBuilder.newBuilderWithSource(mCachedImageSource.getUri()) + .setPostprocessor(postprocessor) + .setResizeOptions(resizeOptions) + .setAutoRotateEnabled(true) + .setProgressiveRenderingEnabled(mProgressiveRenderingEnabled) + .build(); mDraweeControllerBuilder.setLowResImageRequest(cachedImageRequest); } @@ -559,9 +572,7 @@ public class ReactImageView extends GenericDraweeView { } } - /** - * ReactImageViews only render a single image. - */ + /** ReactImageViews only render a single image. */ @Override public boolean hasOverlappingRendering() { return false; @@ -582,7 +593,7 @@ public class ReactImageView extends GenericDraweeView { mSources.add(imageSource); } else if (hasMultipleSources()) { MultiSourceResult multiSource = - MultiSourceHelper.getBestSourceForSize(getWidth(), getHeight(), mSources); + MultiSourceHelper.getBestSourceForSize(getWidth(), getHeight(), mSources); mImageSource = multiSource.getBestResult(); mCachedImageSource = multiSource.getBestResultInCache(); return; @@ -596,9 +607,8 @@ public class ReactImageView extends GenericDraweeView { // We resize here only for images likely to be from the device's camera, where the app developer // has no control over the original size if (mResizeMethod == ImageResizeMethod.AUTO) { - return - UriUtil.isLocalContentUri(imageSource.getUri()) || - UriUtil.isLocalFileUri(imageSource.getUri()); + return UriUtil.isLocalContentUri(imageSource.getUri()) + || UriUtil.isLocalFileUri(imageSource.getUri()); } else if (mResizeMethod == ImageResizeMethod.RESIZE) { return true; } else { @@ -609,9 +619,10 @@ public class ReactImageView extends GenericDraweeView { private void warnImageSource(String uri) { if (ReactBuildConfig.DEBUG) { Toast.makeText( - getContext(), - "Warning: Image source \"" + uri + "\" doesn't exist", - Toast.LENGTH_SHORT).show(); + getContext(), + "Warning: Image source \"" + uri + "\" doesn't exist", + Toast.LENGTH_SHORT) + .show(); } } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/image/ScaleTypeStartInside.java b/ReactAndroid/src/main/java/com/facebook/react/views/image/ScaleTypeStartInside.java index 3a512dbb55d..af96b994ef4 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/image/ScaleTypeStartInside.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/image/ScaleTypeStartInside.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.image; import android.graphics.Matrix; diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/imagehelper/ImageSource.java b/ReactAndroid/src/main/java/com/facebook/react/views/imagehelper/ImageSource.java index 748247785d6..d79b7a54ced 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/imagehelper/ImageSource.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/imagehelper/ImageSource.java @@ -1,22 +1,17 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.imagehelper; -import javax.annotation.Nullable; - import android.content.Context; import android.net.Uri; - import com.facebook.infer.annotation.Assertions; +import javax.annotation.Nullable; -/** - * Class describing an image source (network URI or resource) and size. - */ +/** Class describing an image source (network URI or resource) and size. */ public class ImageSource { private @Nullable Uri mUri; @@ -37,30 +32,22 @@ public class ImageSource { this(context, source, 0.0d, 0.0d); } - /** - * Get the source of this image, as it was passed to the constructor. - */ + /** Get the source of this image, as it was passed to the constructor. */ public String getSource() { return mSource; } - /** - * Get the URI for this image - can be either a parsed network URI or a resource URI. - */ + /** Get the URI for this image - can be either a parsed network URI or a resource URI. */ public Uri getUri() { return Assertions.assertNotNull(mUri); } - /** - * Get the area of this image. - */ + /** Get the area of this image. */ public double getSize() { return mSize; } - /** - * Get whether this image source represents an Android resource or a network URI. - */ + /** Get whether this image source represents an Android resource or a network URI. */ public boolean isResource() { return isResource; } diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/imagehelper/MultiSourceHelper.java b/ReactAndroid/src/main/java/com/facebook/react/views/imagehelper/MultiSourceHelper.java index f71ea562de1..8355956d975 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/imagehelper/MultiSourceHelper.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/imagehelper/MultiSourceHelper.java @@ -1,23 +1,17 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.imagehelper; -import javax.annotation.Nullable; - -import java.util.List; - import com.facebook.imagepipeline.core.ImagePipeline; import com.facebook.imagepipeline.core.ImagePipelineFactory; -import com.facebook.react.views.imagehelper.ImageSource; +import java.util.List; +import javax.annotation.Nullable; -/** - * Helper class for dealing with multisource images. - */ +/** Helper class for dealing with multisource images. */ public class MultiSourceHelper { public static class MultiSourceResult { @@ -25,8 +19,7 @@ public class MultiSourceHelper { private final @Nullable ImageSource bestResultInCache; private MultiSourceResult( - @Nullable ImageSource bestResult, - @Nullable ImageSource bestResultInCache) { + @Nullable ImageSource bestResult, @Nullable ImageSource bestResultInCache) { this.bestResult = bestResult; this.bestResultInCache = bestResultInCache; } @@ -50,9 +43,7 @@ public class MultiSourceHelper { } public static MultiSourceResult getBestSourceForSize( - int width, - int height, - List sources) { + int width, int height, List sources) { return getBestSourceForSize(width, height, sources, 1.0d); } @@ -63,14 +54,11 @@ public class MultiSourceHelper { * @param height the height of the view that will be used to display this image * @param sources the list of potential image sources to choose from * @param multiplier the area of the view will be multiplied by this number before calculating the - * best source; this is useful if the image will be displayed bigger than the view - * (e.g. zoomed) + * best source; this is useful if the image will be displayed bigger than the view (e.g. + * zoomed) */ public static MultiSourceResult getBestSourceForSize( - int width, - int height, - List sources, - double multiplier) { + int width, int height, List sources, double multiplier) { // no sources if (sources.isEmpty()) { return new MultiSourceResult(null, null); @@ -99,9 +87,9 @@ public class MultiSourceHelper { bestPrecision = precision; best = source; } - if (precision < bestCachePrecision && - (imagePipeline.isInBitmapMemoryCache(source.getUri()) || - imagePipeline.isInDiskCacheSync(source.getUri()))) { + if (precision < bestCachePrecision + && (imagePipeline.isInBitmapMemoryCache(source.getUri()) + || imagePipeline.isInDiskCacheSync(source.getUri()))) { bestCachePrecision = precision; bestCached = source; } diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/imagehelper/ResourceDrawableIdHelper.java b/ReactAndroid/src/main/java/com/facebook/react/views/imagehelper/ResourceDrawableIdHelper.java index 724db8c376d..6c64e23eb15 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/imagehelper/ResourceDrawableIdHelper.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/imagehelper/ResourceDrawableIdHelper.java @@ -1,25 +1,20 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.imagehelper; -import javax.annotation.Nullable; -import javax.annotation.concurrent.ThreadSafe; - -import java.util.HashMap; -import java.util.Map; - import android.content.Context; import android.graphics.drawable.Drawable; import android.net.Uri; +import java.util.HashMap; +import java.util.Map; +import javax.annotation.Nullable; +import javax.annotation.concurrent.ThreadSafe; -/** - * Helper class for obtaining information about local images. - */ +/** Helper class for obtaining information about local images. */ @ThreadSafe public class ResourceDrawableIdHelper { @@ -64,10 +59,7 @@ public class ResourceDrawableIdHelper { if (mResourceDrawableIdMap.containsKey(name)) { return mResourceDrawableIdMap.get(name); } - int id = context.getResources().getIdentifier( - name, - "drawable", - context.getPackageName()); + int id = context.getResources().getIdentifier(name, "drawable", context.getPackageName()); mResourceDrawableIdMap.put(name, id); return id; } @@ -80,9 +72,8 @@ public class ResourceDrawableIdHelper { public Uri getResourceDrawableUri(Context context, @Nullable String name) { int resId = getResourceDrawableId(context, name); - return resId > 0 ? new Uri.Builder() - .scheme(LOCAL_RESOURCE_SCHEME) - .path(String.valueOf(resId)) - .build() : Uri.EMPTY; + return resId > 0 + ? new Uri.Builder().scheme(LOCAL_RESOURCE_SCHEME).path(String.valueOf(resId)).build() + : Uri.EMPTY; } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/modal/ModalHostHelper.java b/ReactAndroid/src/main/java/com/facebook/react/views/modal/ModalHostHelper.java index fb56a2fd14d..62693781108 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/modal/ModalHostHelper.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/modal/ModalHostHelper.java @@ -11,12 +11,9 @@ import android.content.res.TypedArray; import android.graphics.Point; import android.view.Display; import android.view.WindowManager; - import com.facebook.infer.annotation.Assertions; -/** - * Helper class for Modals. - */ +/** Helper class for Modals. */ /*package*/ class ModalHostHelper { private static final Point MIN_POINT = new Point(); @@ -24,13 +21,11 @@ import com.facebook.infer.annotation.Assertions; private static final Point SIZE_POINT = new Point(); /** - * To get the size of the screen, we use information from the WindowManager and - * default Display. We don't use DisplayMetricsHolder, or Display#getSize() because - * they return values that include the status bar. We only want the values of what - * will actually be shown on screen. - * We use Display#getSize() to determine if the screen is in portrait or landscape. - * We don't use getRotation because the 'natural' rotation will be portrait on phones - * and landscape on tablets. + * To get the size of the screen, we use information from the WindowManager and default Display. + * We don't use DisplayMetricsHolder, or Display#getSize() because they return values that include + * the status bar. We only want the values of what will actually be shown on screen. We use + * Display#getSize() to determine if the screen is in portrait or landscape. We don't use + * getRotation because the 'natural' rotation will be portrait on phones and landscape on tablets. * This should only be called on the native modules/shadow nodes thread. */ public static Point getModalHostSize(Context context) { @@ -52,7 +47,7 @@ import com.facebook.infer.annotation.Assertions; int statusBarId = resources.getIdentifier("status_bar_height", "dimen", "android"); int statusBarHeight = 0; if (windowFullscreen && statusBarId > 0) { - statusBarHeight = (int) resources.getDimension(statusBarId); + statusBarHeight = (int) resources.getDimension(statusBarId); } if (SIZE_POINT.x < SIZE_POINT.y) { diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/modal/ModalHostShadowNode.java b/ReactAndroid/src/main/java/com/facebook/react/views/modal/ModalHostShadowNode.java index 0e0fd429a3f..8d0e93f4d8f 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/modal/ModalHostShadowNode.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/modal/ModalHostShadowNode.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.modal; import android.graphics.Point; @@ -13,10 +12,10 @@ import com.facebook.react.uimanager.ReactShadowNodeImpl; /** * We implement the Modal by using an Android Dialog. That will fill the entire window of the - * application. To get layout to work properly, we need to layout all the elements within the - * Modal's inner content view as if they can fill the entire window. To do that, we need to + * application. To get layout to work properly, we need to layout all the elements within the + * Modal's inner content view as if they can fill the entire window. To do that, we need to * explicitly set the styleWidth and styleHeight on the LayoutShadowNode of the child of this node - * to be the window size. This will then cause the children of the Modal to layout as if they can + * to be the window size. This will then cause the children of the Modal to layout as if they can * fill the window. */ class ModalHostShadowNode extends LayoutShadowNode { diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/modal/ReactModalHostManager.java b/ReactAndroid/src/main/java/com/facebook/react/views/modal/ReactModalHostManager.java index 6a73f5c7d4a..d80902e9c48 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/modal/ReactModalHostManager.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/modal/ReactModalHostManager.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.modal; import android.content.DialogInterface; @@ -23,9 +22,7 @@ import com.facebook.react.uimanager.annotations.ReactProp; import com.facebook.react.uimanager.events.EventDispatcher; import java.util.Map; -/** - * View manager for {@link ReactModalHostView} components. - */ +/** View manager for {@link ReactModalHostView} components. */ @ReactModule(name = ReactModalHostManager.REACT_CLASS) public class ReactModalHostManager extends ViewGroupManager { @@ -73,33 +70,31 @@ public class ReactModalHostManager extends ViewGroupManager } @Override - protected void addEventEmitters( - ThemedReactContext reactContext, - final ReactModalHostView view) { + protected void addEventEmitters(ThemedReactContext reactContext, final ReactModalHostView view) { final EventDispatcher dispatcher = - reactContext.getNativeModule(UIManagerModule.class).getEventDispatcher(); + reactContext.getNativeModule(UIManagerModule.class).getEventDispatcher(); view.setOnRequestCloseListener( - new ReactModalHostView.OnRequestCloseListener() { - @Override - public void onRequestClose(DialogInterface dialog) { - dispatcher.dispatchEvent(new RequestCloseEvent(view.getId())); - } - }); + new ReactModalHostView.OnRequestCloseListener() { + @Override + public void onRequestClose(DialogInterface dialog) { + dispatcher.dispatchEvent(new RequestCloseEvent(view.getId())); + } + }); view.setOnShowListener( - new DialogInterface.OnShowListener() { - @Override - public void onShow(DialogInterface dialog) { - dispatcher.dispatchEvent(new ShowEvent(view.getId())); - } - }); + new DialogInterface.OnShowListener() { + @Override + public void onShow(DialogInterface dialog) { + dispatcher.dispatchEvent(new ShowEvent(view.getId())); + } + }); } @Override public Map getExportedCustomDirectEventTypeConstants() { return MapBuilder.builder() - .put(RequestCloseEvent.EVENT_NAME, MapBuilder.of("registrationName", "onRequestClose")) - .put(ShowEvent.EVENT_NAME, MapBuilder.of("registrationName", "onShow")) - .build(); + .put(RequestCloseEvent.EVENT_NAME, MapBuilder.of("registrationName", "onRequestClose")) + .put(ShowEvent.EVENT_NAME, MapBuilder.of("registrationName", "onShow")) + .build(); } @Override diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/modal/ReactModalHostView.java b/ReactAndroid/src/main/java/com/facebook/react/views/modal/ReactModalHostView.java index 3c3244194fd..f1ce43f3041 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/modal/ReactModalHostView.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/modal/ReactModalHostView.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.modal; import android.annotation.TargetApi; @@ -38,14 +37,13 @@ import javax.annotation.Nullable; /** * ReactModalHostView is a view that sits in the view hierarchy representing a Modal view. * - * It does a number of things: - * 1. It creates a Dialog. We use this Dialog to actually display the Modal in the window. - * 2. It creates a DialogRootViewGroup. This view is the view that is displayed by the Dialog. To - * display a view within a Dialog, that view must have its parent set to the window the Dialog - * creates. Because of this, we can not use the ReactModalHostView since it sits in the - * normal React view hierarchy. We do however want all of the layout magic to happen as if the - * DialogRootViewGroup were part of the hierarchy. Therefore, we forward all view changes - * around addition and removal of views to the DialogRootViewGroup. + *

It does a number of things: 1. It creates a Dialog. We use this Dialog to actually display the + * Modal in the window. 2. It creates a DialogRootViewGroup. This view is the view that is displayed + * by the Dialog. To display a view within a Dialog, that view must have its parent set to the + * window the Dialog creates. Because of this, we can not use the ReactModalHostView since it sits + * in the normal React view hierarchy. We do however want all of the layout magic to happen as if + * the DialogRootViewGroup were part of the hierarchy. Therefore, we forward all view changes around + * addition and removal of views to the DialogRootViewGroup. */ public class ReactModalHostView extends ViewGroup implements LifecycleEventListener { @@ -133,7 +131,8 @@ public class ReactModalHostView extends ViewGroup implements LifecycleEventListe private void dismiss() { if (mDialog != null) { if (mDialog.isShowing()) { - Activity dialogContext = ContextUtils.findContextOfType(mDialog.getContext(), Activity.class); + Activity dialogContext = + ContextUtils.findContextOfType(mDialog.getContext(), Activity.class); if (dialogContext == null || !dialogContext.isFinishing()) { mDialog.dismiss(); } @@ -196,10 +195,10 @@ public class ReactModalHostView extends ViewGroup implements LifecycleEventListe } /** - * showOrUpdate will display the Dialog. It is called by the manager once all properties are set - * because we need to know all of them before creating the Dialog. It is also smart during - * updates if the changed properties can be applied directly to the Dialog or require the - * recreation of a new Dialog. + * showOrUpdate will display the Dialog. It is called by the manager once all properties are set + * because we need to know all of them before creating the Dialog. It is also smart during updates + * if the changed properties can be applied directly to the Dialog or require the recreation of a + * new Dialog. */ protected void showOrUpdate() { // If the existing Dialog is currently up, we may need to redraw it or we may be able to update @@ -224,39 +223,48 @@ public class ReactModalHostView extends ViewGroup implements LifecycleEventListe Activity currentActivity = getCurrentActivity(); Context context = currentActivity == null ? getContext() : currentActivity; mDialog = new Dialog(context, theme); - mDialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE); + mDialog + .getWindow() + .setFlags( + WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, + WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE); mDialog.setContentView(getContentView()); updateProperties(); mDialog.setOnShowListener(mOnShowListener); mDialog.setOnKeyListener( - new DialogInterface.OnKeyListener() { - @Override - public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { - if (event.getAction() == KeyEvent.ACTION_UP) { - // We need to stop the BACK button from closing the dialog by default so we capture that - // event and instead inform JS so that it can make the decision as to whether or not to - // allow the back button to close the dialog. If it chooses to, it can just set visible - // to false on the Modal and the Modal will go away - if (keyCode == KeyEvent.KEYCODE_BACK) { - Assertions.assertNotNull( - mOnRequestCloseListener, - "setOnRequestCloseListener must be called by the manager"); - mOnRequestCloseListener.onRequestClose(dialog); - return true; - } else { - // We redirect the rest of the key events to the current activity, since the activity - // expects to receive those events and react to them, ie. in the case of the dev menu - Activity currentActivity = ((ReactContext) getContext()).getCurrentActivity(); - if (currentActivity != null) { - return currentActivity.onKeyUp(keyCode, event); + new DialogInterface.OnKeyListener() { + @Override + public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { + if (event.getAction() == KeyEvent.ACTION_UP) { + // We need to stop the BACK button from closing the dialog by default so we capture + // that + // event and instead inform JS so that it can make the decision as to whether or not + // to + // allow the back button to close the dialog. If it chooses to, it can just set + // visible + // to false on the Modal and the Modal will go away + if (keyCode == KeyEvent.KEYCODE_BACK) { + Assertions.assertNotNull( + mOnRequestCloseListener, + "setOnRequestCloseListener must be called by the manager"); + mOnRequestCloseListener.onRequestClose(dialog); + return true; + } else { + // We redirect the rest of the key events to the current activity, since the + // activity + // expects to receive those events and react to them, ie. in the case of the dev + // menu + Activity currentActivity = ((ReactContext) getContext()).getCurrentActivity(); + if (currentActivity != null) { + return currentActivity.onKeyUp(keyCode, event); + } } } + return false; } - return false; - } - }); + }); mDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE); if (mHardwareAccelerated) { @@ -264,10 +272,12 @@ public class ReactModalHostView extends ViewGroup implements LifecycleEventListe } if (currentActivity != null && !currentActivity.isFinishing()) { mDialog.show(); - if (context instanceof Activity){ - mDialog.getWindow().getDecorView().setSystemUiVisibility( - ((Activity)context).getWindow().getDecorView().getSystemUiVisibility() - ); + if (context instanceof Activity) { + mDialog + .getWindow() + .getDecorView() + .setSystemUiVisibility( + ((Activity) context).getWindow().getDecorView().getSystemUiVisibility()); } mDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE); } @@ -276,8 +286,8 @@ public class ReactModalHostView extends ViewGroup implements LifecycleEventListe /** * Returns the view that will be the root view of the dialog. We are wrapping this in a * FrameLayout because this is the system's way of notifying us that the dialog size has changed. - * This has the pleasant side-effect of us not having to preface all Modals with - * "top: statusBarHeight", since that margin will be included in the FrameLayout. + * This has the pleasant side-effect of us not having to preface all Modals with "top: + * statusBarHeight", since that margin will be included in the FrameLayout. */ private View getContentView() { FrameLayout frameLayout = new FrameLayout(getContext()); @@ -297,8 +307,7 @@ public class ReactModalHostView extends ViewGroup implements LifecycleEventListe Activity currentActivity = getCurrentActivity(); if (currentActivity != null) { int activityWindowFlags = currentActivity.getWindow().getAttributes().flags; - if ((activityWindowFlags - & WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0) { + if ((activityWindowFlags & WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0) { mDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } else { mDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); @@ -309,20 +318,22 @@ public class ReactModalHostView extends ViewGroup implements LifecycleEventListe mDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); } else { mDialog.getWindow().setDimAmount(0.5f); - mDialog.getWindow().setFlags( - WindowManager.LayoutParams.FLAG_DIM_BEHIND, - WindowManager.LayoutParams.FLAG_DIM_BEHIND); + mDialog + .getWindow() + .setFlags( + WindowManager.LayoutParams.FLAG_DIM_BEHIND, + WindowManager.LayoutParams.FLAG_DIM_BEHIND); } } /** - * DialogRootViewGroup is the ViewGroup which contains all the children of a Modal. It gets all - * child information forwarded from ReactModalHostView and uses that to create children. It is - * also responsible for acting as a RootView and handling touch events. It does this the same - * way as ReactRootView. + * DialogRootViewGroup is the ViewGroup which contains all the children of a Modal. It gets all + * child information forwarded from ReactModalHostView and uses that to create children. It is + * also responsible for acting as a RootView and handling touch events. It does this the same way + * as ReactRootView. * - * To get layout to work properly, we need to layout all the elements within the Modal as if they - * can fill the entire window. To do that, we need to explicitly set the styleWidth and + *

To get layout to work properly, we need to layout all the elements within the Modal as if + * they can fill the entire window. To do that, we need to explicitly set the styleWidth and * styleHeight on the LayoutShadowNode to be the window size. This is done through the * UIManagerModule, and will then cause the children to layout as if they can fill the window. */ @@ -351,13 +362,14 @@ public class ReactModalHostView extends ViewGroup implements LifecycleEventListe final int viewTag = getChildAt(0).getId(); ReactContext reactContext = getReactContext(); reactContext.runOnNativeModulesQueueThread( - new GuardedRunnable(reactContext) { - @Override - public void runGuarded() { - (getReactContext()).getNativeModule(UIManagerModule.class) - .updateNodeSize(viewTag, viewWidth, viewHeight); - } - }); + new GuardedRunnable(reactContext) { + @Override + public void runGuarded() { + (getReactContext()) + .getNativeModule(UIManagerModule.class) + .updateNodeSize(viewTag, viewWidth, viewHeight); + } + }); } else { hasAdjustedSize = true; } diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/modal/RequestCloseEvent.java b/ReactAndroid/src/main/java/com/facebook/react/views/modal/RequestCloseEvent.java index e8154261b1c..fbda54ffd28 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/modal/RequestCloseEvent.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/modal/RequestCloseEvent.java @@ -1,18 +1,15 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.modal; import com.facebook.react.uimanager.events.Event; import com.facebook.react.uimanager.events.RCTEventEmitter; -/** - * {@link Event} for dismissing a Dialog. - */ +/** {@link Event} for dismissing a Dialog. */ /* package */ class RequestCloseEvent extends Event { public static final String EVENT_NAME = "topRequestClose"; diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/modal/ShowEvent.java b/ReactAndroid/src/main/java/com/facebook/react/views/modal/ShowEvent.java index 4a89bc82436..bea6a2487c4 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/modal/ShowEvent.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/modal/ShowEvent.java @@ -1,18 +1,15 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.modal; import com.facebook.react.uimanager.events.Event; import com.facebook.react.uimanager.events.RCTEventEmitter; -/** - * {@link Event} for showing a Dialog. - */ +/** {@link Event} for showing a Dialog. */ /* package */ class ShowEvent extends Event { public static final String EVENT_NAME = "topShow"; diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/picker/ReactDialogPickerManager.java b/ReactAndroid/src/main/java/com/facebook/react/views/picker/ReactDialogPickerManager.java index b16678ebe40..5f5ca20b02a 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/picker/ReactDialogPickerManager.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/picker/ReactDialogPickerManager.java @@ -1,20 +1,16 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.picker; import android.widget.Spinner; - import com.facebook.react.module.annotations.ReactModule; import com.facebook.react.uimanager.ThemedReactContext; -/** - * {@link ReactPickerManager} for {@link ReactPicker} with {@link Spinner#MODE_DIALOG}. - */ +/** {@link ReactPickerManager} for {@link ReactPicker} with {@link Spinner#MODE_DIALOG}. */ @ReactModule(name = ReactDialogPickerManager.REACT_CLASS) public class ReactDialogPickerManager extends ReactPickerManager { diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/picker/ReactDropdownPickerManager.java b/ReactAndroid/src/main/java/com/facebook/react/views/picker/ReactDropdownPickerManager.java index e3c25721cb9..955f2827d48 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/picker/ReactDropdownPickerManager.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/picker/ReactDropdownPickerManager.java @@ -1,20 +1,16 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.picker; import android.widget.Spinner; - import com.facebook.react.module.annotations.ReactModule; import com.facebook.react.uimanager.ThemedReactContext; -/** - * {@link ReactPickerManager} for {@link ReactPicker} with {@link Spinner#MODE_DROPDOWN}. - */ +/** {@link ReactPickerManager} for {@link ReactPicker} with {@link Spinner#MODE_DROPDOWN}. */ @ReactModule(name = ReactDropdownPickerManager.REACT_CLASS) public class ReactDropdownPickerManager extends ReactPickerManager { diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/picker/ReactPicker.java b/ReactAndroid/src/main/java/com/facebook/react/views/picker/ReactPicker.java index 4a529892274..4e75e504a2b 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/picker/ReactPicker.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/picker/ReactPicker.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.picker; import android.content.Context; @@ -12,13 +11,9 @@ import android.util.AttributeSet; import android.view.View; import android.widget.AdapterView; import android.widget.Spinner; - import androidx.appcompat.widget.AppCompatSpinner; - import com.facebook.react.common.annotations.VisibleForTesting; - import java.util.List; - import javax.annotation.Nullable; public class ReactPicker extends AppCompatSpinner { @@ -30,25 +25,24 @@ public class ReactPicker extends AppCompatSpinner { private @Nullable Integer mStagedSelection; private @Nullable Integer mStagedPrimaryTextColor; - private final OnItemSelectedListener mItemSelectedListener = new OnItemSelectedListener() { - @Override - public void onItemSelected(AdapterView parent, View view, int position, long id) { - if (mOnSelectListener != null) { - mOnSelectListener.onItemSelected(position); - } - } + private final OnItemSelectedListener mItemSelectedListener = + new OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView parent, View view, int position, long id) { + if (mOnSelectListener != null) { + mOnSelectListener.onItemSelected(position); + } + } - @Override - public void onNothingSelected(AdapterView parent) { - if (mOnSelectListener != null) { - mOnSelectListener.onItemSelected(-1); - } - } - }; + @Override + public void onNothingSelected(AdapterView parent) { + if (mOnSelectListener != null) { + mOnSelectListener.onItemSelected(-1); + } + } + }; - /** - * Listener interface for ReactPicker events. - */ + /** Listener interface for ReactPicker events. */ public interface OnSelectListener { void onItemSelected(int position); } @@ -75,15 +69,16 @@ public class ReactPicker extends AppCompatSpinner { mMode = mode; } - private final Runnable measureAndLayout = new Runnable() { - @Override - public void run() { - measure( - MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.EXACTLY), - MeasureSpec.makeMeasureSpec(getHeight(), MeasureSpec.EXACTLY)); - layout(getLeft(), getTop(), getRight(), getBottom()); - } - }; + private final Runnable measureAndLayout = + new Runnable() { + @Override + public void run() { + measure( + MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.EXACTLY), + MeasureSpec.makeMeasureSpec(getHeight(), MeasureSpec.EXACTLY)); + layout(getLeft(), getTop(), getRight(), getBottom()); + } + }; @Override public void requestLayout() { @@ -104,25 +99,24 @@ public class ReactPicker extends AppCompatSpinner { // AdapterView updates the selection position from the default INVALID_POSITION. // To match iOS behavior, which no onItemSelected during initial layout. // We setup the listener after layout. - if (getOnItemSelectedListener() == null) - setOnItemSelectedListener(mItemSelectedListener); + if (getOnItemSelectedListener() == null) setOnItemSelectedListener(mItemSelectedListener); } public void setOnSelectListener(@Nullable OnSelectListener onSelectListener) { mOnSelectListener = onSelectListener; } - @Nullable public OnSelectListener getOnSelectListener() { + @Nullable + public OnSelectListener getOnSelectListener() { return mOnSelectListener; } /* package */ void setStagedItems(final @Nullable List items) { - mStagedItems = items; + mStagedItems = items; } /** - * Will cache "selection" value locally and set it only once {@link #commitStagedData} is - * called + * Will cache "selection" value locally and set it only once {@link #commitStagedData} is called */ /* package */ void setStagedSelection(int selection) { mStagedSelection = selection; @@ -133,9 +127,9 @@ public class ReactPicker extends AppCompatSpinner { } /** - * Used to commit staged data into ReactPicker view. - * During this period, we will disable {@link OnSelectListener#onItemSelected(int)} temporarily, - * so we don't get an event when changing the items/selection ourselves. + * Used to commit staged data into ReactPicker view. During this period, we will disable {@link + * OnSelectListener#onItemSelected(int)} temporarily, so we don't get an event when changing the + * items/selection ourselves. */ /* package */ void commitStagedData() { setOnItemSelectedListener(null); @@ -160,9 +154,9 @@ public class ReactPicker extends AppCompatSpinner { mStagedSelection = null; } - if (mStagedPrimaryTextColor != null && - adapter != null && - mStagedPrimaryTextColor != adapter.getPrimaryTextColor()) { + if (mStagedPrimaryTextColor != null + && adapter != null + && mStagedPrimaryTextColor != adapter.getPrimaryTextColor()) { adapter.setPrimaryTextColor(mStagedPrimaryTextColor); mStagedPrimaryTextColor = null; } diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/picker/ReactPickerAdapter.java b/ReactAndroid/src/main/java/com/facebook/react/views/picker/ReactPickerAdapter.java index b2415d88df6..5dea24204ee 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/picker/ReactPickerAdapter.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/picker/ReactPickerAdapter.java @@ -6,25 +6,22 @@ import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; - import com.facebook.infer.annotation.Assertions; - import java.util.List; - import javax.annotation.Nullable; /* package */ class ReactPickerAdapter extends ArrayAdapter { private final LayoutInflater mInflater; - private @Nullable - Integer mPrimaryTextColor; + private @Nullable Integer mPrimaryTextColor; public ReactPickerAdapter(Context context, List data) { super(context, 0, data); - mInflater = (LayoutInflater) Assertions.assertNotNull( - context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)); + mInflater = + (LayoutInflater) + Assertions.assertNotNull(context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)); } @Override @@ -40,9 +37,10 @@ class ReactPickerAdapter extends ArrayAdapter { private View getView(int position, View convertView, ViewGroup parent, boolean isDropdown) { ReactPickerItem item = getItem(position); if (convertView == null) { - int layoutResId = isDropdown - ? android.R.layout.simple_spinner_dropdown_item - : android.R.layout.simple_spinner_item; + int layoutResId = + isDropdown + ? android.R.layout.simple_spinner_dropdown_item + : android.R.layout.simple_spinner_item; convertView = mInflater.inflate(layoutResId, parent, false); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/picker/ReactPickerItem.java b/ReactAndroid/src/main/java/com/facebook/react/views/picker/ReactPickerItem.java index 0473183773d..5b102150701 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/picker/ReactPickerItem.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/picker/ReactPickerItem.java @@ -2,17 +2,14 @@ package com.facebook.react.views.picker; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableMap; - import java.util.ArrayList; import java.util.List; - import javax.annotation.Nullable; /* package */ class ReactPickerItem { public final String label; - @Nullable - public final Integer color; + @Nullable public final Integer color; public ReactPickerItem(final ReadableMap jsMapData) { label = jsMapData.getString("label"); diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/picker/ReactPickerManager.java b/ReactAndroid/src/main/java/com/facebook/react/views/picker/ReactPickerManager.java index a4fc550d9ea..e3f42a92c4a 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/picker/ReactPickerManager.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/picker/ReactPickerManager.java @@ -1,14 +1,12 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.picker; import android.widget.Spinner; - import com.facebook.react.bridge.ReadableArray; import com.facebook.react.uimanager.SimpleViewManager; import com.facebook.react.uimanager.ThemedReactContext; @@ -17,17 +15,14 @@ import com.facebook.react.uimanager.ViewProps; import com.facebook.react.uimanager.annotations.ReactProp; import com.facebook.react.uimanager.events.EventDispatcher; import com.facebook.react.views.picker.events.PickerItemSelectEvent; - import java.util.List; - import javax.annotation.Nullable; /** - * {@link ViewManager} for the {@link ReactPicker} view. This is abstract because the - * {@link Spinner} doesn't support setting the mode (dropdown/dialog) outside the constructor, so - * that is delegated to the separate {@link ReactDropdownPickerManager} and - * {@link ReactDialogPickerManager} components. These are merged back on the JS side into one - * React component. + * {@link ViewManager} for the {@link ReactPicker} view. This is abstract because the {@link + * Spinner} doesn't support setting the mode (dropdown/dialog) outside the constructor, so that is + * delegated to the separate {@link ReactDropdownPickerManager} and {@link ReactDialogPickerManager} + * components. These are merged back on the JS side into one React component. */ public abstract class ReactPickerManager extends SimpleViewManager { @@ -64,13 +59,10 @@ public abstract class ReactPickerManager extends SimpleViewManager } @Override - protected void addEventEmitters( - final ThemedReactContext reactContext, - final ReactPicker picker) { + protected void addEventEmitters(final ThemedReactContext reactContext, final ReactPicker picker) { picker.setOnSelectListener( - new PickerEventEmitter( - picker, - reactContext.getNativeModule(UIManagerModule.class).getEventDispatcher())); + new PickerEventEmitter( + picker, reactContext.getNativeModule(UIManagerModule.class).getEventDispatcher())); } private static class PickerEventEmitter implements ReactPicker.OnSelectListener { @@ -85,8 +77,7 @@ public abstract class ReactPickerManager extends SimpleViewManager @Override public void onItemSelected(int position) { - mEventDispatcher.dispatchEvent( new PickerItemSelectEvent( - mReactPicker.getId(), position)); + mEventDispatcher.dispatchEvent(new PickerItemSelectEvent(mReactPicker.getId(), position)); } } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/picker/events/PickerItemSelectEvent.java b/ReactAndroid/src/main/java/com/facebook/react/views/picker/events/PickerItemSelectEvent.java index e50b7b3ad50..ff5ef4680b3 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/picker/events/PickerItemSelectEvent.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/picker/events/PickerItemSelectEvent.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.picker.events; import com.facebook.react.bridge.Arguments; diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/progressbar/ProgressBarContainerView.java b/ReactAndroid/src/main/java/com/facebook/react/views/progressbar/ProgressBarContainerView.java index e4a3b463376..a4b4a85f5fb 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/progressbar/ProgressBarContainerView.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/progressbar/ProgressBarContainerView.java @@ -5,8 +5,6 @@ package com.facebook.react.views.progressbar; -import javax.annotation.Nullable; - import android.content.Context; import android.graphics.PorterDuff; import android.graphics.drawable.Drawable; @@ -14,12 +12,12 @@ import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ProgressBar; - import com.facebook.react.bridge.JSApplicationIllegalArgumentException; +import javax.annotation.Nullable; /** - * Controls an enclosing ProgressBar. Exists so that the ProgressBar can be recreated if - * the style would change. + * Controls an enclosing ProgressBar. Exists so that the ProgressBar can be recreated if the style + * would change. */ /* package */ class ProgressBarContainerView extends FrameLayout { private static final int MAX_PROGRESS = 1000; @@ -42,8 +40,7 @@ import com.facebook.react.bridge.JSApplicationIllegalArgumentException; addView( mProgressBar, new ViewGroup.LayoutParams( - ViewGroup.LayoutParams.MATCH_PARENT, - ViewGroup.LayoutParams.MATCH_PARENT)); + ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); } public void setColor(@Nullable Integer color) { diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/progressbar/ProgressBarShadowNode.java b/ReactAndroid/src/main/java/com/facebook/react/views/progressbar/ProgressBarShadowNode.java index e6cb2adceae..c176549b884 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/progressbar/ProgressBarShadowNode.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/progressbar/ProgressBarShadowNode.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.progressbar; import android.util.SparseIntArray; @@ -22,9 +21,9 @@ import java.util.Set; import javax.annotation.Nullable; /** - * Node responsible for holding the style of the ProgressBar, see under - * {@link android.R.attr.progressBarStyle} for possible styles. ReactProgressBarViewManager - * manages how this style is applied to the ProgressBar. + * Node responsible for holding the style of the ProgressBar, see under {@link + * android.R.attr.progressBarStyle} for possible styles. ReactProgressBarViewManager manages how + * this style is applied to the ProgressBar. */ public class ProgressBarShadowNode extends LayoutShadowNode implements YogaMeasureFunction { @@ -63,10 +62,11 @@ public class ProgressBarShadowNode extends LayoutShadowNode implements YogaMeasu YogaMeasureMode heightMode) { final int style = ReactProgressBarViewManager.getStyleFromString(getStyle()); if (!mMeasured.contains(style)) { - ProgressBar progressBar = ReactProgressBarViewManager.createProgressBar(getThemedContext(), style); - final int spec = View.MeasureSpec.makeMeasureSpec( - ViewGroup.LayoutParams.WRAP_CONTENT, - View.MeasureSpec.UNSPECIFIED); + ProgressBar progressBar = + ReactProgressBarViewManager.createProgressBar(getThemedContext(), style); + final int spec = + View.MeasureSpec.makeMeasureSpec( + ViewGroup.LayoutParams.WRAP_CONTENT, View.MeasureSpec.UNSPECIFIED); progressBar.measure(spec, spec); mHeight.put(style, progressBar.getMeasuredHeight()); mWidth.put(style, progressBar.getMeasuredWidth()); diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/progressbar/ReactProgressBarViewManager.java b/ReactAndroid/src/main/java/com/facebook/react/views/progressbar/ReactProgressBarViewManager.java index 24b01e9114b..54e3fd604e4 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/progressbar/ReactProgressBarViewManager.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/progressbar/ReactProgressBarViewManager.java @@ -1,23 +1,20 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.progressbar; -import javax.annotation.Nullable; - import android.content.Context; import android.widget.ProgressBar; - import com.facebook.react.bridge.JSApplicationIllegalArgumentException; import com.facebook.react.module.annotations.ReactModule; import com.facebook.react.uimanager.BaseViewManager; -import com.facebook.react.uimanager.annotations.ReactProp; import com.facebook.react.uimanager.ThemedReactContext; import com.facebook.react.uimanager.ViewProps; +import com.facebook.react.uimanager.annotations.ReactProp; +import javax.annotation.Nullable; /** * Manages instances of ProgressBar. ProgressBar is wrapped in a ProgressBarContainerView because @@ -26,8 +23,8 @@ import com.facebook.react.uimanager.ViewProps; * one with the style given. */ @ReactModule(name = ReactProgressBarViewManager.REACT_CLASS) -public class ReactProgressBarViewManager extends - BaseViewManager { +public class ReactProgressBarViewManager + extends BaseViewManager { public static final String REACT_CLASS = "AndroidProgressBar"; @@ -112,7 +109,7 @@ public class ReactProgressBarViewManager extends "ProgressBar needs to have a style, null received"); } else if (styleStr.equals("Horizontal")) { return android.R.attr.progressBarStyleHorizontal; - } else if (styleStr.equals("Small")) { + } else if (styleStr.equals("Small")) { return android.R.attr.progressBarStyleSmall; } else if (styleStr.equals("Large")) { return android.R.attr.progressBarStyleLarge; diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/scroll/FpsListener.java b/ReactAndroid/src/main/java/com/facebook/react/views/scroll/FpsListener.java index 607c396833d..7fa6063b7f9 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/scroll/FpsListener.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/scroll/FpsListener.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.scroll; public interface FpsListener { @@ -17,17 +16,15 @@ public interface FpsListener { void enable(String tag); /** - * Clients should call this method when they want the listener to stop recording data. - * The listener will then report the data it collected. + * Clients should call this method when they want the listener to stop recording data. The + * listener will then report the data it collected. * - * Calling disable on a listener that has already been disabled is a no-op. + *

Calling disable on a listener that has already been disabled is a no-op. * * @param tag */ void disable(String tag); - /** - * Reports whether this listener is recording data. - */ + /** Reports whether this listener is recording data. */ boolean isEnabled(); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/scroll/OnScrollDispatchHelper.java b/ReactAndroid/src/main/java/com/facebook/react/views/scroll/OnScrollDispatchHelper.java index 6b90c839b2f..15f92878efb 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/scroll/OnScrollDispatchHelper.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/scroll/OnScrollDispatchHelper.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.scroll; import android.os.SystemClock; @@ -32,9 +31,7 @@ public class OnScrollDispatchHelper { public boolean onScrollChanged(int x, int y) { long eventTime = SystemClock.uptimeMillis(); boolean shouldDispatch = - eventTime - mLastScrollEventTimeMs > MIN_EVENT_SEPARATION_MS || - mPrevX != x || - mPrevY != y; + eventTime - mLastScrollEventTimeMs > MIN_EVENT_SEPARATION_MS || mPrevX != x || mPrevY != y; if (eventTime - mLastScrollEventTimeMs != 0) { mXFlingVelocity = (float) (x - mPrevX) / (eventTime - mLastScrollEventTimeMs); diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactHorizontalScrollContainerView.java b/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactHorizontalScrollContainerView.java index 5ff0da06ca8..f64600b13a6 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactHorizontalScrollContainerView.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactHorizontalScrollContainerView.java @@ -6,9 +6,9 @@ package com.facebook.react.views.scroll; import android.content.Context; -import androidx.core.view.ViewCompat; import android.view.ViewGroup; import android.widget.HorizontalScrollView; +import androidx.core.view.ViewCompat; import com.facebook.react.modules.i18nmanager.I18nUtil; /** Container of Horizontal scrollViews that supports RTL scrolling. */ @@ -20,7 +20,9 @@ public class ReactHorizontalScrollContainerView extends ViewGroup { public ReactHorizontalScrollContainerView(Context context) { super(context); mLayoutDirection = - I18nUtil.getInstance().isRTL(context) ? ViewCompat.LAYOUT_DIRECTION_RTL : ViewCompat.LAYOUT_DIRECTION_LTR; + I18nUtil.getInstance().isRTL(context) + ? ViewCompat.LAYOUT_DIRECTION_RTL + : ViewCompat.LAYOUT_DIRECTION_LTR; mCurrentWidth = 0; } diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactHorizontalScrollView.java b/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactHorizontalScrollView.java index 57d47d2956a..407b1a87d8a 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactHorizontalScrollView.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactHorizontalScrollView.java @@ -1,52 +1,43 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.scroll; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; +import android.graphics.Rect; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; -import android.graphics.drawable.LayerDrawable; -import android.graphics.Rect; -import android.hardware.SensorManager; -import androidx.core.view.ViewCompat; -import androidx.core.text.TextUtilsCompat; import android.util.Log; -import android.view.KeyEvent; import android.view.FocusFinder; +import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; -import android.view.ViewConfiguration; import android.widget.HorizontalScrollView; import android.widget.OverScroller; - +import androidx.core.text.TextUtilsCompat; +import androidx.core.view.ViewCompat; import com.facebook.infer.annotation.Assertions; import com.facebook.react.common.ReactConstants; -import com.facebook.react.uimanager.events.NativeGestureUtil; import com.facebook.react.uimanager.MeasureSpecAssertions; import com.facebook.react.uimanager.ReactClippingViewGroup; import com.facebook.react.uimanager.ReactClippingViewGroupHelper; import com.facebook.react.uimanager.ViewProps; +import com.facebook.react.uimanager.events.NativeGestureUtil; import com.facebook.react.views.view.ReactViewBackgroundManager; - import java.lang.reflect.Field; +import java.util.ArrayList; import java.util.List; import java.util.Locale; import javax.annotation.Nullable; -import java.util.ArrayList; -import java.util.List; -/** - * Similar to {@link ReactScrollView} but only supports horizontal scrolling. - */ -public class ReactHorizontalScrollView extends HorizontalScrollView implements - ReactClippingViewGroup { +/** Similar to {@link ReactScrollView} but only supports horizontal scrolling. */ +public class ReactHorizontalScrollView extends HorizontalScrollView + implements ReactClippingViewGroup { private static @Nullable Field sScrollerField; private static boolean sTriedToGetScrollerField = false; @@ -103,9 +94,9 @@ public class ReactHorizontalScrollView extends HorizontalScrollView implements sScrollerField.setAccessible(true); } catch (NoSuchFieldException e) { Log.w( - ReactConstants.TAG, - "Failed to get mScroller field for HorizontalScrollView! " + - "This app will exhibit the bounce-back scrolling bug :("); + ReactConstants.TAG, + "Failed to get mScroller field for HorizontalScrollView! " + + "This app will exhibit the bounce-back scrolling bug :("); } } @@ -116,9 +107,9 @@ public class ReactHorizontalScrollView extends HorizontalScrollView implements scroller = (OverScroller) scrollerValue; } else { Log.w( - ReactConstants.TAG, - "Failed to cast mScroller field in HorizontalScrollView (probably due to OEM changes to AOSP)! " + - "This app will exhibit the bounce-back scrolling bug :("); + ReactConstants.TAG, + "Failed to cast mScroller field in HorizontalScrollView (probably due to OEM changes to AOSP)! " + + "This app will exhibit the bounce-back scrolling bug :("); scroller = null; } } catch (IllegalAccessException e) { @@ -218,8 +209,7 @@ public class ReactHorizontalScrollView extends HorizontalScrollView implements MeasureSpecAssertions.assertExplicitMeasureSpec(widthMeasureSpec, heightMeasureSpec); setMeasuredDimension( - MeasureSpec.getSize(widthMeasureSpec), - MeasureSpec.getSize(heightMeasureSpec)); + MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.getSize(heightMeasureSpec)); } @Override @@ -229,11 +219,11 @@ public class ReactHorizontalScrollView extends HorizontalScrollView implements } /** - * Since ReactHorizontalScrollView handles layout changes on JS side, it does not call super.onlayout - * due to which mIsLayoutDirty flag in HorizontalScrollView remains true and prevents scrolling to child - * when requestChildFocus is called. - * Overriding this method and scrolling to child without checking any layout dirty flag. This will fix - * focus navigation issue for KeyEvents which are not handled in HorizontalScrollView, for example: KEYCODE_TAB. + * Since ReactHorizontalScrollView handles layout changes on JS side, it does not call + * super.onlayout due to which mIsLayoutDirty flag in HorizontalScrollView remains true and + * prevents scrolling to child when requestChildFocus is called. Overriding this method and + * scrolling to child without checking any layout dirty flag. This will fix focus navigation issue + * for KeyEvents which are not handled in HorizontalScrollView, for example: KEYCODE_TAB. */ @Override public void requestChildFocus(View child, View focused) { @@ -250,9 +240,12 @@ public class ReactHorizontalScrollView extends HorizontalScrollView implements ArrayList candidateViews = new ArrayList(); super.addFocusables(candidateViews, direction, focusableMode); for (View candidate : candidateViews) { - // We must also include the currently focused in the focusables list or focus search will always + // We must also include the currently focused in the focusables list or focus search will + // always // return the first element within the focusables list - if (isScrolledInView(candidate) || isPartiallyScrolledInView(candidate) || candidate.isFocused()) { + if (isScrolledInView(candidate) + || isPartiallyScrolledInView(candidate) + || candidate.isFocused()) { views.add(candidate); } } @@ -261,35 +254,26 @@ public class ReactHorizontalScrollView extends HorizontalScrollView implements } } - /** - * Calculates the x delta required to scroll the given descendent into view - */ + /** Calculates the x delta required to scroll the given descendent into view */ private int getScrollDelta(View descendent) { descendent.getDrawingRect(mTempRect); offsetDescendantRectToMyCoords(descendent, mTempRect); return computeScrollDeltaToGetChildRectOnScreen(mTempRect); } - /** - * Returns whether the given descendent is scrolled fully in view - */ + /** Returns whether the given descendent is scrolled fully in view */ private boolean isScrolledInView(View descendent) { return getScrollDelta(descendent) == 0; } - - /** - * Returns whether the given descendent is partially scrolled in view - */ + /** Returns whether the given descendent is partially scrolled in view */ private boolean isPartiallyScrolledInView(View descendent) { int scrollDelta = getScrollDelta(descendent); descendent.getDrawingRect(mTempRect); return scrollDelta != 0 && Math.abs(scrollDelta) < mTempRect.width(); } - /** - * Returns whether the given descendent is "mostly" (>50%) scrolled in view - */ + /** Returns whether the given descendent is "mostly" (>50%) scrolled in view */ private boolean isMostlyScrolledInView(View descendent) { int scrollDelta = getScrollDelta(descendent); descendent.getDrawingRect(mTempRect); @@ -316,9 +300,9 @@ public class ReactHorizontalScrollView extends HorizontalScrollView implements } ReactScrollViewHelper.emitScrollEvent( - this, - mOnScrollDispatchHelper.getXFlingVelocity(), - mOnScrollDispatchHelper.getYFlingVelocity()); + this, + mOnScrollDispatchHelper.getXFlingVelocity(), + mOnScrollDispatchHelper.getYFlingVelocity()); } } @@ -399,10 +383,7 @@ public class ReactHorizontalScrollView extends HorizontalScrollView implements if (action == MotionEvent.ACTION_UP && mDragging) { float velocityX = mVelocityHelper.getXVelocity(); float velocityY = mVelocityHelper.getYVelocity(); - ReactScrollViewHelper.emitScrollEndDragEvent( - this, - velocityX, - velocityY); + ReactScrollViewHelper.emitScrollEndDragEvent(this, velocityX, velocityY); mDragging = false; // After the touch finishes, we may need to do some scrolling afterwards either as a result // of a fling or because we need to page align the content @@ -415,8 +396,9 @@ public class ReactHorizontalScrollView extends HorizontalScrollView implements @Override public boolean executeKeyEvent(KeyEvent event) { int eventKeyCode = event.getKeyCode(); - if (!mScrollEnabled && (eventKeyCode == KeyEvent.KEYCODE_DPAD_LEFT || - eventKeyCode == KeyEvent.KEYCODE_DPAD_RIGHT)) { + if (!mScrollEnabled + && (eventKeyCode == KeyEvent.KEYCODE_DPAD_LEFT + || eventKeyCode == KeyEvent.KEYCODE_DPAD_RIGHT)) { return false; } return super.executeKeyEvent(event); @@ -427,12 +409,13 @@ public class ReactHorizontalScrollView extends HorizontalScrollView implements // Workaround. // On Android P if a ScrollView is inverted, we will get a wrong sign for - // velocityX (see https://issuetracker.google.com/issues/112385925). - // At the same time, mOnScrollDispatchHelper tracks the correct velocity direction. + // velocityX (see https://issuetracker.google.com/issues/112385925). + // At the same time, mOnScrollDispatchHelper tracks the correct velocity direction. // // Hence, we can use the absolute value from whatever the OS gives // us and use the sign of what mOnScrollDispatchHelper has tracked. - final int correctedVelocityX = (int)(Math.abs(velocityX) * Math.signum(mOnScrollDispatchHelper.getXFlingVelocity())); + final int correctedVelocityX = + (int) (Math.abs(velocityX) * Math.signum(mOnScrollDispatchHelper.getXFlingVelocity())); if (mPagingEnabled) { flingAndSnap(correctedVelocityX); @@ -441,24 +424,27 @@ public class ReactHorizontalScrollView extends HorizontalScrollView implements // We provide our own version of fling that uses a different call to the standard OverScroller // which takes into account the possibility of adding new content while the ScrollView is - // animating. Because we give essentially no max X for the fling, the fling will continue as long - // as there is content. See #onOverScrolled() to see the second part of this change which properly + // animating. Because we give essentially no max X for the fling, the fling will continue as + // long + // as there is content. See #onOverScrolled() to see the second part of this change which + // properly // aborts the scroller animation when we get to the bottom of the ScrollView content. - int scrollWindowWidth = getWidth() - ViewCompat.getPaddingStart(this) - ViewCompat.getPaddingEnd(this); + int scrollWindowWidth = + getWidth() - ViewCompat.getPaddingStart(this) - ViewCompat.getPaddingEnd(this); mScroller.fling( - getScrollX(), // startX - getScrollY(), // startY - correctedVelocityX, // velocityX - 0, // velocityY - 0, // minX - Integer.MAX_VALUE, // maxX - 0, // minY - 0, // maxY - scrollWindowWidth / 2, // overX - 0 // overY - ); + getScrollX(), // startX + getScrollY(), // startY + correctedVelocityX, // velocityX + 0, // velocityY + 0, // minX + Integer.MAX_VALUE, // maxX + 0, // minY + 0, // maxY + scrollWindowWidth / 2, // overX + 0 // overY + ); ViewCompat.postInvalidateOnAnimation(this); @@ -524,7 +510,8 @@ public class ReactHorizontalScrollView extends HorizontalScrollView implements if (mScroller != null) { // FB SCROLLVIEW CHANGE - // This is part two of the reimplementation of fling to fix the bounce-back bug. See #fling() for + // This is part two of the reimplementation of fling to fix the bounce-back bug. See #fling() + // for // more information. if (!mScroller.isFinished() && mScroller.getCurrX() != mScroller.getFinalX()) { @@ -574,8 +561,8 @@ public class ReactHorizontalScrollView extends HorizontalScrollView implements } /** - * This handles any sort of scrolling that may occur after a touch is finished. This may be - * momentum scrolling (fling) or because you have pagingEnabled on the scroll view. Because we + * This handles any sort of scrolling that may occur after a touch is finished. This may be + * momentum scrolling (fling) or because you have pagingEnabled on the scroll view. Because we * don't get any events from Android about this lifecycle, we do all our detection by creating a * runnable that checks if we scrolled in the last frame and if so assumes we are still scrolling. */ @@ -596,40 +583,39 @@ public class ReactHorizontalScrollView extends HorizontalScrollView implements } mActivelyScrolling = false; - mPostTouchRunnable = new Runnable() { + mPostTouchRunnable = + new Runnable() { - private boolean mSnappingToPage = false; + private boolean mSnappingToPage = false; - @Override - public void run() { - if (mActivelyScrolling) { - // We are still scrolling so we just post to check again a frame later - mActivelyScrolling = false; - ViewCompat.postOnAnimationDelayed(ReactHorizontalScrollView.this, - this, - ReactScrollViewHelper.MOMENTUM_DELAY); - } else { - if (mPagingEnabled && !mSnappingToPage) { - // Only if we have pagingEnabled and we have not snapped to the page do we - // need to continue checking for the scroll. And we cause that scroll by asking for it - mSnappingToPage = true; - flingAndSnap(0); - ViewCompat.postOnAnimationDelayed(ReactHorizontalScrollView.this, - this, - ReactScrollViewHelper.MOMENTUM_DELAY); - } else { - if (mSendMomentumEvents) { - ReactScrollViewHelper.emitScrollMomentumEndEvent(ReactHorizontalScrollView.this); + @Override + public void run() { + if (mActivelyScrolling) { + // We are still scrolling so we just post to check again a frame later + mActivelyScrolling = false; + ViewCompat.postOnAnimationDelayed( + ReactHorizontalScrollView.this, this, ReactScrollViewHelper.MOMENTUM_DELAY); + } else { + if (mPagingEnabled && !mSnappingToPage) { + // Only if we have pagingEnabled and we have not snapped to the page do we + // need to continue checking for the scroll. And we cause that scroll by asking for + // it + mSnappingToPage = true; + flingAndSnap(0); + ViewCompat.postOnAnimationDelayed( + ReactHorizontalScrollView.this, this, ReactScrollViewHelper.MOMENTUM_DELAY); + } else { + if (mSendMomentumEvents) { + ReactScrollViewHelper.emitScrollMomentumEndEvent(ReactHorizontalScrollView.this); + } + ReactHorizontalScrollView.this.mPostTouchRunnable = null; + disableFpsListener(); + } } - ReactHorizontalScrollView.this.mPostTouchRunnable = null; - disableFpsListener(); } - } - } - }; - ViewCompat.postOnAnimationDelayed(ReactHorizontalScrollView.this, - mPostTouchRunnable, - ReactScrollViewHelper.MOMENTUM_DELAY); + }; + ViewCompat.postOnAnimationDelayed( + ReactHorizontalScrollView.this, mPostTouchRunnable, ReactScrollViewHelper.MOMENTUM_DELAY); } private int predictFinalScrollPosition(int velocityX) { @@ -643,24 +629,24 @@ public class ReactHorizontalScrollView extends HorizontalScrollView implements int maximumOffset = Math.max(0, computeHorizontalScrollRange() - getWidth()); int width = getWidth() - ViewCompat.getPaddingStart(this) - ViewCompat.getPaddingEnd(this); scroller.fling( - getScrollX(), // startX - getScrollY(), // startY - velocityX, // velocityX - 0, // velocityY - 0, // minX - maximumOffset, // maxX - 0, // minY - 0, // maxY - width/2, // overX - 0 // overY - ); + getScrollX(), // startX + getScrollY(), // startY + velocityX, // velocityX + 0, // velocityY + 0, // minX + maximumOffset, // maxX + 0, // minY + 0, // maxY + width / 2, // overX + 0 // overY + ); return scroller.getFinalX(); } /** - * This will smooth scroll us to the nearest snap offset point - * It currently just looks at where the content is and slides to the nearest point. - * It is intended to be run after we are done scrolling, and handling any momentum scrolling. + * This will smooth scroll us to the nearest snap offset point It currently just looks at where + * the content is and slides to the nearest point. It is intended to be run after we are done + * scrolling, and handling any momentum scrolling. */ private void smoothScrollAndSnap(int velocity) { double interval = (double) getSnapInterval(); @@ -673,29 +659,30 @@ public class ReactHorizontalScrollView extends HorizontalScrollView implements int targetPage = (int) Math.round(targetOffset / interval); if (velocity > 0 && nextPage == previousPage) { - nextPage ++; + nextPage++; } else if (velocity < 0 && previousPage == nextPage) { - previousPage --; + previousPage--; } if ( - // if scrolling towards next page - velocity > 0 && - // and the middle of the page hasn't been crossed already - currentPage < nextPage && - // and it would have been crossed after flinging - targetPage > previousPage - ) { + // if scrolling towards next page + velocity > 0 + && + // and the middle of the page hasn't been crossed already + currentPage < nextPage + && + // and it would have been crossed after flinging + targetPage > previousPage) { currentPage = nextPage; - } - else if ( - // if scrolling towards previous page - velocity < 0 && - // and the middle of the page hasn't been crossed already - currentPage > previousPage && - // and it would have been crossed after flinging - targetPage < nextPage - ) { + } else if ( + // if scrolling towards previous page + velocity < 0 + && + // and the middle of the page hasn't been crossed already + currentPage > previousPage + && + // and it would have been crossed after flinging + targetPage < nextPage) { currentPage = previousPage; } @@ -730,7 +717,9 @@ public class ReactHorizontalScrollView extends HorizontalScrollView implements int width = getWidth() - ViewCompat.getPaddingStart(this) - ViewCompat.getPaddingEnd(this); // offsets are from the right edge in RTL layouts - boolean isRTL = TextUtilsCompat.getLayoutDirectionFromLocale(Locale.getDefault()) == ViewCompat.LAYOUT_DIRECTION_RTL; + boolean isRTL = + TextUtilsCompat.getLayoutDirectionFromLocale(Locale.getDefault()) + == ViewCompat.LAYOUT_DIRECTION_RTL; if (isRTL) { targetOffset = maximumOffset - targetOffset; velocityX = -velocityX; @@ -741,7 +730,7 @@ public class ReactHorizontalScrollView extends HorizontalScrollView implements firstOffset = mSnapOffsets.get(0); lastOffset = mSnapOffsets.get(mSnapOffsets.size() - 1); - for (int i = 0; i < mSnapOffsets.size(); i ++) { + for (int i = 0; i < mSnapOffsets.size(); i++) { int offset = mSnapOffsets.get(i); if (offset <= targetOffset) { @@ -764,9 +753,8 @@ public class ReactHorizontalScrollView extends HorizontalScrollView implements } // Calculate the nearest offset - int nearestOffset = targetOffset - smallerOffset < largerOffset - targetOffset - ? smallerOffset - : largerOffset; + int nearestOffset = + targetOffset - smallerOffset < largerOffset - targetOffset ? smallerOffset : largerOffset; // if scrolling after the last snap offset and snapping to the // end of the list is disabled, then we allow free scrolling @@ -818,22 +806,22 @@ public class ReactHorizontalScrollView extends HorizontalScrollView implements mActivelyScrolling = true; mScroller.fling( - getScrollX(), // startX - getScrollY(), // startY - // velocity = 0 doesn't work with fling() so we pretend there's a reasonable - // initial velocity going on when a touch is released without any movement - velocityX != 0 ? velocityX : targetOffset - getScrollX(), // velocityX - 0, // velocityY - // setting both minX and maxX to the same value will guarantee that we scroll to it - // but using the standard fling-style easing rather than smoothScrollTo's 250ms animation - targetOffset, // minX - targetOffset, // maxX - 0, // minY - 0, // maxY - // we only want to allow overscrolling if the final offset is at the very edge of the view - (targetOffset == 0 || targetOffset == maximumOffset) ? width / 2 : 0, // overX - 0 // overY - ); + getScrollX(), // startX + getScrollY(), // startY + // velocity = 0 doesn't work with fling() so we pretend there's a reasonable + // initial velocity going on when a touch is released without any movement + velocityX != 0 ? velocityX : targetOffset - getScrollX(), // velocityX + 0, // velocityY + // setting both minX and maxX to the same value will guarantee that we scroll to it + // but using the standard fling-style easing rather than smoothScrollTo's 250ms animation + targetOffset, // minX + targetOffset, // maxX + 0, // minY + 0, // maxY + // we only want to allow overscrolling if the final offset is at the very edge of the view + (targetOffset == 0 || targetOffset == maximumOffset) ? width / 2 : 0, // overX + 0 // overY + ); postInvalidateOnAnimation(); } else { @@ -888,5 +876,4 @@ public class ReactHorizontalScrollView extends HorizontalScrollView implements public void setBorderStyle(@Nullable String style) { mReactBackgroundManager.setBorderStyle(style); } - } diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactHorizontalScrollViewManager.java b/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactHorizontalScrollViewManager.java index b07816d4c27..14796cd48a3 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactHorizontalScrollViewManager.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactHorizontalScrollViewManager.java @@ -1,16 +1,14 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.scroll; import android.graphics.Color; -import androidx.core.view.ViewCompat; import android.util.DisplayMetrics; - +import androidx.core.view.ViewCompat; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.module.annotations.ReactModule; import com.facebook.react.uimanager.DisplayMetricsHolder; @@ -23,7 +21,6 @@ import com.facebook.react.uimanager.ViewProps; import com.facebook.react.uimanager.annotations.ReactProp; import com.facebook.react.uimanager.annotations.ReactPropGroup; import com.facebook.yoga.YogaConstants; - import java.util.ArrayList; import java.util.List; import javax.annotation.Nullable; @@ -31,18 +28,17 @@ import javax.annotation.Nullable; /** * View manager for {@link ReactHorizontalScrollView} components. * - *

Note that {@link ReactScrollView} and {@link ReactHorizontalScrollView} are exposed to JS - * as a single ScrollView component, configured via the {@code horizontal} boolean property. + *

Note that {@link ReactScrollView} and {@link ReactHorizontalScrollView} are exposed to JS as a + * single ScrollView component, configured via the {@code horizontal} boolean property. */ @ReactModule(name = ReactHorizontalScrollViewManager.REACT_CLASS) -public class ReactHorizontalScrollViewManager - extends ViewGroupManager +public class ReactHorizontalScrollViewManager extends ViewGroupManager implements ReactScrollViewCommandHelper.ScrollCommandHandler { public static final String REACT_CLASS = "AndroidHorizontalScrollView"; private static final int[] SPACING_TYPES = { - Spacing.ALL, Spacing.LEFT, Spacing.RIGHT, Spacing.TOP, Spacing.BOTTOM, + Spacing.ALL, Spacing.LEFT, Spacing.RIGHT, Spacing.TOP, Spacing.BOTTOM, }; private @Nullable FpsListener mFpsListener = null; @@ -81,7 +77,8 @@ public class ReactHorizontalScrollViewManager } @ReactProp(name = "disableIntervalMomentum") - public void setDisableIntervalMomentum(ReactHorizontalScrollView view, boolean disbaleIntervalMomentum) { + public void setDisableIntervalMomentum( + ReactHorizontalScrollView view, boolean disbaleIntervalMomentum) { view.setDisableIntervalMomentum(disbaleIntervalMomentum); } @@ -93,7 +90,8 @@ public class ReactHorizontalScrollViewManager } @ReactProp(name = "snapToOffsets") - public void setSnapToOffsets(ReactHorizontalScrollView view, @Nullable ReadableArray snapToOffsets) { + public void setSnapToOffsets( + ReactHorizontalScrollView view, @Nullable ReadableArray snapToOffsets) { DisplayMetrics screenDisplayMetrics = DisplayMetricsHolder.getScreenDisplayMetrics(); List offsets = new ArrayList(); for (int i = 0; i < snapToOffsets.size(); i++) { @@ -113,14 +111,15 @@ public class ReactHorizontalScrollViewManager } @ReactProp(name = ReactClippingViewGroupHelper.PROP_REMOVE_CLIPPED_SUBVIEWS) - public void setRemoveClippedSubviews(ReactHorizontalScrollView view, boolean removeClippedSubviews) { + public void setRemoveClippedSubviews( + ReactHorizontalScrollView view, boolean removeClippedSubviews) { view.setRemoveClippedSubviews(removeClippedSubviews); } /** - * Computing momentum events is potentially expensive since we post a runnable on the UI thread - * to see when it is done. We only do that if {@param sendMomentumEvents} is set to true. This - * is handled automatically in js by checking if there is a listener on the momentum events. + * Computing momentum events is potentially expensive since we post a runnable on the UI thread to + * see when it is done. We only do that if {@param sendMomentumEvents} is set to true. This is + * handled automatically in js by checking if there is a listener on the momentum events. * * @param view * @param sendMomentumEvents @@ -147,9 +146,7 @@ public class ReactHorizontalScrollViewManager view.setPagingEnabled(pagingEnabled); } - /** - * Controls overScroll behaviour - */ + /** Controls overScroll behaviour */ @ReactProp(name = "overScrollMode") public void setOverScrollMode(ReactHorizontalScrollView view, String value) { view.setOverScrollMode(ReactScrollViewHelper.parseOverScrollMode(value)); @@ -162,17 +159,13 @@ public class ReactHorizontalScrollViewManager @Override public void receiveCommand( - ReactHorizontalScrollView scrollView, - int commandId, - @Nullable ReadableArray args) { + ReactHorizontalScrollView scrollView, int commandId, @Nullable ReadableArray args) { ReactScrollViewCommandHelper.receiveCommand(this, scrollView, commandId, args); } @Override public void receiveCommand( - ReactHorizontalScrollView scrollView, - String commandId, - @Nullable ReadableArray args) { + ReactHorizontalScrollView scrollView, String commandId, @Nullable ReadableArray args) { ReactScrollViewCommandHelper.receiveCommand(this, scrollView, commandId, args); } @@ -196,8 +189,7 @@ public class ReactHorizontalScrollViewManager ReactHorizontalScrollView scrollView, ReactScrollViewCommandHelper.ScrollToEndCommandData data) { // ScrollView always has one child - the scrollable area - int right = - scrollView.getChildAt(0).getWidth() + scrollView.getPaddingRight(); + int right = scrollView.getChildAt(0).getWidth() + scrollView.getPaddingRight(); if (data.mAnimated) { scrollView.smoothScrollTo(right, scrollView.getScrollY()); } else { @@ -208,6 +200,7 @@ public class ReactHorizontalScrollViewManager /** * When set, fills the rest of the scrollview with a color to avoid setting a background and * creating unnecessary overdraw. + * * @param view * @param color */ @@ -216,13 +209,15 @@ public class ReactHorizontalScrollViewManager view.setEndFillColor(color); } - @ReactPropGroup(names = { - ViewProps.BORDER_RADIUS, - ViewProps.BORDER_TOP_LEFT_RADIUS, - ViewProps.BORDER_TOP_RIGHT_RADIUS, - ViewProps.BORDER_BOTTOM_RIGHT_RADIUS, - ViewProps.BORDER_BOTTOM_LEFT_RADIUS - }, defaultFloat = YogaConstants.UNDEFINED) + @ReactPropGroup( + names = { + ViewProps.BORDER_RADIUS, + ViewProps.BORDER_TOP_LEFT_RADIUS, + ViewProps.BORDER_TOP_RIGHT_RADIUS, + ViewProps.BORDER_BOTTOM_RIGHT_RADIUS, + ViewProps.BORDER_BOTTOM_LEFT_RADIUS + }, + defaultFloat = YogaConstants.UNDEFINED) public void setBorderRadius(ReactHorizontalScrollView view, int index, float borderRadius) { if (!YogaConstants.isUndefined(borderRadius)) { borderRadius = PixelUtil.toPixelFromDIP(borderRadius); @@ -240,13 +235,15 @@ public class ReactHorizontalScrollViewManager view.setBorderStyle(borderStyle); } - @ReactPropGroup(names = { - ViewProps.BORDER_WIDTH, - ViewProps.BORDER_LEFT_WIDTH, - ViewProps.BORDER_RIGHT_WIDTH, - ViewProps.BORDER_TOP_WIDTH, - ViewProps.BORDER_BOTTOM_WIDTH, - }, defaultFloat = YogaConstants.UNDEFINED) + @ReactPropGroup( + names = { + ViewProps.BORDER_WIDTH, + ViewProps.BORDER_LEFT_WIDTH, + ViewProps.BORDER_RIGHT_WIDTH, + ViewProps.BORDER_TOP_WIDTH, + ViewProps.BORDER_BOTTOM_WIDTH, + }, + defaultFloat = YogaConstants.UNDEFINED) public void setBorderWidth(ReactHorizontalScrollView view, int index, float width) { if (!YogaConstants.isUndefined(width)) { width = PixelUtil.toPixelFromDIP(width); @@ -254,13 +251,19 @@ public class ReactHorizontalScrollViewManager view.setBorderWidth(SPACING_TYPES[index], width); } - @ReactPropGroup(names = { - "borderColor", "borderLeftColor", "borderRightColor", "borderTopColor", "borderBottomColor" - }, customType = "Color") + @ReactPropGroup( + names = { + "borderColor", + "borderLeftColor", + "borderRightColor", + "borderTopColor", + "borderBottomColor" + }, + customType = "Color") public void setBorderColor(ReactHorizontalScrollView view, int index, Integer color) { float rgbComponent = - color == null ? YogaConstants.UNDEFINED : (float) ((int)color & 0x00FFFFFF); - float alphaComponent = color == null ? YogaConstants.UNDEFINED : (float) ((int)color >>> 24); + color == null ? YogaConstants.UNDEFINED : (float) ((int) color & 0x00FFFFFF); + float alphaComponent = color == null ? YogaConstants.UNDEFINED : (float) ((int) color >>> 24); view.setBorderColor(SPACING_TYPES[index], rgbComponent, alphaComponent); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactScrollView.java b/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactScrollView.java index b2126d6debe..433583ee200 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactScrollView.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactScrollView.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.scroll; import android.graphics.Canvas; @@ -12,7 +11,6 @@ import android.graphics.Color; import android.graphics.Rect; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; -import androidx.core.view.ViewCompat; import android.util.Log; import android.view.KeyEvent; import android.view.MotionEvent; @@ -20,17 +18,16 @@ import android.view.View; import android.view.ViewGroup; import android.widget.OverScroller; import android.widget.ScrollView; - +import androidx.core.view.ViewCompat; import com.facebook.infer.annotation.Assertions; import com.facebook.react.bridge.ReactContext; import com.facebook.react.common.ReactConstants; -import com.facebook.react.uimanager.events.NativeGestureUtil; import com.facebook.react.uimanager.MeasureSpecAssertions; import com.facebook.react.uimanager.ReactClippingViewGroup; import com.facebook.react.uimanager.ReactClippingViewGroupHelper; import com.facebook.react.uimanager.ViewProps; +import com.facebook.react.uimanager.events.NativeGestureUtil; import com.facebook.react.views.view.ReactViewBackgroundManager; - import java.lang.reflect.Field; import java.util.List; import javax.annotation.Nullable; @@ -39,10 +36,13 @@ import javax.annotation.Nullable; * A simple subclass of ScrollView that doesn't dispatch measure and layout to its children and has * a scroll listener to send scroll events to JS. * - *

ReactScrollView only supports vertical scrolling. For horizontal scrolling, - * use {@link ReactHorizontalScrollView}. + *

ReactScrollView only supports vertical scrolling. For horizontal scrolling, use {@link + * ReactHorizontalScrollView}. */ -public class ReactScrollView extends ScrollView implements ReactClippingViewGroup, ViewGroup.OnHierarchyChangeListener, View.OnLayoutChangeListener { +public class ReactScrollView extends ScrollView + implements ReactClippingViewGroup, + ViewGroup.OnHierarchyChangeListener, + View.OnLayoutChangeListener { private static @Nullable Field sScrollerField; private static boolean sTriedToGetScrollerField = false; @@ -98,9 +98,9 @@ public class ReactScrollView extends ScrollView implements ReactClippingViewGrou sScrollerField.setAccessible(true); } catch (NoSuchFieldException e) { Log.w( - ReactConstants.TAG, - "Failed to get mScroller field for ScrollView! " + - "This app will exhibit the bounce-back scrolling bug :("); + ReactConstants.TAG, + "Failed to get mScroller field for ScrollView! " + + "This app will exhibit the bounce-back scrolling bug :("); } } @@ -111,9 +111,9 @@ public class ReactScrollView extends ScrollView implements ReactClippingViewGrou scroller = (OverScroller) scrollerValue; } else { Log.w( - ReactConstants.TAG, - "Failed to cast mScroller field in ScrollView (probably due to OEM changes to AOSP)! " + - "This app will exhibit the bounce-back scrolling bug :("); + ReactConstants.TAG, + "Failed to cast mScroller field in ScrollView (probably due to OEM changes to AOSP)! " + + "This app will exhibit the bounce-back scrolling bug :("); scroller = null; } } catch (IllegalAccessException e) { @@ -180,8 +180,7 @@ public class ReactScrollView extends ScrollView implements ReactClippingViewGrou MeasureSpecAssertions.assertExplicitMeasureSpec(widthMeasureSpec, heightMeasureSpec); setMeasuredDimension( - MeasureSpec.getSize(widthMeasureSpec), - MeasureSpec.getSize(heightMeasureSpec)); + MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.getSize(heightMeasureSpec)); } @Override @@ -207,11 +206,11 @@ public class ReactScrollView extends ScrollView implements ReactClippingViewGrou } /** - * Since ReactScrollView handles layout changes on JS side, it does not call super.onlayout - * due to which mIsLayoutDirty flag in ScrollView remains true and prevents scrolling to child - * when requestChildFocus is called. - * Overriding this method and scrolling to child without checking any layout dirty flag. This will fix - * focus navigation issue for KeyEvents which are not handled by ScrollView, for example: KEYCODE_TAB. + * Since ReactScrollView handles layout changes on JS side, it does not call super.onlayout due to + * which mIsLayoutDirty flag in ScrollView remains true and prevents scrolling to child when + * requestChildFocus is called. Overriding this method and scrolling to child without checking any + * layout dirty flag. This will fix focus navigation issue for KeyEvents which are not handled by + * ScrollView, for example: KEYCODE_TAB. */ @Override public void requestChildFocus(View child, View focused) { @@ -247,9 +246,9 @@ public class ReactScrollView extends ScrollView implements ReactClippingViewGrou } ReactScrollViewHelper.emitScrollEvent( - this, - mOnScrollDispatchHelper.getXFlingVelocity(), - mOnScrollDispatchHelper.getYFlingVelocity()); + this, + mOnScrollDispatchHelper.getXFlingVelocity(), + mOnScrollDispatchHelper.getYFlingVelocity()); } } @@ -288,10 +287,7 @@ public class ReactScrollView extends ScrollView implements ReactClippingViewGrou if (action == MotionEvent.ACTION_UP && mDragging) { float velocityX = mVelocityHelper.getXVelocity(); float velocityY = mVelocityHelper.getYVelocity(); - ReactScrollViewHelper.emitScrollEndDragEvent( - this, - velocityX, - velocityY); + ReactScrollViewHelper.emitScrollEndDragEvent(this, velocityX, velocityY); mDragging = false; // After the touch finishes, we may need to do some scrolling afterwards either as a result // of a fling or because we need to page align the content @@ -304,8 +300,9 @@ public class ReactScrollView extends ScrollView implements ReactClippingViewGrou @Override public boolean executeKeyEvent(KeyEvent event) { int eventKeyCode = event.getKeyCode(); - if (!mScrollEnabled && (eventKeyCode == KeyEvent.KEYCODE_DPAD_UP || - eventKeyCode == KeyEvent.KEYCODE_DPAD_DOWN)) { + if (!mScrollEnabled + && (eventKeyCode == KeyEvent.KEYCODE_DPAD_UP + || eventKeyCode == KeyEvent.KEYCODE_DPAD_DOWN)) { return false; } return super.executeKeyEvent(event); @@ -349,8 +346,8 @@ public class ReactScrollView extends ScrollView implements ReactClippingViewGrou public void fling(int velocityY) { // Workaround. // On Android P if a ScrollView is inverted, we will get a wrong sign for - // velocityY (see https://issuetracker.google.com/issues/112385925). - // At the same time, mOnScrollDispatchHelper tracks the correct velocity direction. + // velocityY (see https://issuetracker.google.com/issues/112385925). + // At the same time, mOnScrollDispatchHelper tracks the correct velocity direction. // // Hence, we can use the absolute value from whatever the OS gives // us and use the sign of what mOnScrollDispatchHelper has tracked. @@ -358,7 +355,7 @@ public class ReactScrollView extends ScrollView implements ReactClippingViewGrou if (signum == 0) { signum = Math.signum(velocityY); } - final int correctedVelocityY = (int)(Math.abs(velocityY) * signum); + final int correctedVelocityY = (int) (Math.abs(velocityY) * signum); if (mPagingEnabled) { flingAndSnap(correctedVelocityY); @@ -367,24 +364,26 @@ public class ReactScrollView extends ScrollView implements ReactClippingViewGrou // We provide our own version of fling that uses a different call to the standard OverScroller // which takes into account the possibility of adding new content while the ScrollView is - // animating. Because we give essentially no max Y for the fling, the fling will continue as long - // as there is content. See #onOverScrolled() to see the second part of this change which properly + // animating. Because we give essentially no max Y for the fling, the fling will continue as + // long + // as there is content. See #onOverScrolled() to see the second part of this change which + // properly // aborts the scroller animation when we get to the bottom of the ScrollView content. int scrollWindowHeight = getHeight() - getPaddingBottom() - getPaddingTop(); mScroller.fling( - getScrollX(), // startX - getScrollY(), // startY - 0, // velocityX - correctedVelocityY, // velocityY - 0, // minX - 0, // maxX - 0, // minY - Integer.MAX_VALUE, // maxY - 0, // overX - scrollWindowHeight / 2 // overY - ); + getScrollX(), // startX + getScrollY(), // startY + 0, // velocityX + correctedVelocityY, // velocityY + 0, // minX + 0, // maxX + 0, // minY + Integer.MAX_VALUE, // maxY + 0, // overX + scrollWindowHeight / 2 // overY + ); ViewCompat.postInvalidateOnAnimation(this); @@ -444,8 +443,8 @@ public class ReactScrollView extends ScrollView implements ReactClippingViewGrou } /** - * This handles any sort of scrolling that may occur after a touch is finished. This may be - * momentum scrolling (fling) or because you have pagingEnabled on the scroll view. Because we + * This handles any sort of scrolling that may occur after a touch is finished. This may be + * momentum scrolling (fling) or because you have pagingEnabled on the scroll view. Because we * don't get any events from Android about this lifecycle, we do all our detection by creating a * runnable that checks if we scrolled in the last frame and if so assumes we are still scrolling. */ @@ -467,40 +466,39 @@ public class ReactScrollView extends ScrollView implements ReactClippingViewGrou } mActivelyScrolling = false; - mPostTouchRunnable = new Runnable() { + mPostTouchRunnable = + new Runnable() { - private boolean mSnappingToPage = false; + private boolean mSnappingToPage = false; - @Override - public void run() { - if (mActivelyScrolling) { - // We are still scrolling so we just post to check again a frame later - mActivelyScrolling = false; - ViewCompat.postOnAnimationDelayed(ReactScrollView.this, - this, - ReactScrollViewHelper.MOMENTUM_DELAY); - } else { - if (mPagingEnabled && !mSnappingToPage) { - // Only if we have pagingEnabled and we have not snapped to the page do we - // need to continue checking for the scroll. And we cause that scroll by asking for it - mSnappingToPage = true; - flingAndSnap(0); - ViewCompat.postOnAnimationDelayed(ReactScrollView.this, - this, - ReactScrollViewHelper.MOMENTUM_DELAY); - } else { - if (mSendMomentumEvents) { - ReactScrollViewHelper.emitScrollMomentumEndEvent(ReactScrollView.this); + @Override + public void run() { + if (mActivelyScrolling) { + // We are still scrolling so we just post to check again a frame later + mActivelyScrolling = false; + ViewCompat.postOnAnimationDelayed( + ReactScrollView.this, this, ReactScrollViewHelper.MOMENTUM_DELAY); + } else { + if (mPagingEnabled && !mSnappingToPage) { + // Only if we have pagingEnabled and we have not snapped to the page do we + // need to continue checking for the scroll. And we cause that scroll by asking for + // it + mSnappingToPage = true; + flingAndSnap(0); + ViewCompat.postOnAnimationDelayed( + ReactScrollView.this, this, ReactScrollViewHelper.MOMENTUM_DELAY); + } else { + if (mSendMomentumEvents) { + ReactScrollViewHelper.emitScrollMomentumEndEvent(ReactScrollView.this); + } + ReactScrollView.this.mPostTouchRunnable = null; + disableFpsListener(); + } } - ReactScrollView.this.mPostTouchRunnable = null; - disableFpsListener(); } - } - } - }; - ViewCompat.postOnAnimationDelayed(ReactScrollView.this, - mPostTouchRunnable, - ReactScrollViewHelper.MOMENTUM_DELAY); + }; + ViewCompat.postOnAnimationDelayed( + ReactScrollView.this, mPostTouchRunnable, ReactScrollViewHelper.MOMENTUM_DELAY); } private int predictFinalScrollPosition(int velocityY) { @@ -514,24 +512,24 @@ public class ReactScrollView extends ScrollView implements ReactClippingViewGrou int maximumOffset = getMaxScrollY(); int height = getHeight() - getPaddingBottom() - getPaddingTop(); scroller.fling( - getScrollX(), // startX - getScrollY(), // startY - 0, // velocityX - velocityY, // velocityY - 0, // minX - 0, // maxX - 0, // minY - maximumOffset, // maxY - 0, // overX - height/2 // overY - ); + getScrollX(), // startX + getScrollY(), // startY + 0, // velocityX + velocityY, // velocityY + 0, // minX + 0, // maxX + 0, // minY + maximumOffset, // maxY + 0, // overX + height / 2 // overY + ); return scroller.getFinalY(); } /** - * This will smooth scroll us to the nearest snap offset point - * It currently just looks at where the content is and slides to the nearest point. - * It is intended to be run after we are done scrolling, and handling any momentum scrolling. + * This will smooth scroll us to the nearest snap offset point It currently just looks at where + * the content is and slides to the nearest point. It is intended to be run after we are done + * scrolling, and handling any momentum scrolling. */ private void smoothScrollAndSnap(int velocity) { double interval = (double) getSnapInterval(); @@ -544,29 +542,30 @@ public class ReactScrollView extends ScrollView implements ReactClippingViewGrou int targetPage = (int) Math.round(targetOffset / interval); if (velocity > 0 && nextPage == previousPage) { - nextPage ++; + nextPage++; } else if (velocity < 0 && previousPage == nextPage) { - previousPage --; + previousPage--; } if ( - // if scrolling towards next page - velocity > 0 && - // and the middle of the page hasn't been crossed already - currentPage < nextPage && - // and it would have been crossed after flinging - targetPage > previousPage - ) { + // if scrolling towards next page + velocity > 0 + && + // and the middle of the page hasn't been crossed already + currentPage < nextPage + && + // and it would have been crossed after flinging + targetPage > previousPage) { currentPage = nextPage; - } - else if ( - // if scrolling towards previous page - velocity < 0 && - // and the middle of the page hasn't been crossed already - currentPage > previousPage && - // and it would have been crossed after flinging - targetPage < nextPage - ) { + } else if ( + // if scrolling towards previous page + velocity < 0 + && + // and the middle of the page hasn't been crossed already + currentPage > previousPage + && + // and it would have been crossed after flinging + targetPage < nextPage) { currentPage = previousPage; } @@ -601,7 +600,7 @@ public class ReactScrollView extends ScrollView implements ReactClippingViewGrou firstOffset = mSnapOffsets.get(0); lastOffset = mSnapOffsets.get(mSnapOffsets.size() - 1); - for (int i = 0; i < mSnapOffsets.size(); i ++) { + for (int i = 0; i < mSnapOffsets.size(); i++) { int offset = mSnapOffsets.get(i); if (offset <= targetOffset) { @@ -624,9 +623,8 @@ public class ReactScrollView extends ScrollView implements ReactClippingViewGrou } // Calculate the nearest offset - int nearestOffset = targetOffset - smallerOffset < largerOffset - targetOffset - ? smallerOffset - : largerOffset; + int nearestOffset = + targetOffset - smallerOffset < largerOffset - targetOffset ? smallerOffset : largerOffset; // if scrolling after the last snap offset and snapping to the // end of the list is disabled, then we allow free scrolling @@ -669,22 +667,22 @@ public class ReactScrollView extends ScrollView implements ReactClippingViewGrou mActivelyScrolling = true; mScroller.fling( - getScrollX(), // startX - getScrollY(), // startY - // velocity = 0 doesn't work with fling() so we pretend there's a reasonable - // initial velocity going on when a touch is released without any movement - 0, // velocityX - velocityY != 0 ? velocityY : targetOffset - getScrollY(), // velocityY - 0, // minX - 0, // maxX - // setting both minY and maxY to the same value will guarantee that we scroll to it - // but using the standard fling-style easing rather than smoothScrollTo's 250ms animation - targetOffset, // minY - targetOffset, // maxY - 0, // overX - // we only want to allow overscrolling if the final offset is at the very edge of the view - (targetOffset == 0 || targetOffset == maximumOffset) ? height / 2 : 0 // overY - ); + getScrollX(), // startX + getScrollY(), // startY + // velocity = 0 doesn't work with fling() so we pretend there's a reasonable + // initial velocity going on when a touch is released without any movement + 0, // velocityX + velocityY != 0 ? velocityY : targetOffset - getScrollY(), // velocityY + 0, // minX + 0, // maxX + // setting both minY and maxY to the same value will guarantee that we scroll to it + // but using the standard fling-style easing rather than smoothScrollTo's 250ms animation + targetOffset, // minY + targetOffset, // maxY + 0, // overX + // we only want to allow overscrolling if the final offset is at the very edge of the view + (targetOffset == 0 || targetOffset == maximumOffset) ? height / 2 : 0 // overY + ); postInvalidateOnAnimation(); } else { @@ -711,7 +709,8 @@ public class ReactScrollView extends ScrollView implements ReactClippingViewGrou if (mScroller != null && mContentView != null) { // FB SCROLLVIEW CHANGE - // This is part two of the reimplementation of fling to fix the bounce-back bug. See #fling() for + // This is part two of the reimplementation of fling to fix the bounce-back bug. See #fling() + // for // more information. if (!mScroller.isFinished() && mScroller.getCurrY() != mScroller.getFinalY()) { @@ -746,7 +745,16 @@ public class ReactScrollView extends ScrollView implements ReactClippingViewGrou * position is larger than the ScrollView's max scroll position after the content shrinks. */ @Override - public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { + public void onLayoutChange( + View v, + int left, + int top, + int right, + int bottom, + int oldLeft, + int oldTop, + int oldRight, + int oldBottom) { if (mContentView == null) { return; } @@ -782,5 +790,4 @@ public class ReactScrollView extends ScrollView implements ReactClippingViewGrou public void setBorderStyle(@Nullable String style) { mReactBackgroundManager.setBorderStyle(style); } - } diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactScrollViewCommandHelper.java b/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactScrollViewCommandHelper.java index fe3fda2afd7..f7a579e800e 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactScrollViewCommandHelper.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactScrollViewCommandHelper.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.scroll; import com.facebook.infer.annotation.Assertions; @@ -15,8 +14,8 @@ import java.util.Map; import javax.annotation.Nullable; /** - * Helper for view managers to handle commands like 'scrollTo'. - * Shared by {@link ReactScrollViewManager} and {@link ReactHorizontalScrollViewManager}. + * Helper for view managers to handle commands like 'scrollTo'. Shared by {@link + * ReactScrollViewManager} and {@link ReactHorizontalScrollViewManager}. */ public class ReactScrollViewCommandHelper { @@ -26,7 +25,9 @@ public class ReactScrollViewCommandHelper { public interface ScrollCommandHandler { void scrollTo(T scrollView, ScrollToCommandData data); + void scrollToEnd(T scrollView, ScrollToEndCommandData data); + void flashScrollIndicators(T scrollView); } @@ -51,7 +52,7 @@ public class ReactScrollViewCommandHelper { } } - public static Map getCommandsMap() { + public static Map getCommandsMap() { return MapBuilder.of( "scrollTo", COMMAND_SCROLL_TO, @@ -70,23 +71,25 @@ public class ReactScrollViewCommandHelper { Assertions.assertNotNull(scrollView); Assertions.assertNotNull(args); switch (commandType) { - case COMMAND_SCROLL_TO: { - scrollTo(viewManager, scrollView, args); - return; - } - case COMMAND_SCROLL_TO_END: { - scrollToEnd(viewManager, scrollView, args); - return; - } + case COMMAND_SCROLL_TO: + { + scrollTo(viewManager, scrollView, args); + return; + } + case COMMAND_SCROLL_TO_END: + { + scrollToEnd(viewManager, scrollView, args); + return; + } case COMMAND_FLASH_SCROLL_INDICATORS: viewManager.flashScrollIndicators(scrollView); return; default: - throw new IllegalArgumentException(String.format( - "Unsupported command %d received by %s.", - commandType, - viewManager.getClass().getSimpleName())); + throw new IllegalArgumentException( + String.format( + "Unsupported command %d received by %s.", + commandType, viewManager.getClass().getSimpleName())); } } @@ -99,29 +102,30 @@ public class ReactScrollViewCommandHelper { Assertions.assertNotNull(scrollView); Assertions.assertNotNull(args); switch (commandType) { - case "scrollTo": { - scrollTo(viewManager, scrollView, args); - return; - } - case "scrollToEnd": { - scrollToEnd(viewManager, scrollView, args); - return; - } + case "scrollTo": + { + scrollTo(viewManager, scrollView, args); + return; + } + case "scrollToEnd": + { + scrollToEnd(viewManager, scrollView, args); + return; + } case "flashScrollIndicators": viewManager.flashScrollIndicators(scrollView); return; default: - throw new IllegalArgumentException(String.format( - "Unsupported command %s received by %s.", - commandType, - viewManager.getClass().getSimpleName())); + throw new IllegalArgumentException( + String.format( + "Unsupported command %s received by %s.", + commandType, viewManager.getClass().getSimpleName())); } } private static void scrollTo( - ScrollCommandHandler viewManager, - T scrollView, @Nullable ReadableArray args) { + ScrollCommandHandler viewManager, T scrollView, @Nullable ReadableArray args) { int destX = Math.round(PixelUtil.toPixelFromDIP(args.getDouble(0))); int destY = Math.round(PixelUtil.toPixelFromDIP(args.getDouble(1))); boolean animated = args.getBoolean(2); @@ -129,8 +133,7 @@ public class ReactScrollViewCommandHelper { } private static void scrollToEnd( - ScrollCommandHandler viewManager, - T scrollView, @Nullable ReadableArray args) { + ScrollCommandHandler viewManager, T scrollView, @Nullable ReadableArray args) { boolean animated = args.getBoolean(0); viewManager.scrollToEnd(scrollView, new ScrollToEndCommandData(animated)); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactScrollViewHelper.java b/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactScrollViewHelper.java index 1e8cdae053f..c3d3e8721ee 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactScrollViewHelper.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactScrollViewHelper.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.scroll; import android.view.View; @@ -12,11 +11,8 @@ import android.view.ViewGroup; import com.facebook.react.bridge.JSApplicationIllegalArgumentException; import com.facebook.react.bridge.ReactContext; import com.facebook.react.uimanager.UIManagerModule; -import com.facebook.react.uimanager.events.EventDispatcher; -/** - * Helper class that deals with emitting Scroll Events. - */ +/** Helper class that deals with emitting Scroll Events. */ public class ReactScrollViewHelper { public static final long MOMENTUM_DELAY = 20; @@ -24,9 +20,7 @@ public class ReactScrollViewHelper { public static final String AUTO = "auto"; public static final String OVER_SCROLL_NEVER = "never"; - /** - * Shared by {@link ReactScrollView} and {@link ReactHorizontalScrollView}. - */ + /** Shared by {@link ReactScrollView} and {@link ReactHorizontalScrollView}. */ public static void emitScrollEvent(ViewGroup scrollView, float xVelocity, float yVelocity) { emitScrollEvent(scrollView, ScrollEventType.SCROLL, xVelocity, yVelocity); } @@ -36,16 +30,12 @@ public class ReactScrollViewHelper { } public static void emitScrollEndDragEvent( - ViewGroup scrollView, - float xVelocity, - float yVelocity) { + ViewGroup scrollView, float xVelocity, float yVelocity) { emitScrollEvent(scrollView, ScrollEventType.END_DRAG, xVelocity, yVelocity); } public static void emitScrollMomentumBeginEvent( - ViewGroup scrollView, - int xVelocity, - int yVelocity) { + ViewGroup scrollView, int xVelocity, int yVelocity) { emitScrollEvent(scrollView, ScrollEventType.MOMENTUM_BEGIN, xVelocity, yVelocity); } @@ -58,10 +48,7 @@ public class ReactScrollViewHelper { } private static void emitScrollEvent( - ViewGroup scrollView, - ScrollEventType scrollEventType, - float xVelocity, - float yVelocity) { + ViewGroup scrollView, ScrollEventType scrollEventType, float xVelocity, float yVelocity) { View contentView = scrollView.getChildAt(0); if (contentView == null) { @@ -69,18 +56,21 @@ public class ReactScrollViewHelper { } ReactContext reactContext = (ReactContext) scrollView.getContext(); - reactContext.getNativeModule(UIManagerModule.class).getEventDispatcher().dispatchEvent( - ScrollEvent.obtain( - scrollView.getId(), - scrollEventType, - scrollView.getScrollX(), - scrollView.getScrollY(), - xVelocity, - yVelocity, - contentView.getWidth(), - contentView.getHeight(), - scrollView.getWidth(), - scrollView.getHeight())); + reactContext + .getNativeModule(UIManagerModule.class) + .getEventDispatcher() + .dispatchEvent( + ScrollEvent.obtain( + scrollView.getId(), + scrollEventType, + scrollView.getScrollX(), + scrollView.getScrollY(), + xVelocity, + yVelocity, + contentView.getWidth(), + contentView.getHeight(), + scrollView.getWidth(), + scrollView.getHeight())); } public static int parseOverScrollMode(String jsOverScrollMode) { diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactScrollViewManager.java b/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactScrollViewManager.java index 04e1585d8a1..c19262a1847 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactScrollViewManager.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactScrollViewManager.java @@ -1,16 +1,14 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.scroll; import android.graphics.Color; -import androidx.core.view.ViewCompat; import android.util.DisplayMetrics; - +import androidx.core.view.ViewCompat; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.common.MapBuilder; import com.facebook.react.module.annotations.ReactModule; @@ -24,7 +22,6 @@ import com.facebook.react.uimanager.ViewProps; import com.facebook.react.uimanager.annotations.ReactProp; import com.facebook.react.uimanager.annotations.ReactPropGroup; import com.facebook.yoga.YogaConstants; - import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -33,18 +30,17 @@ import javax.annotation.Nullable; /** * View manager for {@link ReactScrollView} components. * - *

Note that {@link ReactScrollView} and {@link ReactHorizontalScrollView} are exposed to JS - * as a single ScrollView component, configured via the {@code horizontal} boolean property. + *

Note that {@link ReactScrollView} and {@link ReactHorizontalScrollView} are exposed to JS as a + * single ScrollView component, configured via the {@code horizontal} boolean property. */ @ReactModule(name = ReactScrollViewManager.REACT_CLASS) -public class ReactScrollViewManager - extends ViewGroupManager +public class ReactScrollViewManager extends ViewGroupManager implements ReactScrollViewCommandHelper.ScrollCommandHandler { public static final String REACT_CLASS = "RCTScrollView"; private static final int[] SPACING_TYPES = { - Spacing.ALL, Spacing.LEFT, Spacing.RIGHT, Spacing.TOP, Spacing.BOTTOM, + Spacing.ALL, Spacing.LEFT, Spacing.RIGHT, Spacing.TOP, Spacing.BOTTOM, }; private @Nullable FpsListener mFpsListener = null; @@ -119,9 +115,9 @@ public class ReactScrollViewManager } /** - * Computing momentum events is potentially expensive since we post a runnable on the UI thread - * to see when it is done. We only do that if {@param sendMomentumEvents} is set to true. This - * is handled automatically in js by checking if there is a listener on the momentum events. + * Computing momentum events is potentially expensive since we post a runnable on the UI thread to + * see when it is done. We only do that if {@param sendMomentumEvents} is set to true. This is + * handled automatically in js by checking if there is a listener on the momentum events. * * @param view * @param sendMomentumEvents @@ -151,6 +147,7 @@ public class ReactScrollViewManager /** * When set, fills the rest of the scrollview with a color to avoid setting a background and * creating unnecessary overdraw. + * * @param view * @param color */ @@ -159,9 +156,7 @@ public class ReactScrollViewManager view.setEndFillColor(color); } - /** - * Controls overScroll behaviour - */ + /** Controls overScroll behaviour */ @ReactProp(name = "overScrollMode") public void setOverScrollMode(ReactScrollView view, String value) { view.setOverScrollMode(ReactScrollViewHelper.parseOverScrollMode(value)); @@ -179,17 +174,13 @@ public class ReactScrollViewManager @Override public void receiveCommand( - ReactScrollView scrollView, - int commandId, - @Nullable ReadableArray args) { + ReactScrollView scrollView, int commandId, @Nullable ReadableArray args) { ReactScrollViewCommandHelper.receiveCommand(this, scrollView, commandId, args); } @Override public void receiveCommand( - ReactScrollView scrollView, - String commandId, - @Nullable ReadableArray args) { + ReactScrollView scrollView, String commandId, @Nullable ReadableArray args) { ReactScrollViewCommandHelper.receiveCommand(this, scrollView, commandId, args); } @@ -207,13 +198,16 @@ public class ReactScrollViewManager scrollView.scrollTo(data.mDestX, data.mDestY); } } - @ReactPropGroup(names = { - ViewProps.BORDER_RADIUS, - ViewProps.BORDER_TOP_LEFT_RADIUS, - ViewProps.BORDER_TOP_RIGHT_RADIUS, - ViewProps.BORDER_BOTTOM_RIGHT_RADIUS, - ViewProps.BORDER_BOTTOM_LEFT_RADIUS - }, defaultFloat = YogaConstants.UNDEFINED) + + @ReactPropGroup( + names = { + ViewProps.BORDER_RADIUS, + ViewProps.BORDER_TOP_LEFT_RADIUS, + ViewProps.BORDER_TOP_RIGHT_RADIUS, + ViewProps.BORDER_BOTTOM_RIGHT_RADIUS, + ViewProps.BORDER_BOTTOM_LEFT_RADIUS + }, + defaultFloat = YogaConstants.UNDEFINED) public void setBorderRadius(ReactScrollView view, int index, float borderRadius) { if (!YogaConstants.isUndefined(borderRadius)) { borderRadius = PixelUtil.toPixelFromDIP(borderRadius); @@ -231,13 +225,15 @@ public class ReactScrollViewManager view.setBorderStyle(borderStyle); } - @ReactPropGroup(names = { - ViewProps.BORDER_WIDTH, - ViewProps.BORDER_LEFT_WIDTH, - ViewProps.BORDER_RIGHT_WIDTH, - ViewProps.BORDER_TOP_WIDTH, - ViewProps.BORDER_BOTTOM_WIDTH, - }, defaultFloat = YogaConstants.UNDEFINED) + @ReactPropGroup( + names = { + ViewProps.BORDER_WIDTH, + ViewProps.BORDER_LEFT_WIDTH, + ViewProps.BORDER_RIGHT_WIDTH, + ViewProps.BORDER_TOP_WIDTH, + ViewProps.BORDER_BOTTOM_WIDTH, + }, + defaultFloat = YogaConstants.UNDEFINED) public void setBorderWidth(ReactScrollView view, int index, float width) { if (!YogaConstants.isUndefined(width)) { width = PixelUtil.toPixelFromDIP(width); @@ -245,12 +241,17 @@ public class ReactScrollViewManager view.setBorderWidth(SPACING_TYPES[index], width); } - @ReactPropGroup(names = { - "borderColor", "borderLeftColor", "borderRightColor", "borderTopColor", "borderBottomColor" - }, customType = "Color") + @ReactPropGroup( + names = { + "borderColor", + "borderLeftColor", + "borderRightColor", + "borderTopColor", + "borderBottomColor" + }, + customType = "Color") public void setBorderColor(ReactScrollView view, int index, Integer color) { - float rgbComponent = - color == null ? YogaConstants.UNDEFINED : (float) (color & 0x00FFFFFF); + float rgbComponent = color == null ? YogaConstants.UNDEFINED : (float) (color & 0x00FFFFFF); float alphaComponent = color == null ? YogaConstants.UNDEFINED : (float) (color >>> 24); view.setBorderColor(SPACING_TYPES[index], rgbComponent, alphaComponent); } @@ -262,11 +263,9 @@ public class ReactScrollViewManager @Override public void scrollToEnd( - ReactScrollView scrollView, - ReactScrollViewCommandHelper.ScrollToEndCommandData data) { + ReactScrollView scrollView, ReactScrollViewCommandHelper.ScrollToEndCommandData data) { // ScrollView always has one child - the scrollable area - int bottom = - scrollView.getChildAt(0).getHeight() + scrollView.getPaddingBottom(); + int bottom = scrollView.getChildAt(0).getHeight() + scrollView.getPaddingBottom(); if (data.mAnimated) { scrollView.smoothScrollTo(scrollView.getScrollX(), bottom); } else { @@ -286,11 +285,21 @@ public class ReactScrollViewManager public static Map createExportedCustomDirectEventTypeConstants() { return MapBuilder.builder() - .put(ScrollEventType.getJSEventName(ScrollEventType.SCROLL), MapBuilder.of("registrationName", "onScroll")) - .put(ScrollEventType.getJSEventName(ScrollEventType.BEGIN_DRAG), MapBuilder.of("registrationName", "onScrollBeginDrag")) - .put(ScrollEventType.getJSEventName(ScrollEventType.END_DRAG), MapBuilder.of("registrationName", "onScrollEndDrag")) - .put(ScrollEventType.getJSEventName(ScrollEventType.MOMENTUM_BEGIN), MapBuilder.of("registrationName", "onMomentumScrollBegin")) - .put(ScrollEventType.getJSEventName(ScrollEventType.MOMENTUM_END), MapBuilder.of("registrationName", "onMomentumScrollEnd")) + .put( + ScrollEventType.getJSEventName(ScrollEventType.SCROLL), + MapBuilder.of("registrationName", "onScroll")) + .put( + ScrollEventType.getJSEventName(ScrollEventType.BEGIN_DRAG), + MapBuilder.of("registrationName", "onScrollBeginDrag")) + .put( + ScrollEventType.getJSEventName(ScrollEventType.END_DRAG), + MapBuilder.of("registrationName", "onScrollEndDrag")) + .put( + ScrollEventType.getJSEventName(ScrollEventType.MOMENTUM_BEGIN), + MapBuilder.of("registrationName", "onMomentumScrollBegin")) + .put( + ScrollEventType.getJSEventName(ScrollEventType.MOMENTUM_END), + MapBuilder.of("registrationName", "onMomentumScrollEnd")) .build(); } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ScrollEvent.java b/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ScrollEvent.java index b05d1458127..9db4cb20ba3 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ScrollEvent.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ScrollEvent.java @@ -1,28 +1,21 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.scroll; -import javax.annotation.Nullable; - -import java.lang.Override; - import androidx.core.util.Pools; - import com.facebook.infer.annotation.Assertions; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.WritableMap; import com.facebook.react.uimanager.PixelUtil; import com.facebook.react.uimanager.events.Event; import com.facebook.react.uimanager.events.RCTEventEmitter; +import javax.annotation.Nullable; -/** - * A event dispatched from a ScrollView scrolling. - */ +/** A event dispatched from a ScrollView scrolling. */ public class ScrollEvent extends Event { private static final Pools.SynchronizedPool EVENTS_POOL = @@ -72,8 +65,7 @@ public class ScrollEvent extends Event { EVENTS_POOL.release(this); } - private ScrollEvent() { - } + private ScrollEvent() {} private void init( int viewTag, diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ScrollEventType.java b/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ScrollEventType.java index d51de786174..35bbe909af6 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ScrollEventType.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ScrollEventType.java @@ -1,15 +1,12 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.scroll; -/** - * Scroll event types that JS module RCTEventEmitter can understand - */ +/** Scroll event types that JS module RCTEventEmitter can understand */ public enum ScrollEventType { BEGIN_DRAG, END_DRAG, diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/scroll/VelocityHelper.java b/ReactAndroid/src/main/java/com/facebook/react/views/scroll/VelocityHelper.java index 8260fa675ce..010f3a9d572 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/scroll/VelocityHelper.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/scroll/VelocityHelper.java @@ -1,21 +1,18 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.scroll; -import javax.annotation.Nullable; - import android.view.MotionEvent; import android.view.VelocityTracker; +import javax.annotation.Nullable; /** - * This Class helps to calculate the velocity for all ScrollView. The x and y velocity - * will later on send to ReactScrollViewHelper for further use. - * + * This Class helps to calculate the velocity for all ScrollView. The x and y velocity will later on + * send to ReactScrollViewHelper for further use. */ public class VelocityHelper { @@ -24,9 +21,9 @@ public class VelocityHelper { private float mYVelocity; /** - * Call from a ScrollView in onTouchEvent. - * Calculating the velocity for END_DRAG movement and send them back to react ScrollResponder.js - * */ + * Call from a ScrollView in onTouchEvent. Calculating the velocity for END_DRAG movement and send + * them back to react ScrollResponder.js + */ public void calculateVelocity(MotionEvent ev) { int action = ev.getAction() & MotionEvent.ACTION_MASK; if (mVelocityTracker == null) { @@ -36,18 +33,19 @@ public class VelocityHelper { switch (action) { case MotionEvent.ACTION_UP: - case MotionEvent.ACTION_CANCEL: { - // Calculate velocity on END_DRAG - mVelocityTracker.computeCurrentVelocity(1); // points/millisecond - mXVelocity = mVelocityTracker.getXVelocity(); - mYVelocity = mVelocityTracker.getYVelocity(); + case MotionEvent.ACTION_CANCEL: + { + // Calculate velocity on END_DRAG + mVelocityTracker.computeCurrentVelocity(1); // points/millisecond + mXVelocity = mVelocityTracker.getXVelocity(); + mYVelocity = mVelocityTracker.getYVelocity(); - if (mVelocityTracker != null) { - mVelocityTracker.recycle(); - mVelocityTracker = null; + if (mVelocityTracker != null) { + mVelocityTracker.recycle(); + mVelocityTracker = null; + } + break; } - break; - } } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/slider/ReactSlider.java b/ReactAndroid/src/main/java/com/facebook/react/views/slider/ReactSlider.java index b1e1db94631..7b0bc28e90f 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/slider/ReactSlider.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/slider/ReactSlider.java @@ -8,8 +8,8 @@ package com.facebook.react.views.slider; import android.content.Context; import android.os.Build; -import androidx.appcompat.widget.AppCompatSeekBar; import android.util.AttributeSet; +import androidx.appcompat.widget.AppCompatSeekBar; import javax.annotation.Nullable; /** diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/slider/ReactSliderEvent.java b/ReactAndroid/src/main/java/com/facebook/react/views/slider/ReactSliderEvent.java index 504da715584..63a68dc4e63 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/slider/ReactSliderEvent.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/slider/ReactSliderEvent.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.slider; import com.facebook.react.bridge.Arguments; @@ -12,9 +11,7 @@ import com.facebook.react.bridge.WritableMap; import com.facebook.react.uimanager.events.Event; import com.facebook.react.uimanager.events.RCTEventEmitter; -/** - * Event emitted by a ReactSliderManager when user changes slider position. - */ +/** Event emitted by a ReactSliderManager when user changes slider position. */ public class ReactSliderEvent extends Event { public static final String EVENT_NAME = "topChange"; @@ -36,7 +33,6 @@ public class ReactSliderEvent extends Event { return mFromUser; } - @Override public String getEventName() { return EVENT_NAME; @@ -46,6 +42,7 @@ public class ReactSliderEvent extends Event { public short getCoalescingKey() { return 0; } + @Override public void dispatch(RCTEventEmitter rctEventEmitter) { rctEventEmitter.receiveEvent(getViewTag(), getEventName(), serializeEventData()); diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/slider/ReactSliderManager.java b/ReactAndroid/src/main/java/com/facebook/react/views/slider/ReactSliderManager.java index fc2dfecf971..25176ef1dee 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/slider/ReactSliderManager.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/slider/ReactSliderManager.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.slider; import android.content.Context; @@ -18,13 +17,11 @@ import com.facebook.react.bridge.ReactContext; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.common.MapBuilder; import com.facebook.react.uimanager.LayoutShadowNode; -import com.facebook.react.uimanager.ReactShadowNodeImpl; import com.facebook.react.uimanager.SimpleViewManager; import com.facebook.react.uimanager.ThemedReactContext; import com.facebook.react.uimanager.UIManagerModule; import com.facebook.react.uimanager.ViewProps; import com.facebook.react.uimanager.annotations.ReactProp; -import com.facebook.react.uimanager.events.EventDispatcher; import com.facebook.yoga.YogaMeasureFunction; import com.facebook.yoga.YogaMeasureMode; import com.facebook.yoga.YogaMeasureOutput; @@ -34,7 +31,7 @@ import java.util.Map; /** * Manages instances of {@code ReactSlider}. * - * Note that the slider is _not_ a controlled component. + *

Note that the slider is _not_ a controlled component. */ public class ReactSliderManager extends SimpleViewManager { @@ -42,8 +39,7 @@ public class ReactSliderManager extends SimpleViewManager { public static final String REACT_CLASS = "RCTSlider"; - static class ReactSliderShadowNode extends LayoutShadowNode implements - YogaMeasureFunction { + static class ReactSliderShadowNode extends LayoutShadowNode implements YogaMeasureFunction { private int mWidth; private int mHeight; @@ -66,9 +62,9 @@ public class ReactSliderManager extends SimpleViewManager { YogaMeasureMode heightMode) { if (!mMeasured) { SeekBar reactSlider = new ReactSlider(getThemedContext(), null, STYLE); - final int spec = View.MeasureSpec.makeMeasureSpec( - ViewGroup.LayoutParams.WRAP_CONTENT, - View.MeasureSpec.UNSPECIFIED); + final int spec = + View.MeasureSpec.makeMeasureSpec( + ViewGroup.LayoutParams.WRAP_CONTENT, View.MeasureSpec.UNSPECIFIED); reactSlider.measure(spec, spec); mWidth = reactSlider.getMeasuredWidth(); mHeight = reactSlider.getMeasuredHeight(); @@ -84,24 +80,27 @@ public class ReactSliderManager extends SimpleViewManager { @Override public void onProgressChanged(SeekBar seekbar, int progress, boolean fromUser) { ReactContext reactContext = (ReactContext) seekbar.getContext(); - reactContext.getNativeModule(UIManagerModule.class).getEventDispatcher().dispatchEvent( - new ReactSliderEvent( - seekbar.getId(), - ((ReactSlider) seekbar).toRealProgress(progress), - fromUser)); + reactContext + .getNativeModule(UIManagerModule.class) + .getEventDispatcher() + .dispatchEvent( + new ReactSliderEvent( + seekbar.getId(), ((ReactSlider) seekbar).toRealProgress(progress), fromUser)); } @Override - public void onStartTrackingTouch(SeekBar seekbar) { - } + public void onStartTrackingTouch(SeekBar seekbar) {} @Override public void onStopTrackingTouch(SeekBar seekbar) { ReactContext reactContext = (ReactContext) seekbar.getContext(); - reactContext.getNativeModule(UIManagerModule.class).getEventDispatcher().dispatchEvent( - new ReactSlidingCompleteEvent( - seekbar.getId(), - ((ReactSlider) seekbar).toRealProgress(seekbar.getProgress()))); + reactContext + .getNativeModule(UIManagerModule.class) + .getEventDispatcher() + .dispatchEvent( + new ReactSlidingCompleteEvent( + seekbar.getId(), + ((ReactSlider) seekbar).toRealProgress(seekbar.getProgress()))); } }; @@ -197,20 +196,20 @@ public class ReactSliderManager extends SimpleViewManager { @Override public long measure( - Context context, - ReadableMap localData, - ReadableMap props, - ReadableMap state, - float width, - YogaMeasureMode widthMode, - float height, - YogaMeasureMode heightMode) { - SeekBar reactSlider = new ReactSlider(context, null, STYLE); - final int spec = View.MeasureSpec.makeMeasureSpec( - ViewGroup.LayoutParams.WRAP_CONTENT, - View.MeasureSpec.UNSPECIFIED); - reactSlider.measure(spec, spec); + Context context, + ReadableMap localData, + ReadableMap props, + ReadableMap state, + float width, + YogaMeasureMode widthMode, + float height, + YogaMeasureMode heightMode) { + SeekBar reactSlider = new ReactSlider(context, null, STYLE); + final int spec = + View.MeasureSpec.makeMeasureSpec( + ViewGroup.LayoutParams.WRAP_CONTENT, View.MeasureSpec.UNSPECIFIED); + reactSlider.measure(spec, spec); - return YogaMeasureOutput.make(reactSlider.getMeasuredWidth(), reactSlider.getMeasuredHeight()); - } + return YogaMeasureOutput.make(reactSlider.getMeasuredWidth(), reactSlider.getMeasuredHeight()); } +} diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/slider/ReactSlidingCompleteEvent.java b/ReactAndroid/src/main/java/com/facebook/react/views/slider/ReactSlidingCompleteEvent.java index 5534b3b55f4..69303c0740d 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/slider/ReactSlidingCompleteEvent.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/slider/ReactSlidingCompleteEvent.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.slider; import com.facebook.react.bridge.Arguments; @@ -12,9 +11,7 @@ import com.facebook.react.bridge.WritableMap; import com.facebook.react.uimanager.events.Event; import com.facebook.react.uimanager.events.RCTEventEmitter; -/** - * Event emitted when the user finishes dragging the slider. - */ +/** Event emitted when the user finishes dragging the slider. */ public class ReactSlidingCompleteEvent extends Event { public static final String EVENT_NAME = "topSlidingComplete"; @@ -56,5 +53,4 @@ public class ReactSlidingCompleteEvent extends Event eventData.putDouble("value", getValue()); return eventData; } - } diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/swiperefresh/ReactSwipeRefreshLayout.java b/ReactAndroid/src/main/java/com/facebook/react/views/swiperefresh/ReactSwipeRefreshLayout.java index 0d717df1464..55435526c67 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/swiperefresh/ReactSwipeRefreshLayout.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/swiperefresh/ReactSwipeRefreshLayout.java @@ -1,23 +1,19 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.swiperefresh; -import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import android.view.MotionEvent; import android.view.ViewConfiguration; - +import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import com.facebook.react.bridge.ReactContext; import com.facebook.react.uimanager.PixelUtil; import com.facebook.react.uimanager.events.NativeGestureUtil; -/** - * Basic extension of {@link SwipeRefreshLayout} with ReactNative-specific functionality. - */ +/** Basic extension of {@link SwipeRefreshLayout} with ReactNative-specific functionality. */ public class ReactSwipeRefreshLayout extends SwipeRefreshLayout { private static final float DEFAULT_CIRCLE_TARGET = 64; @@ -104,9 +100,9 @@ public class ReactSwipeRefreshLayout extends SwipeRefreshLayout { /** * {@link SwipeRefreshLayout} completely bypasses ViewGroup's "disallowIntercept" by overriding - * {@link ViewGroup#onInterceptTouchEvent} and never calling super.onInterceptTouchEvent(). - * This means that horizontal scrolls will always be intercepted, even though they shouldn't, so - * we have to check for that manually here. + * {@link ViewGroup#onInterceptTouchEvent} and never calling super.onInterceptTouchEvent(). This + * means that horizontal scrolls will always be intercepted, even though they shouldn't, so we + * have to check for that manually here. */ private boolean shouldInterceptTouchEvent(MotionEvent ev) { switch (ev.getAction()) { diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/swiperefresh/RefreshEvent.java b/ReactAndroid/src/main/java/com/facebook/react/views/swiperefresh/RefreshEvent.java index dc3cfb9c205..3960f4f9733 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/swiperefresh/RefreshEvent.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/swiperefresh/RefreshEvent.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.swiperefresh; import com.facebook.react.uimanager.events.Event; @@ -12,17 +11,17 @@ import com.facebook.react.uimanager.events.RCTEventEmitter; public class RefreshEvent extends Event { - protected RefreshEvent(int viewTag) { - super(viewTag); - } + protected RefreshEvent(int viewTag) { + super(viewTag); + } - @Override - public String getEventName() { - return "topRefresh"; - } + @Override + public String getEventName() { + return "topRefresh"; + } - @Override - public void dispatch(RCTEventEmitter rctEventEmitter) { - rctEventEmitter.receiveEvent(getViewTag(), getEventName(), null); - } + @Override + public void dispatch(RCTEventEmitter rctEventEmitter) { + rctEventEmitter.receiveEvent(getViewTag(), getEventName(), null); + } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/swiperefresh/SwipeRefreshLayoutManager.java b/ReactAndroid/src/main/java/com/facebook/react/views/swiperefresh/SwipeRefreshLayoutManager.java index be8d7959d59..2e3742eecc3 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/swiperefresh/SwipeRefreshLayoutManager.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/swiperefresh/SwipeRefreshLayoutManager.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.swiperefresh; import static com.facebook.react.views.swiperefresh.SwipeRefreshLayoutManager.REACT_CLASS; @@ -22,7 +21,6 @@ import com.facebook.react.uimanager.UIManagerModule; import com.facebook.react.uimanager.ViewGroupManager; import com.facebook.react.uimanager.ViewProps; import com.facebook.react.uimanager.annotations.ReactProp; -import com.facebook.react.uimanager.events.EventDispatcher; import java.util.Map; import javax.annotation.Nullable; @@ -84,7 +82,8 @@ public class SwipeRefreshLayoutManager extends ViewGroupManagerThis source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.switchview; import android.content.Context; diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/switchview/ReactSwitchEvent.java b/ReactAndroid/src/main/java/com/facebook/react/views/switchview/ReactSwitchEvent.java index 019a7b7291d..22bdc1a32ad 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/switchview/ReactSwitchEvent.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/switchview/ReactSwitchEvent.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.switchview; import com.facebook.react.bridge.Arguments; @@ -12,44 +11,42 @@ import com.facebook.react.bridge.WritableMap; import com.facebook.react.uimanager.events.Event; import com.facebook.react.uimanager.events.RCTEventEmitter; -/** - * Event emitted by a ReactSwitchManager once a switch is fully switched on/off - */ +/** Event emitted by a ReactSwitchManager once a switch is fully switched on/off */ /*package*/ class ReactSwitchEvent extends Event { - public static final String EVENT_NAME = "topChange"; + public static final String EVENT_NAME = "topChange"; - private final boolean mIsChecked; + private final boolean mIsChecked; - public ReactSwitchEvent(int viewId, boolean isChecked) { - super(viewId); - mIsChecked = isChecked; - } + public ReactSwitchEvent(int viewId, boolean isChecked) { + super(viewId); + mIsChecked = isChecked; + } - public boolean getIsChecked() { - return mIsChecked; - } + public boolean getIsChecked() { + return mIsChecked; + } - @Override - public String getEventName() { - return EVENT_NAME; - } + @Override + public String getEventName() { + return EVENT_NAME; + } - @Override - public short getCoalescingKey() { - // All switch events for a given view can be coalesced. - return 0; - } + @Override + public short getCoalescingKey() { + // All switch events for a given view can be coalesced. + return 0; + } - @Override - public void dispatch(RCTEventEmitter rctEventEmitter) { - rctEventEmitter.receiveEvent(getViewTag(), getEventName(), serializeEventData()); - } + @Override + public void dispatch(RCTEventEmitter rctEventEmitter) { + rctEventEmitter.receiveEvent(getViewTag(), getEventName(), serializeEventData()); + } - private WritableMap serializeEventData() { - WritableMap eventData = Arguments.createMap(); - eventData.putInt("target", getViewTag()); - eventData.putBoolean("value", getIsChecked()); - return eventData; - } + private WritableMap serializeEventData() { + WritableMap eventData = Arguments.createMap(); + eventData.putInt("target", getViewTag()); + eventData.putBoolean("value", getIsChecked()); + return eventData; + } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/switchview/ReactSwitchManager.java b/ReactAndroid/src/main/java/com/facebook/react/views/switchview/ReactSwitchManager.java index 7ab494cc3ea..03dfc9e34a1 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/switchview/ReactSwitchManager.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/switchview/ReactSwitchManager.java @@ -1,41 +1,34 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ // switchview because switch is a keyword package com.facebook.react.views.switchview; -import android.graphics.PorterDuff; import android.view.View; -import android.view.ViewGroup; import android.widget.CompoundButton; import com.facebook.react.bridge.ReactContext; import com.facebook.react.uimanager.LayoutShadowNode; -import com.facebook.react.uimanager.ReactShadowNodeImpl; import com.facebook.react.uimanager.SimpleViewManager; import com.facebook.react.uimanager.ThemedReactContext; import com.facebook.react.uimanager.UIManagerModule; import com.facebook.react.uimanager.ViewProps; import com.facebook.react.uimanager.annotations.ReactProp; -import com.facebook.react.uimanager.events.EventDispatcher; import com.facebook.yoga.YogaMeasureFunction; import com.facebook.yoga.YogaMeasureMode; import com.facebook.yoga.YogaMeasureOutput; import com.facebook.yoga.YogaNode; import javax.annotation.Nullable; -/** - * View manager for {@link ReactSwitch} components. - */ +/** View manager for {@link ReactSwitch} components. */ public class ReactSwitchManager extends SimpleViewManager { public static final String REACT_CLASS = "AndroidSwitch"; - static class ReactSwitchShadowNode extends LayoutShadowNode implements - YogaMeasureFunction { + static class ReactSwitchShadowNode extends LayoutShadowNode implements YogaMeasureFunction { private int mWidth; private int mHeight; @@ -62,9 +55,7 @@ public class ReactSwitchManager extends SimpleViewManager { // on a specific device/theme/locale combination. ReactSwitch reactSwitch = new ReactSwitch(getThemedContext()); reactSwitch.setShowText(false); - final int spec = View.MeasureSpec.makeMeasureSpec( - 0, - View.MeasureSpec.UNSPECIFIED); + final int spec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); reactSwitch.measure(spec, spec); mWidth = reactSwitch.getMeasuredWidth(); mHeight = reactSwitch.getMeasuredHeight(); @@ -80,10 +71,10 @@ public class ReactSwitchManager extends SimpleViewManager { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { ReactContext reactContext = (ReactContext) buttonView.getContext(); - reactContext.getNativeModule(UIManagerModule.class).getEventDispatcher().dispatchEvent( - new ReactSwitchEvent( - buttonView.getId(), - isChecked)); + reactContext + .getNativeModule(UIManagerModule.class) + .getEventDispatcher() + .dispatchEvent(new ReactSwitchEvent(buttonView.getId(), isChecked)); } }; diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/text/CustomLetterSpacingSpan.java b/ReactAndroid/src/main/java/com/facebook/react/views/text/CustomLetterSpacingSpan.java index fe0c5ca6499..6f937ecef34 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/text/CustomLetterSpacingSpan.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/text/CustomLetterSpacingSpan.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.text; import android.annotation.TargetApi; @@ -12,15 +11,11 @@ import android.os.Build; import android.text.TextPaint; import android.text.style.MetricAffectingSpan; -import com.facebook.infer.annotation.Assertions; - /** - * A {@link MetricAffectingSpan} that allows to set the letter spacing - * on the selected text span. - * - * The letter spacing is specified in pixels, which are converted to - * ems at paint time; this span must therefore be applied after any - * spans affecting font size. + * A {@link MetricAffectingSpan} that allows to set the letter spacing on the selected text span. + * + *

The letter spacing is specified in pixels, which are converted to ems at paint time; this span + * must therefore be applied after any spans affecting font size. */ @TargetApi(Build.VERSION_CODES.LOLLIPOP) public class CustomLetterSpacingSpan extends MetricAffectingSpan implements ReactSpan { diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/text/CustomLineHeightSpan.java b/ReactAndroid/src/main/java/com/facebook/react/views/text/CustomLineHeightSpan.java index c866e2e61b6..63a2172a6ef 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/text/CustomLineHeightSpan.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/text/CustomLineHeightSpan.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.text; import android.graphics.Paint; @@ -23,12 +22,7 @@ public class CustomLineHeightSpan implements LineHeightSpan, ReactSpan { @Override public void chooseHeight( - CharSequence text, - int start, - int end, - int spanstartv, - int v, - Paint.FontMetricsInt fm) { + CharSequence text, int start, int end, int spanstartv, int v, Paint.FontMetricsInt fm) { // This is more complicated that I wanted it to be. You can find a good explanation of what the // FontMetrics mean here: http://stackoverflow.com/questions/27631736. // The general solution is that if there's not enough height to show the full line height, we diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/text/CustomStyleSpan.java b/ReactAndroid/src/main/java/com/facebook/react/views/text/CustomStyleSpan.java index 347b0c98b97..11a95a9834b 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/text/CustomStyleSpan.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/text/CustomStyleSpan.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.text; import android.content.res.AssetManager; @@ -12,7 +11,6 @@ import android.graphics.Paint; import android.graphics.Typeface; import android.text.TextPaint; import android.text.style.MetricAffectingSpan; - import androidx.annotation.NonNull; import androidx.annotation.Nullable; @@ -22,14 +20,13 @@ public class CustomStyleSpan extends MetricAffectingSpan implements ReactSpan { * A {@link MetricAffectingSpan} that allows to change the style of the displayed font. * CustomStyleSpan will try to load the fontFamily with the right style and weight from the * assets. The custom fonts will have to be located in the res/assets folder of the application. - * The supported custom fonts extensions are .ttf and .otf. For each font family the bold, - * italic and bold_italic variants are supported. Given a "family" font family the files in the + * The supported custom fonts extensions are .ttf and .otf. For each font family the bold, italic + * and bold_italic variants are supported. Given a "family" font family the files in the * assets/fonts folder need to be family.ttf(.otf) family_bold.ttf(.otf) family_italic.ttf(.otf) * and family_bold_italic.ttf(.otf). If the right font is not found in the assets folder * CustomStyleSpan will fallback on the most appropriate default typeface depending on the style. * Fonts are retrieved and cached using the {@link ReactFontManager} */ - private final AssetManager mAssetManager; private final int mStyle; @@ -57,33 +54,23 @@ public class CustomStyleSpan extends MetricAffectingSpan implements ReactSpan { apply(paint, mStyle, mWeight, mFontFamily, mAssetManager); } - /** - * Returns {@link Typeface#NORMAL} or {@link Typeface#ITALIC}. - */ + /** Returns {@link Typeface#NORMAL} or {@link Typeface#ITALIC}. */ public int getStyle() { return (mStyle == ReactTextShadowNode.UNSET ? 0 : mStyle); } - /** - * Returns {@link Typeface#NORMAL} or {@link Typeface#BOLD}. - */ + /** Returns {@link Typeface#NORMAL} or {@link Typeface#BOLD}. */ public int getWeight() { return (mWeight == ReactTextShadowNode.UNSET ? 0 : mWeight); } - /** - * Returns the font family set for this StyleSpan. - */ + /** Returns the font family set for this StyleSpan. */ public @Nullable String getFontFamily() { return mFontFamily; } private static void apply( - Paint paint, - int style, - int weight, - @Nullable String family, - AssetManager assetManager) { + Paint paint, int style, int weight, @Nullable String family, AssetManager assetManager) { int oldStyle; Typeface typeface = paint.getTypeface(); if (typeface == null) { @@ -93,13 +80,13 @@ public class CustomStyleSpan extends MetricAffectingSpan implements ReactSpan { } int want = 0; - if ((weight == Typeface.BOLD) || - ((oldStyle & Typeface.BOLD) != 0 && weight == ReactTextShadowNode.UNSET)) { + if ((weight == Typeface.BOLD) + || ((oldStyle & Typeface.BOLD) != 0 && weight == ReactTextShadowNode.UNSET)) { want |= Typeface.BOLD; } - if ((style == Typeface.ITALIC) || - ((oldStyle & Typeface.ITALIC) != 0 && style == ReactTextShadowNode.UNSET)) { + if ((style == Typeface.ITALIC) + || ((oldStyle & Typeface.ITALIC) != 0 && style == ReactTextShadowNode.UNSET)) { want |= Typeface.ITALIC; } diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/text/DefaultStyleValuesUtil.java b/ReactAndroid/src/main/java/com/facebook/react/views/text/DefaultStyleValuesUtil.java index 9e248833d37..90690e34e8a 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/text/DefaultStyleValuesUtil.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/text/DefaultStyleValuesUtil.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.text; import android.content.Context; @@ -12,9 +11,7 @@ import android.content.res.ColorStateList; import android.content.res.Resources; import android.content.res.TypedArray; -/** - * Utility class that access default values from style - */ +/** Utility class that access default values from style */ public final class DefaultStyleValuesUtil { private DefaultStyleValuesUtil() { @@ -55,7 +52,7 @@ public final class DefaultStyleValuesUtil { Resources.Theme theme = context.getTheme(); TypedArray textAppearances = null; try { - textAppearances = theme.obtainStyledAttributes(new int[]{attribute}); + textAppearances = theme.obtainStyledAttributes(new int[] {attribute}); ColorStateList textColor = textAppearances.getColorStateList(0); return textColor; } finally { diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/text/FontMetricsUtil.java b/ReactAndroid/src/main/java/com/facebook/react/views/text/FontMetricsUtil.java index 4d9b265a7ce..6f8d1d20a05 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/text/FontMetricsUtil.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/text/FontMetricsUtil.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.text; import android.content.Context; @@ -22,19 +21,24 @@ public class FontMetricsUtil { private static final String X_HEIGHT_MEASUREMENT_TEXT = "x"; private static final float AMPLIFICATION_FACTOR = 100; - public static WritableArray getFontMetrics(CharSequence text, Layout layout, TextPaint paint, Context context) { + public static WritableArray getFontMetrics( + CharSequence text, Layout layout, TextPaint paint, Context context) { DisplayMetrics dm = context.getResources().getDisplayMetrics(); WritableArray lines = Arguments.createArray(); - // To calculate xHeight and capHeight we have to render an "x" and "T" and manually measure their height. - // In order to get more precision than Android offers, we blow up the text size by 100 and measure it. + // To calculate xHeight and capHeight we have to render an "x" and "T" and manually measure + // their height. + // In order to get more precision than Android offers, we blow up the text size by 100 and + // measure it. // Luckily, text size affects rendering linearly, so we can do this trick. TextPaint paintCopy = new TextPaint(paint); paintCopy.setTextSize(paintCopy.getTextSize() * AMPLIFICATION_FACTOR); Rect capHeightBounds = new Rect(); - paintCopy.getTextBounds(CAP_HEIGHT_MEASUREMENT_TEXT, 0, CAP_HEIGHT_MEASUREMENT_TEXT.length(), capHeightBounds); + paintCopy.getTextBounds( + CAP_HEIGHT_MEASUREMENT_TEXT, 0, CAP_HEIGHT_MEASUREMENT_TEXT.length(), capHeightBounds); double capHeight = capHeightBounds.height() / AMPLIFICATION_FACTOR / dm.density; Rect xHeightBounds = new Rect(); - paintCopy.getTextBounds(X_HEIGHT_MEASUREMENT_TEXT, 0, X_HEIGHT_MEASUREMENT_TEXT.length(), xHeightBounds); + paintCopy.getTextBounds( + X_HEIGHT_MEASUREMENT_TEXT, 0, X_HEIGHT_MEASUREMENT_TEXT.length(), xHeightBounds); double xHeight = xHeightBounds.height() / AMPLIFICATION_FACTOR / dm.density; for (int i = 0; i < layout.getLineCount(); i++) { Rect bounds = new Rect(); diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactAbsoluteSizeSpan.java b/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactAbsoluteSizeSpan.java index 5d88e99d9e4..803f66ccc3e 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactAbsoluteSizeSpan.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactAbsoluteSizeSpan.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.text; import android.text.style.AbsoluteSizeSpan; diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactBackgroundColorSpan.java b/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactBackgroundColorSpan.java index 2472443b936..b0cdb1a145d 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactBackgroundColorSpan.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactBackgroundColorSpan.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.text; import android.text.style.BackgroundColorSpan; diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactBaseTextShadowNode.java b/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactBaseTextShadowNode.java index 015d4f72ced..fb460ca5a41 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactBaseTextShadowNode.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactBaseTextShadowNode.java @@ -1,8 +1,8 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ package com.facebook.react.views.text; @@ -14,7 +14,6 @@ import android.text.Layout; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.view.Gravity; - import com.facebook.infer.annotation.Assertions; import com.facebook.react.bridge.JSApplicationIllegalArgumentException; import com.facebook.react.bridge.ReadableMap; @@ -25,11 +24,9 @@ import com.facebook.react.uimanager.PixelUtil; import com.facebook.react.uimanager.ReactShadowNode; import com.facebook.react.uimanager.ViewProps; import com.facebook.react.uimanager.annotations.ReactProp; -import com.facebook.yoga.YogaConstants; import com.facebook.yoga.YogaDirection; import com.facebook.yoga.YogaUnit; import com.facebook.yoga.YogaValue; - import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -112,10 +109,16 @@ public abstract class ReactBaseTextShadowNode extends LayoutShadowNode { if (child instanceof ReactRawTextShadowNode) { sb.append( TextTransform.apply( - ((ReactRawTextShadowNode) child).getText(), - textAttributes.getTextTransform())); + ((ReactRawTextShadowNode) child).getText(), textAttributes.getTextTransform())); } else if (child instanceof ReactBaseTextShadowNode) { - buildSpannedFromShadowNode((ReactBaseTextShadowNode) child, sb, ops, textAttributes, supportsInlineViews, inlineViews, sb.length()); + buildSpannedFromShadowNode( + (ReactBaseTextShadowNode) child, + sb, + ops, + textAttributes, + supportsInlineViews, + inlineViews, + sb.length()); } else if (child instanceof ReactTextInlineImageShadowNode) { // We make the image take up 1 character in the span and put a corresponding character into // the text so that the image doesn't run over any following text. @@ -131,12 +134,14 @@ public abstract class ReactBaseTextShadowNode extends LayoutShadowNode { YogaValue heightValue = child.getStyleHeight(); if (widthValue.unit != YogaUnit.POINT || heightValue.unit != YogaUnit.POINT) { - throw new IllegalViewOperationException("Views nested within a must have a width and height"); + throw new IllegalViewOperationException( + "Views nested within a must have a width and height"); } float width = widthValue.value; float height = heightValue.value; - // We make the inline view take up 1 character in the span and put a corresponding character into + // We make the inline view take up 1 character in the span and put a corresponding character + // into // the text so that the inline view doesn't run over any following text. sb.append(INLINE_VIEW_PLACEHOLDER); ops.add( @@ -154,7 +159,8 @@ public abstract class ReactBaseTextShadowNode extends LayoutShadowNode { int end = sb.length(); if (end >= start) { if (textShadowNode.mIsColorSet) { - ops.add(new SetSpanOperation(start, end, new ReactForegroundColorSpan(textShadowNode.mColor))); + ops.add( + new SetSpanOperation(start, end, new ReactForegroundColorSpan(textShadowNode.mColor))); } if (textShadowNode.mIsBackgroundColorSet) { ops.add( @@ -164,17 +170,18 @@ public abstract class ReactBaseTextShadowNode extends LayoutShadowNode { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { float effectiveLetterSpacing = textAttributes.getEffectiveLetterSpacing(); if (!Float.isNaN(effectiveLetterSpacing) - && (parentTextAttributes == null || parentTextAttributes.getEffectiveLetterSpacing() != effectiveLetterSpacing)) { - ops.add(new SetSpanOperation( - start, - end, - new CustomLetterSpacingSpan(effectiveLetterSpacing))); + && (parentTextAttributes == null + || parentTextAttributes.getEffectiveLetterSpacing() != effectiveLetterSpacing)) { + ops.add( + new SetSpanOperation( + start, end, new CustomLetterSpacingSpan(effectiveLetterSpacing))); } } int effectiveFontSize = textAttributes.getEffectiveFontSize(); - if (// `getEffectiveFontSize` always returns a value so don't need to check for anything like - // `Float.NaN`. - parentTextAttributes == null || parentTextAttributes.getEffectiveFontSize() != effectiveFontSize) { + if ( // `getEffectiveFontSize` always returns a value so don't need to check for anything like + // `Float.NaN`. + parentTextAttributes == null + || parentTextAttributes.getEffectiveFontSize() != effectiveFontSize) { ops.add(new SetSpanOperation(start, end, new ReactAbsoluteSizeSpan(effectiveFontSize))); } if (textShadowNode.mFontStyle != UNSET @@ -196,14 +203,10 @@ public abstract class ReactBaseTextShadowNode extends LayoutShadowNode { if (textShadowNode.mIsLineThroughTextDecorationSet) { ops.add(new SetSpanOperation(start, end, new ReactStrikethroughSpan())); } - if ( - ( - textShadowNode.mTextShadowOffsetDx != 0 || - textShadowNode.mTextShadowOffsetDy != 0 || - textShadowNode.mTextShadowRadius != 0 - ) && - Color.alpha(textShadowNode.mTextShadowColor) != 0 - ) { + if ((textShadowNode.mTextShadowOffsetDx != 0 + || textShadowNode.mTextShadowOffsetDy != 0 + || textShadowNode.mTextShadowRadius != 0) + && Color.alpha(textShadowNode.mTextShadowColor) != 0) { ops.add( new SetSpanOperation( start, @@ -216,10 +219,9 @@ public abstract class ReactBaseTextShadowNode extends LayoutShadowNode { } float effectiveLineHeight = textAttributes.getEffectiveLineHeight(); if (!Float.isNaN(effectiveLineHeight) - && (parentTextAttributes == null || parentTextAttributes.getEffectiveLineHeight() != effectiveLineHeight)) { - ops.add( - new SetSpanOperation( - start, end, new CustomLineHeightSpan(effectiveLineHeight))); + && (parentTextAttributes == null + || parentTextAttributes.getEffectiveLineHeight() != effectiveLineHeight)) { + ops.add(new SetSpanOperation(start, end, new CustomLineHeightSpan(effectiveLineHeight))); } ops.add(new SetSpanOperation(start, end, new ReactTagSpan(textShadowNode.getReactTag()))); } @@ -242,7 +244,8 @@ public abstract class ReactBaseTextShadowNode extends LayoutShadowNode { // up-to-bottom, otherwise all the spannables that are withing the region for which one may set // a new spannable will be wiped out List ops = new ArrayList<>(); - Map inlineViews = supportsInlineViews ? new HashMap() : null; + Map inlineViews = + supportsInlineViews ? new HashMap() : null; if (text != null) { // Handle text that is provided via a prop (e.g. the `value` and `defaultValue` props on @@ -264,7 +267,7 @@ public abstract class ReactBaseTextShadowNode extends LayoutShadowNode { if (isInlineImage || op.what instanceof TextInlineViewPlaceholderSpan) { int height; if (isInlineImage) { - height = ((TextInlineImageSpan)op.what).getHeight(); + height = ((TextInlineImageSpan) op.what).getHeight(); textShadowNode.mContainsImages = true; } else { TextInlineViewPlaceholderSpan placeholder = (TextInlineViewPlaceholderSpan) op.what; @@ -279,7 +282,8 @@ public abstract class ReactBaseTextShadowNode extends LayoutShadowNode { childNode.setLayoutParent(textShadowNode); } - if (Float.isNaN(heightOfTallestInlineViewOrImage) || height > heightOfTallestInlineViewOrImage) { + if (Float.isNaN(heightOfTallestInlineViewOrImage) + || height > heightOfTallestInlineViewOrImage) { heightOfTallestInlineViewOrImage = height; } } @@ -290,7 +294,8 @@ public abstract class ReactBaseTextShadowNode extends LayoutShadowNode { priority++; } - textShadowNode.mTextAttributes.setHeightOfTallestInlineViewOrImage(heightOfTallestInlineViewOrImage); + textShadowNode.mTextAttributes.setHeightOfTallestInlineViewOrImage( + heightOfTallestInlineViewOrImage); return sb; } @@ -299,8 +304,8 @@ public abstract class ReactBaseTextShadowNode extends LayoutShadowNode { * Return -1 if the input string is not a valid numeric fontWeight (100, 200, ..., 900), otherwise * return the weight. * - * This code is duplicated in ReactTextInputManager - * TODO: Factor into a common place they can both use + *

This code is duplicated in ReactTextInputManager TODO: Factor into a common place they can + * both use */ private static int parseNumericFontWeight(String fontWeightString) { // This should be much faster than using regex to verify input and Integer.parseInt @@ -324,7 +329,7 @@ public abstract class ReactBaseTextShadowNode extends LayoutShadowNode { protected int mTextBreakStrategy = (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) ? 0 : Layout.BREAK_STRATEGY_HIGH_QUALITY; protected int mJustificationMode = - (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) ? 0 : Layout.JUSTIFICATION_MODE_NONE; + (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) ? 0 : Layout.JUSTIFICATION_MODE_NONE; protected TextTransform mTextTransform = TextTransform.UNSET; protected float mTextShadowOffsetDx = 0; @@ -337,8 +342,8 @@ public abstract class ReactBaseTextShadowNode extends LayoutShadowNode { protected boolean mIncludeFontPadding = true; /** - * mFontStyle can be {@link Typeface#NORMAL} or {@link Typeface#ITALIC}. - * mFontWeight can be {@link Typeface#NORMAL} or {@link Typeface#BOLD}. + * mFontStyle can be {@link Typeface#NORMAL} or {@link Typeface#ITALIC}. mFontWeight can be {@link + * Typeface#NORMAL} or {@link Typeface#BOLD}. */ protected int mFontStyle = UNSET; @@ -346,19 +351,18 @@ public abstract class ReactBaseTextShadowNode extends LayoutShadowNode { /** * NB: If a font family is used that does not have a style in a certain Android version (ie. * monospace bold pre Android 5.0), that style (ie. bold) will not be inherited by nested Text - * nodes. To retain that style, you have to add it to those nodes explicitly. - * Example, Android 4.4: - * Bold Text - * Bold Text - * Bold Text + * nodes. To retain that style, you have to add it to those nodes explicitly. Example, Android + * 4.4: Bold Text Bold Text Bold + * Text * - * Not Bold Text - * Not Bold Text - * Not Bold Text + *

Not Bold Text Not Bold Text Not + * Bold Text * - * Not Bold Text - * Bold Text - * Bold Text + *

Not Bold Text Bold Text Bold Text */ protected @Nullable String mFontFamily = null; @@ -439,7 +443,6 @@ public abstract class ReactBaseTextShadowNode extends LayoutShadowNode { } else { throw new JSApplicationIllegalArgumentException("Invalid textAlign: " + textAlign); } - } markUpdated(); } @@ -481,9 +484,9 @@ public abstract class ReactBaseTextShadowNode extends LayoutShadowNode { } /** - /* This code is duplicated in ReactTextInputManager - /* TODO: Factor into a common place they can both use - */ + * /* This code is duplicated in ReactTextInputManager /* TODO: Factor into a common place they + * can both use + */ @ReactProp(name = ViewProps.FONT_WEIGHT) public void setFontWeight(@Nullable String fontWeightString) { int fontWeightNumeric = @@ -500,9 +503,9 @@ public abstract class ReactBaseTextShadowNode extends LayoutShadowNode { } /** - /* This code is duplicated in ReactTextInputManager - /* TODO: Factor into a common place they can both use - */ + * /* This code is duplicated in ReactTextInputManager /* TODO: Factor into a common place they + * can both use + */ @ReactProp(name = ViewProps.FONT_STYLE) public void setFontStyle(@Nullable String fontStyleString) { int fontStyle = UNSET; diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactFontManager.java b/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactFontManager.java index 21d4c175380..a501df8253f 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactFontManager.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactFontManager.java @@ -1,24 +1,21 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.text; -import java.util.HashMap; -import java.util.Map; - import android.content.Context; import android.content.res.AssetManager; import android.graphics.Typeface; import android.os.Build; import android.util.SparseArray; - import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.content.res.ResourcesCompat; +import java.util.HashMap; +import java.util.Map; /** * Class responsible to load and cache Typeface objects. It will first try to load typefaces inside @@ -30,18 +27,14 @@ import androidx.core.content.res.ResourcesCompat; */ public class ReactFontManager { - private static final String[] EXTENSIONS = { - "", - "_bold", - "_italic", - "_bold_italic"}; + private static final String[] EXTENSIONS = {"", "_bold", "_italic", "_bold_italic"}; private static final String[] FILE_EXTENSIONS = {".ttf", ".otf"}; private static final String FONTS_ASSET_PATH = "fonts/"; private static ReactFontManager sReactFontManagerInstance; - final private Map mFontCache; - final private Map mCustomTypefaceCache; + private final Map mFontCache; + private final Map mCustomTypefaceCache; private ReactFontManager() { mFontCache = new HashMap<>(); @@ -56,18 +49,13 @@ public class ReactFontManager { } public @Nullable Typeface getTypeface( - String fontFamilyName, - int style, - AssetManager assetManager) { + String fontFamilyName, int style, AssetManager assetManager) { return getTypeface(fontFamilyName, style, 0, assetManager); } public @Nullable Typeface getTypeface( - String fontFamilyName, - int style, - int weight, - AssetManager assetManager) { - if(mCustomTypefaceCache.containsKey(fontFamilyName)) { + String fontFamilyName, int style, int weight, AssetManager assetManager) { + if (mCustomTypefaceCache.containsKey(fontFamilyName)) { Typeface typeface = mCustomTypefaceCache.get(fontFamilyName); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && weight >= 100 && weight <= 1000) { return Typeface.create(typeface, weight, (style & Typeface.ITALIC) != 0); @@ -108,6 +96,7 @@ public class ReactFontManager { /** * Add additional font family, or replace the exist one in the font memory cache. + * * @param style * @see {@link Typeface#DEFAULT} * @see {@link Typeface#BOLD} @@ -125,19 +114,17 @@ public class ReactFontManager { } } - private static - @Nullable Typeface createTypeface( - String fontFamilyName, - int style, - AssetManager assetManager) { + private static @Nullable Typeface createTypeface( + String fontFamilyName, int style, AssetManager assetManager) { String extension = EXTENSIONS[style]; for (String fileExtension : FILE_EXTENSIONS) { - String fileName = new StringBuilder() - .append(FONTS_ASSET_PATH) - .append(fontFamilyName) - .append(extension) - .append(fileExtension) - .toString(); + String fileName = + new StringBuilder() + .append(FONTS_ASSET_PATH) + .append(fontFamilyName) + .append(extension) + .append(fileExtension) + .toString(); try { return Typeface.createFromAsset(assetManager, fileName); } catch (RuntimeException e) { @@ -164,6 +151,5 @@ public class ReactFontManager { public void setTypeface(int style, Typeface typeface) { mTypefaceSparseArray.put(style, typeface); } - } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactForegroundColorSpan.java b/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactForegroundColorSpan.java index 44383d2f831..636734fcc33 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactForegroundColorSpan.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactForegroundColorSpan.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.text; import android.text.style.ForegroundColorSpan; diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactRawTextManager.java b/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactRawTextManager.java index 7a6a6af6d83..83b7b6a3854 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactRawTextManager.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactRawTextManager.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.text; import android.view.View; @@ -14,15 +13,13 @@ import com.facebook.react.uimanager.ThemedReactContext; import com.facebook.react.uimanager.ViewManager; /** - * Manages raw text nodes (aka {@code textContent} in terms of DOM). - * Since they are used only as a virtual nodes, any type of native view - * operation will throw an {@link IllegalStateException}. + * Manages raw text nodes (aka {@code textContent} in terms of DOM). Since they are used only as a + * virtual nodes, any type of native view operation will throw an {@link IllegalStateException}. */ @ReactModule(name = ReactRawTextManager.REACT_CLASS) public class ReactRawTextManager extends ViewManager { - @VisibleForTesting - public static final String REACT_CLASS = "RCTRawText"; + @VisibleForTesting public static final String REACT_CLASS = "RCTRawText"; @Override public String getName() { diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactRawTextShadowNode.java b/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactRawTextShadowNode.java index aa389fdcf40..2b3ccf79059 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactRawTextShadowNode.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactRawTextShadowNode.java @@ -1,8 +1,8 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ package com.facebook.react.views.text; @@ -22,7 +22,7 @@ public class ReactRawTextShadowNode extends ReactShadowNodeImpl { private @Nullable String mText = null; - public ReactRawTextShadowNode() { } + public ReactRawTextShadowNode() {} @ReactProp(name = PROP_TEXT) public void setText(@Nullable String text) { diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactSpan.java b/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactSpan.java index dc3787936db..4aa31f17f54 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactSpan.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactSpan.java @@ -1,15 +1,13 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.text; /* * Enables us to distinguish between spans that were added by React Native and spans that were * added by something else. All spans that React Native adds should implement this interface. */ -public interface ReactSpan { -} +public interface ReactSpan {} diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactStrikethroughSpan.java b/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactStrikethroughSpan.java index b881f7d2eb2..93767ef6687 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactStrikethroughSpan.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactStrikethroughSpan.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.text; import android.text.style.StrikethroughSpan; @@ -12,5 +11,4 @@ import android.text.style.StrikethroughSpan; /* * Wraps {@link StrikethroughSpan} as a {@link ReactSpan}. */ -public class ReactStrikethroughSpan extends StrikethroughSpan implements ReactSpan { -} +public class ReactStrikethroughSpan extends StrikethroughSpan implements ReactSpan {} diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTagSpan.java b/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTagSpan.java index 48b08aa5005..ce88229aeba 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTagSpan.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTagSpan.java @@ -1,15 +1,14 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.text; /** - * Instances of this class are used to place reactTag information of nested text react nodes - * into spannable text rendered by single {@link TextView} + * Instances of this class are used to place reactTag information of nested text react nodes into + * spannable text rendered by single {@link TextView} */ public class ReactTagSpan implements ReactSpan { diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTextAnchorViewManager.java b/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTextAnchorViewManager.java index 2cedc5afbe9..f0fd027d478 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTextAnchorViewManager.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTextAnchorViewManager.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.text; import android.text.Spannable; @@ -92,15 +91,14 @@ public abstract class ReactTextAnchorViewManagerThis source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.text; -import com.facebook.yoga.YogaNode; import com.facebook.react.uimanager.LayoutShadowNode; +import com.facebook.yoga.YogaNode; -/** - * Base class for {@link YogaNode}s that represent inline images. - */ +/** Base class for {@link YogaNode}s that represent inline images. */ public abstract class ReactTextInlineImageShadowNode extends LayoutShadowNode { /** - * Build a {@link TextInlineImageSpan} from this node. This will be added to the TextView in - * place of this node. + * Build a {@link TextInlineImageSpan} from this node. This will be added to the TextView in place + * of this node. */ public abstract TextInlineImageSpan buildInlineImageSpan(); public ReactTextInlineImageShadowNode() {} - } diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTextShadowNode.java b/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTextShadowNode.java index fd181c1c96e..8e7939b6243 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTextShadowNode.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTextShadowNode.java @@ -32,9 +32,7 @@ import com.facebook.yoga.YogaMeasureFunction; import com.facebook.yoga.YogaMeasureMode; import com.facebook.yoga.YogaMeasureOutput; import com.facebook.yoga.YogaNode; - import java.util.ArrayList; - import javax.annotation.Nullable; /** @@ -106,17 +104,17 @@ public class ReactTextShadowNode extends ReactBaseTextShadowNode { } else { StaticLayout.Builder builder = StaticLayout.Builder.obtain(text, 0, text.length(), textPaint, hintWidth) - .setAlignment(alignment) - .setLineSpacing(0.f, 1.f) - .setIncludePad(mIncludeFontPadding) - .setBreakStrategy(mTextBreakStrategy) - .setHyphenationFrequency(Layout.HYPHENATION_FREQUENCY_NORMAL); + .setAlignment(alignment) + .setLineSpacing(0.f, 1.f) + .setIncludePad(mIncludeFontPadding) + .setBreakStrategy(mTextBreakStrategy) + .setHyphenationFrequency(Layout.HYPHENATION_FREQUENCY_NORMAL); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { builder.setJustificationMode(mJustificationMode); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { - builder.setUseLineSpacingFromFallbacks(true); + builder.setUseLineSpacingFromFallbacks(true); } layout = builder.build(); } @@ -151,7 +149,7 @@ public class ReactTextShadowNode extends ReactBaseTextShadowNode { .setHyphenationFrequency(Layout.HYPHENATION_FREQUENCY_NORMAL); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { - builder.setUseLineSpacingFromFallbacks(true); + builder.setUseLineSpacingFromFallbacks(true); } layout = builder.build(); } @@ -202,11 +200,12 @@ public class ReactTextShadowNode extends ReactBaseTextShadowNode { @Override public void onBeforeLayout(NativeViewHierarchyOptimizer nativeViewHierarchyOptimizer) { - mPreparedSpannableText = spannedFromShadowNode( - this, - /* text (e.g. from `value` prop): */ null, - /* supportsInlineViews: */ true, - nativeViewHierarchyOptimizer); + mPreparedSpannableText = + spannedFromShadowNode( + this, + /* text (e.g. from `value` prop): */ null, + /* supportsInlineViews: */ true, + nativeViewHierarchyOptimizer); markUpdated(); } @@ -264,10 +263,12 @@ public class ReactTextShadowNode extends ReactBaseTextShadowNode { return null; } - Spanned text = Assertions.assertNotNull( - this.mPreparedSpannableText, - "Spannable element has not been prepared in onBeforeLayout"); - TextInlineViewPlaceholderSpan[] placeholders = text.getSpans(0, text.length(), TextInlineViewPlaceholderSpan.class); + Spanned text = + Assertions.assertNotNull( + this.mPreparedSpannableText, + "Spannable element has not been prepared in onBeforeLayout"); + TextInlineViewPlaceholderSpan[] placeholders = + text.getSpans(0, text.length(), TextInlineViewPlaceholderSpan.class); ArrayList shadowNodes = new ArrayList(placeholders.length); for (TextInlineViewPlaceholderSpan placeholder : placeholders) { diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTextUpdate.java b/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTextUpdate.java index 26957a58f19..d2ab6d3a4a4 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTextUpdate.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTextUpdate.java @@ -1,18 +1,16 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.text; import android.text.Layout; import android.text.Spannable; /** - * Class that contains the data needed for a text update. - * Used by both and + * Class that contains the data needed for a text update. Used by both and * VisibleForTesting from {@link TextInputEventsTestCase}. */ public class ReactTextUpdate { @@ -32,7 +30,7 @@ public class ReactTextUpdate { /** * @deprecated Use a non-deprecated constructor for ReactTextUpdate instead. This one remains - * because it's being used by a unit test that isn't currently open source. + * because it's being used by a unit test that isn't currently open source. */ @Deprecated public ReactTextUpdate( @@ -44,7 +42,8 @@ public class ReactTextUpdate { float paddingEnd, float paddingBottom, int textAlign) { - this(text, + this( + text, jsEventCounter, containsImages, paddingStart, @@ -59,17 +58,18 @@ public class ReactTextUpdate { } public ReactTextUpdate( - Spannable text, - int jsEventCounter, - boolean containsImages, - float paddingStart, - float paddingTop, - float paddingEnd, - float paddingBottom, - int textAlign, - int textBreakStrategy, - int justificationMode) { - this(text, + Spannable text, + int jsEventCounter, + boolean containsImages, + float paddingStart, + float paddingTop, + float paddingEnd, + float paddingBottom, + int textAlign, + int textBreakStrategy, + int justificationMode) { + this( + text, jsEventCounter, containsImages, paddingStart, @@ -84,18 +84,18 @@ public class ReactTextUpdate { } public ReactTextUpdate( - Spannable text, - int jsEventCounter, - boolean containsImages, - float paddingStart, - float paddingTop, - float paddingEnd, - float paddingBottom, - int textAlign, - int textBreakStrategy, - int justificationMode, - int selectionStart, - int selectionEnd) { + Spannable text, + int jsEventCounter, + boolean containsImages, + float paddingStart, + float paddingTop, + float paddingEnd, + float paddingBottom, + int textAlign, + int textBreakStrategy, + int justificationMode, + int selectionStart, + int selectionEnd) { mText = text; mJsEventCounter = jsEventCounter; mContainsImages = containsImages; diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTextView.java b/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTextView.java index feede92d6e8..428f05b0b46 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTextView.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTextView.java @@ -1,17 +1,14 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.text; import android.content.Context; import android.graphics.drawable.Drawable; import android.os.Build; -import androidx.appcompat.widget.AppCompatTextView; -import androidx.appcompat.widget.TintContextWrapper; import android.text.Layout; import android.text.Spannable; import android.text.Spanned; @@ -21,7 +18,8 @@ import android.text.util.Linkify; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; - +import androidx.appcompat.widget.AppCompatTextView; +import androidx.appcompat.widget.TintContextWrapper; import com.facebook.common.logging.FLog; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.ReactContext; @@ -34,16 +32,15 @@ import com.facebook.react.uimanager.UIManagerModule; import com.facebook.react.uimanager.ViewDefaults; import com.facebook.react.uimanager.events.RCTEventEmitter; import com.facebook.react.views.view.ReactViewBackgroundManager; -import javax.annotation.Nullable; - import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; +import javax.annotation.Nullable; public class ReactTextView extends AppCompatTextView implements ReactCompoundView { private static final ViewGroup.LayoutParams EMPTY_LAYOUT_PARAMS = - new ViewGroup.LayoutParams(0, 0); + new ViewGroup.LayoutParams(0, 0); private boolean mContainsImages; private int mDefaultGravityHorizontal; @@ -61,11 +58,12 @@ public class ReactTextView extends AppCompatTextView implements ReactCompoundVie super(context); mReactBackgroundManager = new ReactViewBackgroundManager(this); mDefaultGravityHorizontal = - getGravity() & (Gravity.HORIZONTAL_GRAVITY_MASK | Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK); + getGravity() & (Gravity.HORIZONTAL_GRAVITY_MASK | Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK); mDefaultGravityVertical = getGravity() & Gravity.VERTICAL_GRAVITY_MASK; } - private WritableMap inlineViewJson(int visibility, int index, int left, int top, int right, int bottom) { + private WritableMap inlineViewJson( + int visibility, int index, int left, int top, int right, int bottom) { WritableMap json = Arguments.createMap(); if (visibility == View.GONE) { json.putString("visibility", "gone"); @@ -87,28 +85,25 @@ public class ReactTextView extends AppCompatTextView implements ReactCompoundVie private ReactContext getReactContext() { Context context = getContext(); return (context instanceof TintContextWrapper) - ? (ReactContext)((TintContextWrapper)context).getBaseContext() - : (ReactContext)context; + ? (ReactContext) ((TintContextWrapper) context).getBaseContext() + : (ReactContext) context; } @Override - protected void onLayout(boolean changed, - int textViewLeft, - int textViewTop, - int textViewRight, - int textViewBottom) { + protected void onLayout( + boolean changed, int textViewLeft, int textViewTop, int textViewRight, int textViewBottom) { if (!(getText() instanceof Spanned)) { /** * In general, {@link #setText} is called via {@link ReactTextViewManager#updateExtraData} * before we are laid out. This ordering is a requirement because we utilize the data from * setText in onLayout. * - * However, it's possible for us to get an extra layout before we've received our setText + *

However, it's possible for us to get an extra layout before we've received our setText * call. If this happens before the initial setText call, then getText() will have its default * value which isn't a Spanned and we need to bail out. That's fine because we'll get a * setText followed by a layout later. * - * The cause for the extra early layout is that an ancestor gets transitioned from a + *

The cause for the extra early layout is that an ancestor gets transitioned from a * layout-only node to a non layout-only node. */ return; @@ -124,8 +119,10 @@ public class ReactTextView extends AppCompatTextView implements ReactCompoundVie Spanned text = (Spanned) getText(); Layout layout = getLayout(); - TextInlineViewPlaceholderSpan[] placeholders = text.getSpans(0, text.length(), TextInlineViewPlaceholderSpan.class); - ArrayList inlineViewInfoArray = mNotifyOnInlineViewLayout ? new ArrayList(placeholders.length) : null; + TextInlineViewPlaceholderSpan[] placeholders = + text.getSpans(0, text.length(), TextInlineViewPlaceholderSpan.class); + ArrayList inlineViewInfoArray = + mNotifyOnInlineViewLayout ? new ArrayList(placeholders.length) : null; int textViewWidth = textViewRight - textViewLeft; int textViewHeight = textViewBottom - textViewTop; @@ -136,17 +133,19 @@ public class ReactTextView extends AppCompatTextView implements ReactCompoundVie int line = layout.getLineForOffset(start); boolean isLineTruncated = layout.getEllipsisCount(line) > 0; - if (// This truncation check works well on recent versions of Android (tested on 5.1.1 and - // 6.0.1) but not on Android 4.4.4. The reason is that getEllipsisCount is buggy on - // Android 4.4.4. Specifically, it incorrectly returns 0 if an inline view is the first - // thing to be truncated. - (isLineTruncated && start >= layout.getLineStart(line) + layout.getEllipsisStart(line)) || + if ( // This truncation check works well on recent versions of Android (tested on 5.1.1 and + // 6.0.1) but not on Android 4.4.4. The reason is that getEllipsisCount is buggy on + // Android 4.4.4. Specifically, it incorrectly returns 0 if an inline view is the first + // thing to be truncated. + (isLineTruncated && start >= layout.getLineStart(line) + layout.getEllipsisStart(line)) + || // This truncation check works well on Android 4.4.4 but not on others (e.g. 6.0.1). // On Android 4.4.4, getLineEnd returns the first truncated character whereas on 6.0.1, // it appears to return the position after the last character on the line even if that // character is truncated. - line >= mNumberOfLines || start >= layout.getLineEnd(line)) { + line >= mNumberOfLines + || start >= layout.getLineEnd(line)) { // On some versions of Android (e.g. 4.4.4, 5.1.1), getPrimaryHorizontal can infinite // loop when called on a character that appears after the ellipsis. Avoid this bug by // special casing the character truncation case. @@ -168,21 +167,25 @@ public class ReactTextView extends AppCompatTextView implements ReactCompoundVie // the last offset in the layout will result in an endless loop. Work around // this bug by avoiding getPrimaryHorizontal in that case. if (start == text.length() - 1) { - placeholderHorizontalPosition = isRtlParagraph - // Equivalent to `layout.getLineLeft(line)` but `getLineLeft` returns incorrect - // values when the paragraph is RTL and `setSingleLine(true)`. - ? textViewWidth - (int)layout.getLineWidth(line) - : (int) layout.getLineRight(line) - width; + placeholderHorizontalPosition = + isRtlParagraph + // Equivalent to `layout.getLineLeft(line)` but `getLineLeft` returns incorrect + // values when the paragraph is RTL and `setSingleLine(true)`. + ? textViewWidth - (int) layout.getLineWidth(line) + : (int) layout.getLineRight(line) - width; } else { - // The direction of the paragraph may not be exactly the direction the string is heading in at the - // position of the placeholder. So, if the direction of the character is the same as the paragraph + // The direction of the paragraph may not be exactly the direction the string is heading + // in at the + // position of the placeholder. So, if the direction of the character is the same as the + // paragraph // use primary, secondary otherwise. boolean characterAndParagraphDirectionMatch = isRtlParagraph == isRtlChar; - placeholderHorizontalPosition = characterAndParagraphDirectionMatch - ? (int) layout.getPrimaryHorizontal(start) - : (int) layout.getSecondaryHorizontal(start); - + placeholderHorizontalPosition = + characterAndParagraphDirectionMatch + ? (int) layout.getPrimaryHorizontal(start) + : (int) layout.getSecondaryHorizontal(start); + if (isRtlParagraph) { // Adjust `placeholderHorizontalPosition` to work around an Android bug. // The bug is when the paragraph is RTL and `setSingleLine(true)`, some layout @@ -190,8 +193,10 @@ public class ReactTextView extends AppCompatTextView implements ReactCompoundVie // `getLineRight` return incorrect values. Their return values seem to be off // by the same number of pixels so subtracting these values cancels out the error. // - // The result is equivalent to bugless versions of `getPrimaryHorizontal`/`getSecondaryHorizontal`. - placeholderHorizontalPosition = textViewWidth - ((int)layout.getLineRight(line) - placeholderHorizontalPosition); + // The result is equivalent to bugless versions of + // `getPrimaryHorizontal`/`getSecondaryHorizontal`. + placeholderHorizontalPosition = + textViewWidth - ((int) layout.getLineRight(line) - placeholderHorizontalPosition); } if (isRtlChar) { @@ -199,9 +204,10 @@ public class ReactTextView extends AppCompatTextView implements ReactCompoundVie } } - int leftRelativeToTextView = isRtlChar - ? placeholderHorizontalPosition + getTotalPaddingRight() - : placeholderHorizontalPosition + getTotalPaddingLeft(); + int leftRelativeToTextView = + isRtlChar + ? placeholderHorizontalPosition + getTotalPaddingRight() + : placeholderHorizontalPosition + getTotalPaddingLeft(); int left = textViewLeft + leftRelativeToTextView; @@ -209,7 +215,8 @@ public class ReactTextView extends AppCompatTextView implements ReactCompoundVie int topRelativeToTextView = getTotalPaddingTop() + layout.getLineBaseline(line) - height; int top = textViewTop + topRelativeToTextView; - boolean isFullyClipped = textViewWidth <= leftRelativeToTextView || textViewHeight <= topRelativeToTextView; + boolean isFullyClipped = + textViewWidth <= leftRelativeToTextView || textViewHeight <= topRelativeToTextView; int layoutVisibility = isFullyClipped ? View.GONE : View.VISIBLE; int layoutLeft = left; int layoutTop = top; @@ -221,32 +228,33 @@ public class ReactTextView extends AppCompatTextView implements ReactCompoundVie child.layout(layoutLeft, layoutTop, layoutRight, layoutBottom); if (mNotifyOnInlineViewLayout) { inlineViewInfoArray.add( - inlineViewJson(layoutVisibility, start, layoutLeft, layoutTop, layoutRight, layoutBottom)); + inlineViewJson( + layoutVisibility, start, layoutLeft, layoutTop, layoutRight, layoutBottom)); } } } if (mNotifyOnInlineViewLayout) { - Collections.sort(inlineViewInfoArray, new Comparator() { - @Override - public int compare(Object o1, Object o2) { - WritableMap m1 = (WritableMap)o1; - WritableMap m2 = (WritableMap)o2; - return m1.getInt("index") - m2.getInt("index"); - } - }); + Collections.sort( + inlineViewInfoArray, + new Comparator() { + @Override + public int compare(Object o1, Object o2) { + WritableMap m1 = (WritableMap) o1; + WritableMap m2 = (WritableMap) o2; + return m1.getInt("index") - m2.getInt("index"); + } + }); WritableArray inlineViewInfoArray2 = Arguments.createArray(); for (Object item : inlineViewInfoArray) { - inlineViewInfoArray2.pushMap((WritableMap)item); + inlineViewInfoArray2.pushMap((WritableMap) item); } WritableMap event = Arguments.createMap(); event.putArray("inlineViews", inlineViewInfoArray2); - getReactContext().getJSModule(RCTEventEmitter.class).receiveEvent( - getId(), - "topInlineViewLayout", - event - ); + getReactContext() + .getJSModule(RCTEventEmitter.class) + .receiveEvent(getId(), "topInlineViewLayout", event); } } @@ -265,10 +273,10 @@ public class ReactTextView extends AppCompatTextView implements ReactCompoundVie } setText(spannable); setPadding( - (int) Math.floor(update.getPaddingLeft()), - (int) Math.floor(update.getPaddingTop()), - (int) Math.floor(update.getPaddingRight()), - (int) Math.floor(update.getPaddingBottom())); + (int) Math.floor(update.getPaddingLeft()), + (int) Math.floor(update.getPaddingTop()), + (int) Math.floor(update.getPaddingRight()), + (int) Math.floor(update.getPaddingBottom())); int nextTextAlign = update.getTextAlign(); if (mTextAlign != nextTextAlign) { @@ -429,8 +437,10 @@ public class ReactTextView extends AppCompatTextView implements ReactCompoundVie gravityHorizontal = mDefaultGravityHorizontal; } setGravity( - (getGravity() & ~Gravity.HORIZONTAL_GRAVITY_MASK & - ~Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) | gravityHorizontal); + (getGravity() + & ~Gravity.HORIZONTAL_GRAVITY_MASK + & ~Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) + | gravityHorizontal); } /* package */ void setGravityVertical(int gravityVertical) { @@ -455,7 +465,9 @@ public class ReactTextView extends AppCompatTextView implements ReactCompoundVie } public void updateView() { - @Nullable TextUtils.TruncateAt ellipsizeLocation = mNumberOfLines == ViewDefaults.NUMBER_OF_LINES ? null : mEllipsizeLocation; + @Nullable + TextUtils.TruncateAt ellipsizeLocation = + mNumberOfLines == ViewDefaults.NUMBER_OF_LINES ? null : mEllipsizeLocation; setEllipsize(ellipsizeLocation); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTextViewManager.java b/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTextViewManager.java index f744c392a83..7eab1eaf6cb 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTextViewManager.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTextViewManager.java @@ -9,7 +9,6 @@ package com.facebook.react.views.text; import android.content.Context; import android.text.Layout; import android.text.Spannable; -import com.facebook.react.bridge.ReactContext; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.common.MapBuilder; import com.facebook.react.common.annotations.VisibleForTesting; @@ -19,7 +18,6 @@ import com.facebook.react.uimanager.ReactStylesDiffMap; import com.facebook.react.uimanager.ThemedReactContext; import com.facebook.yoga.YogaMeasureMode; import java.util.Map; - import javax.annotation.Nullable; /** @@ -100,8 +98,7 @@ public class ReactTextViewManager textViewProps.getBottomPadding(), textViewProps.getTextAlign(), textBreakStrategy, - justificationMode - ); + justificationMode); } @Override diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactUnderlineSpan.java b/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactUnderlineSpan.java index 375f7dfcad1..29360376048 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactUnderlineSpan.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactUnderlineSpan.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.text; import android.text.style.UnderlineSpan; @@ -12,5 +11,4 @@ import android.text.style.UnderlineSpan; /* * Wraps {@link UnderlineSpan} as a {@link ReactSpan}. */ -public class ReactUnderlineSpan extends UnderlineSpan implements ReactSpan { -} +public class ReactUnderlineSpan extends UnderlineSpan implements ReactSpan {} diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactVirtualTextShadowNode.java b/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactVirtualTextShadowNode.java index 094db58bb44..58fd4dc7e77 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactVirtualTextShadowNode.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactVirtualTextShadowNode.java @@ -5,9 +5,7 @@ package com.facebook.react.views.text; -/** - * A virtual text node. - */ +/** A virtual text node. */ public class ReactVirtualTextShadowNode extends ReactBaseTextShadowNode { @Override @@ -15,6 +13,5 @@ public class ReactVirtualTextShadowNode extends ReactBaseTextShadowNode { return true; } - public ReactVirtualTextShadowNode() { } - + public ReactVirtualTextShadowNode() {} } diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactVirtualTextViewManager.java b/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactVirtualTextViewManager.java index 5fdee39cf4d..3f5784fa354 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactVirtualTextViewManager.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactVirtualTextViewManager.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.text; import android.view.View; @@ -20,8 +19,7 @@ import com.facebook.react.uimanager.ThemedReactContext; @ReactModule(name = ReactVirtualTextViewManager.REACT_CLASS) public class ReactVirtualTextViewManager extends BaseViewManager { - @VisibleForTesting - public static final String REACT_CLASS = "RCTVirtualText"; + @VisibleForTesting public static final String REACT_CLASS = "RCTVirtualText"; @Override public String getName() { diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/text/ShadowStyleSpan.java b/ReactAndroid/src/main/java/com/facebook/react/views/text/ShadowStyleSpan.java index 18c8be6ff4d..631cf13957e 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/text/ShadowStyleSpan.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/text/ShadowStyleSpan.java @@ -1,13 +1,11 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.text; - import android.text.TextPaint; import android.text.style.CharacterStyle; diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/text/TextAttributeProps.java b/ReactAndroid/src/main/java/com/facebook/react/views/text/TextAttributeProps.java index d4d81cbfaa6..02a15abb3aa 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/text/TextAttributeProps.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/text/TextAttributeProps.java @@ -1,10 +1,9 @@ /** * Copyright (c) 2014-present, Facebook, Inc. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.text; import android.graphics.Typeface; @@ -49,9 +48,9 @@ public class TextAttributeProps { protected float mLetterSpacingInput = Float.NaN; protected int mTextAlign = Gravity.NO_GRAVITY; protected int mTextBreakStrategy = - (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) ? 0 : Layout.BREAK_STRATEGY_HIGH_QUALITY; + (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) ? 0 : Layout.BREAK_STRATEGY_HIGH_QUALITY; protected int mJustificationMode = - (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) ? 0 : Layout.JUSTIFICATION_MODE_NONE; + (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) ? 0 : Layout.JUSTIFICATION_MODE_NONE; protected TextTransform mTextTransform = TextTransform.UNSET; protected float mTextShadowOffsetDx = 0; @@ -64,8 +63,8 @@ public class TextAttributeProps { protected boolean mIncludeFontPadding = true; /** - * mFontStyle can be {@link Typeface#NORMAL} or {@link Typeface#ITALIC}. - * mFontWeight can be {@link Typeface#NORMAL} or {@link Typeface#BOLD}. + * mFontStyle can be {@link Typeface#NORMAL} or {@link Typeface#ITALIC}. mFontWeight can be {@link + * Typeface#NORMAL} or {@link Typeface#BOLD}. */ protected int mFontStyle = UNSET; @@ -73,19 +72,18 @@ public class TextAttributeProps { /** * NB: If a font family is used that does not have a style in a certain Android version (ie. * monospace bold pre Android 5.0), that style (ie. bold) will not be inherited by nested Text - * nodes. To retain that style, you have to add it to those nodes explicitly. - * Example, Android 4.4: - * Bold Text - * Bold Text - * Bold Text + * nodes. To retain that style, you have to add it to those nodes explicitly. Example, Android + * 4.4: Bold Text Bold Text Bold + * Text * - * Not Bold Text - * Not Bold Text - * Not Bold Text + *

Not Bold Text Not Bold Text Not + * Bold Text * - * Not Bold Text - * Bold Text - * Bold Text + *

Not Bold Text Bold Text Bold Text */ protected @Nullable String mFontFamily = null; @@ -94,7 +92,6 @@ public class TextAttributeProps { private final ReactStylesDiffMap mProps; - public TextAttributeProps(ReactStylesDiffMap props) { mProps = props; setNumberOfLines(getIntProp(ViewProps.NUMBER_OF_LINES, UNSET)); @@ -105,7 +102,10 @@ public class TextAttributeProps { setFontSize(getFloatProp(ViewProps.FONT_SIZE, UNSET)); setColor(props.hasKey(ViewProps.COLOR) ? props.getInt(ViewProps.COLOR, 0) : null); setColor(props.hasKey("foregroundColor") ? props.getInt("foregroundColor", 0) : null); - setBackgroundColor(props.hasKey(ViewProps.BACKGROUND_COLOR) ? props.getInt(ViewProps.BACKGROUND_COLOR, 0) : null); + setBackgroundColor( + props.hasKey(ViewProps.BACKGROUND_COLOR) + ? props.getInt(ViewProps.BACKGROUND_COLOR, 0) + : null); setFontFamily(getStringProp(ViewProps.FONT_FAMILY)); setFontWeight(getStringProp(ViewProps.FONT_WEIGHT)); setFontStyle(getStringProp(ViewProps.FONT_STYLE)); @@ -154,9 +154,9 @@ public class TextAttributeProps { // and the height of the inline images. public float getEffectiveLineHeight() { boolean useInlineViewHeight = - !Float.isNaN(mLineHeight) - && !Float.isNaN(mHeightOfTallestInlineImage) - && mHeightOfTallestInlineImage > mLineHeight; + !Float.isNaN(mLineHeight) + && !Float.isNaN(mHeightOfTallestInlineImage) + && mHeightOfTallestInlineImage > mLineHeight; return useInlineViewHeight ? mHeightOfTallestInlineImage : mLineHeight; } @@ -183,17 +183,18 @@ public class TextAttributeProps { mLineHeight = Float.NaN; } else { mLineHeight = - mAllowFontScaling - ? PixelUtil.toPixelFromSP(lineHeight) - : PixelUtil.toPixelFromDIP(lineHeight); + mAllowFontScaling + ? PixelUtil.toPixelFromSP(lineHeight) + : PixelUtil.toPixelFromDIP(lineHeight); } } public void setLetterSpacing(float letterSpacing) { mLetterSpacingInput = letterSpacing; - mLetterSpacing = mAllowFontScaling - ? PixelUtil.toPixelFromSP(mLetterSpacingInput) - : PixelUtil.toPixelFromDIP(mLetterSpacingInput); + mLetterSpacing = + mAllowFontScaling + ? PixelUtil.toPixelFromSP(mLetterSpacingInput) + : PixelUtil.toPixelFromDIP(mLetterSpacingInput); } public void setAllowFontScaling(boolean allowFontScaling) { @@ -227,7 +228,6 @@ public class TextAttributeProps { } else { throw new JSApplicationIllegalArgumentException("Invalid textAlign: " + textAlign); } - } } @@ -235,9 +235,9 @@ public class TextAttributeProps { mFontSizeInput = fontSize; if (fontSize != UNSET) { fontSize = - mAllowFontScaling - ? (float) Math.ceil(PixelUtil.toPixelFromSP(fontSize)) - : (float) Math.ceil(PixelUtil.toPixelFromDIP(fontSize)); + mAllowFontScaling + ? (float) Math.ceil(PixelUtil.toPixelFromSP(fontSize)) + : (float) Math.ceil(PixelUtil.toPixelFromDIP(fontSize)); } mFontSize = (int) fontSize; } @@ -250,13 +250,14 @@ public class TextAttributeProps { } public void setBackgroundColor(Integer color) { - //TODO: Don't apply background color to anchor TextView since it will be applied on the View directly - //if (!isVirtualAnchor()) { - mIsBackgroundColorSet = (color != null); - if (mIsBackgroundColorSet) { - mBackgroundColor = color; - } - //} + // TODO: Don't apply background color to anchor TextView since it will be applied on the View + // directly + // if (!isVirtualAnchor()) { + mIsBackgroundColorSet = (color != null); + if (mIsBackgroundColorSet) { + mBackgroundColor = color; + } + // } } public void setFontFamily(@Nullable String fontFamily) { @@ -264,17 +265,17 @@ public class TextAttributeProps { } /** - /* This code is duplicated in ReactTextInputManager - /* TODO: Factor into a common place they can both use + * /* This code is duplicated in ReactTextInputManager /* TODO: Factor into a common place they + * can both use */ public void setFontWeight(@Nullable String fontWeightString) { int fontWeightNumeric = - fontWeightString != null ? parseNumericFontWeight(fontWeightString) : -1; + fontWeightString != null ? parseNumericFontWeight(fontWeightString) : -1; int fontWeight = UNSET; if (fontWeightNumeric >= 500 || "bold".equals(fontWeightString)) { fontWeight = Typeface.BOLD; } else if ("normal".equals(fontWeightString) - || (fontWeightNumeric != -1 && fontWeightNumeric < 500)) { + || (fontWeightNumeric != -1 && fontWeightNumeric < 500)) { fontWeight = Typeface.NORMAL; } if (fontWeight != mFontWeight) { @@ -283,8 +284,8 @@ public class TextAttributeProps { } /** - /* This code is duplicated in ReactTextInputManager - /* TODO: Factor into a common place they can both use + * /* This code is duplicated in ReactTextInputManager /* TODO: Factor into a common place they + * can both use */ public void setFontStyle(@Nullable String fontStyleString) { int fontStyle = UNSET; @@ -329,7 +330,7 @@ public class TextAttributeProps { mTextBreakStrategy = Layout.BREAK_STRATEGY_BALANCED; } else { throw new JSApplicationIllegalArgumentException( - "Invalid textBreakStrategy: " + textBreakStrategy); + "Invalid textBreakStrategy: " + textBreakStrategy); } } @@ -339,14 +340,14 @@ public class TextAttributeProps { if (offsetMap != null) { if (offsetMap.hasKey(PROP_SHADOW_OFFSET_WIDTH) - && !offsetMap.isNull(PROP_SHADOW_OFFSET_WIDTH)) { + && !offsetMap.isNull(PROP_SHADOW_OFFSET_WIDTH)) { mTextShadowOffsetDx = - PixelUtil.toPixelFromDIP(offsetMap.getDouble(PROP_SHADOW_OFFSET_WIDTH)); + PixelUtil.toPixelFromDIP(offsetMap.getDouble(PROP_SHADOW_OFFSET_WIDTH)); } if (offsetMap.hasKey(PROP_SHADOW_OFFSET_HEIGHT) - && !offsetMap.isNull(PROP_SHADOW_OFFSET_HEIGHT)) { + && !offsetMap.isNull(PROP_SHADOW_OFFSET_HEIGHT)) { mTextShadowOffsetDy = - PixelUtil.toPixelFromDIP(offsetMap.getDouble(PROP_SHADOW_OFFSET_HEIGHT)); + PixelUtil.toPixelFromDIP(offsetMap.getDouble(PROP_SHADOW_OFFSET_HEIGHT)); } } } @@ -360,7 +361,6 @@ public class TextAttributeProps { public void setTextShadowColor(int textShadowColor) { if (textShadowColor != mTextShadowColor) { mTextShadowColor = textShadowColor; - } } @@ -382,20 +382,20 @@ public class TextAttributeProps { * Return -1 if the input string is not a valid numeric fontWeight (100, 200, ..., 900), otherwise * return the weight. * - * This code is duplicated in ReactTextInputManager - * TODO: Factor into a common place they can both use + *

This code is duplicated in ReactTextInputManager TODO: Factor into a common place they can + * both use */ private static int parseNumericFontWeight(String fontWeightString) { // This should be much faster than using regex to verify input and Integer.parseInt return fontWeightString.length() == 3 - && fontWeightString.endsWith("00") - && fontWeightString.charAt(0) <= '9' - && fontWeightString.charAt(0) >= '1' - ? 100 * (fontWeightString.charAt(0) - '0') - : -1; + && fontWeightString.endsWith("00") + && fontWeightString.charAt(0) <= '9' + && fontWeightString.charAt(0) >= '1' + ? 100 * (fontWeightString.charAt(0) - '0') + : -1; } - //TODO T31905686 remove this from here and add support to RTL + // TODO T31905686 remove this from here and add support to RTL private YogaDirection getLayoutDirection() { return YogaDirection.LTR; } diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/text/TextAttributes.java b/ReactAndroid/src/main/java/com/facebook/react/views/text/TextAttributes.java index 9ebf1d83d1e..d1c33b39b72 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/text/TextAttributes.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/text/TextAttributes.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.text; import com.facebook.react.bridge.JSApplicationIllegalArgumentException; @@ -30,8 +29,7 @@ public class TextAttributes { private float mHeightOfTallestInlineViewOrImage = Float.NaN; private TextTransform mTextTransform = TextTransform.UNSET; - public TextAttributes() { - } + public TextAttributes() {} public TextAttributes applyChild(TextAttributes child) { TextAttributes result = new TextAttributes(); @@ -42,10 +40,18 @@ public class TextAttributes { result.mFontSize = !Float.isNaN(child.mFontSize) ? child.mFontSize : mFontSize; result.mLineHeight = !Float.isNaN(child.mLineHeight) ? child.mLineHeight : mLineHeight; - result.mLetterSpacing = !Float.isNaN(child.mLetterSpacing) ? child.mLetterSpacing : mLetterSpacing; - result.mMaxFontSizeMultiplier = !Float.isNaN(child.mMaxFontSizeMultiplier) ? child.mMaxFontSizeMultiplier : mMaxFontSizeMultiplier; - result.mHeightOfTallestInlineViewOrImage = !Float.isNaN(child.mHeightOfTallestInlineViewOrImage) ? child.mHeightOfTallestInlineViewOrImage : mHeightOfTallestInlineViewOrImage; - result.mTextTransform = child.mTextTransform != TextTransform.UNSET ? child.mTextTransform : mTextTransform; + result.mLetterSpacing = + !Float.isNaN(child.mLetterSpacing) ? child.mLetterSpacing : mLetterSpacing; + result.mMaxFontSizeMultiplier = + !Float.isNaN(child.mMaxFontSizeMultiplier) + ? child.mMaxFontSizeMultiplier + : mMaxFontSizeMultiplier; + result.mHeightOfTallestInlineViewOrImage = + !Float.isNaN(child.mHeightOfTallestInlineViewOrImage) + ? child.mHeightOfTallestInlineViewOrImage + : mHeightOfTallestInlineViewOrImage; + result.mTextTransform = + child.mTextTransform != TextTransform.UNSET ? child.mTextTransform : mTextTransform; return result; } @@ -91,7 +97,8 @@ public class TextAttributes { public void setMaxFontSizeMultiplier(float maxFontSizeMultiplier) { if (maxFontSizeMultiplier != 0 && maxFontSizeMultiplier < 1) { - throw new JSApplicationIllegalArgumentException("maxFontSizeMultiplier must be NaN, 0, or >= 1"); + throw new JSApplicationIllegalArgumentException( + "maxFontSizeMultiplier must be NaN, 0, or >= 1"); } mMaxFontSizeMultiplier = maxFontSizeMultiplier; } @@ -121,8 +128,8 @@ public class TextAttributes { public int getEffectiveFontSize() { float fontSize = !Float.isNaN(mFontSize) ? mFontSize : ViewDefaults.FONT_SIZE_SP; return mAllowFontScaling - ? (int) Math.ceil(PixelUtil.toPixelFromSP(fontSize, getEffectiveMaxFontSizeMultiplier())) - : (int) Math.ceil(PixelUtil.toPixelFromDIP(fontSize)); + ? (int) Math.ceil(PixelUtil.toPixelFromSP(fontSize, getEffectiveMaxFontSizeMultiplier())) + : (int) Math.ceil(PixelUtil.toPixelFromDIP(fontSize)); } public float getEffectiveLineHeight() { @@ -130,15 +137,16 @@ public class TextAttributes { return Float.NaN; } - float lineHeight = mAllowFontScaling - ? PixelUtil.toPixelFromSP(mLineHeight, getEffectiveMaxFontSizeMultiplier()) - : PixelUtil.toPixelFromDIP(mLineHeight); + float lineHeight = + mAllowFontScaling + ? PixelUtil.toPixelFromSP(mLineHeight, getEffectiveMaxFontSizeMultiplier()) + : PixelUtil.toPixelFromDIP(mLineHeight); // Take into account the requested line height // and the height of the inline images. boolean useInlineViewHeight = - !Float.isNaN(mHeightOfTallestInlineViewOrImage) - && mHeightOfTallestInlineViewOrImage > lineHeight; + !Float.isNaN(mHeightOfTallestInlineViewOrImage) + && mHeightOfTallestInlineViewOrImage > lineHeight; return useInlineViewHeight ? mHeightOfTallestInlineViewOrImage : lineHeight; } @@ -147,9 +155,10 @@ public class TextAttributes { return Float.NaN; } - float letterSpacingPixels = mAllowFontScaling - ? PixelUtil.toPixelFromSP(mLetterSpacing, getEffectiveMaxFontSizeMultiplier()) - : PixelUtil.toPixelFromDIP(mLetterSpacing); + float letterSpacingPixels = + mAllowFontScaling + ? PixelUtil.toPixelFromSP(mLetterSpacing, getEffectiveMaxFontSizeMultiplier()) + : PixelUtil.toPixelFromDIP(mLetterSpacing); // `letterSpacingPixels` and `getEffectiveFontSize` are both in pixels, // yielding an accurate em value. @@ -159,25 +168,34 @@ public class TextAttributes { // Never returns NaN public float getEffectiveMaxFontSizeMultiplier() { return !Float.isNaN(mMaxFontSizeMultiplier) - ? mMaxFontSizeMultiplier - : DEFAULT_MAX_FONT_SIZE_MULTIPLIER; + ? mMaxFontSizeMultiplier + : DEFAULT_MAX_FONT_SIZE_MULTIPLIER; } public String toString() { - return ( - "TextAttributes {" - + "\n getAllowFontScaling(): " + getAllowFontScaling() - + "\n getFontSize(): " + getFontSize() - + "\n getEffectiveFontSize(): " + getEffectiveFontSize() - + "\n getHeightOfTallestInlineViewOrImage(): " + getHeightOfTallestInlineViewOrImage() - + "\n getLetterSpacing(): " + getLetterSpacing() - + "\n getEffectiveLetterSpacing(): " + getEffectiveLetterSpacing() - + "\n getLineHeight(): " + getLineHeight() - + "\n getEffectiveLineHeight(): " + getEffectiveLineHeight() - + "\n getTextTransform(): " + getTextTransform() - + "\n getMaxFontSizeMultiplier(): " + getMaxFontSizeMultiplier() - + "\n getEffectiveMaxFontSizeMultiplier(): " + getEffectiveMaxFontSizeMultiplier() - + "\n}" - ); + return ("TextAttributes {" + + "\n getAllowFontScaling(): " + + getAllowFontScaling() + + "\n getFontSize(): " + + getFontSize() + + "\n getEffectiveFontSize(): " + + getEffectiveFontSize() + + "\n getHeightOfTallestInlineViewOrImage(): " + + getHeightOfTallestInlineViewOrImage() + + "\n getLetterSpacing(): " + + getLetterSpacing() + + "\n getEffectiveLetterSpacing(): " + + getEffectiveLetterSpacing() + + "\n getLineHeight(): " + + getLineHeight() + + "\n getEffectiveLineHeight(): " + + getEffectiveLineHeight() + + "\n getTextTransform(): " + + getTextTransform() + + "\n getMaxFontSizeMultiplier(): " + + getMaxFontSizeMultiplier() + + "\n getEffectiveMaxFontSizeMultiplier(): " + + getEffectiveMaxFontSizeMultiplier() + + "\n}"); } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/text/TextInlineImageSpan.java b/ReactAndroid/src/main/java/com/facebook/react/views/text/TextInlineImageSpan.java index c986d7348c4..fa85c69e121 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/text/TextInlineImageSpan.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/text/TextInlineImageSpan.java @@ -1,78 +1,58 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ +package com.facebook.react.views.text; - package com.facebook.react.views.text; +import android.graphics.drawable.Drawable; +import android.text.Spannable; +import android.text.style.ReplacementSpan; +import android.view.View; +import android.widget.TextView; +import javax.annotation.Nullable; - import javax.annotation.Nullable; +/** Base class for inline image spans. */ +public abstract class TextInlineImageSpan extends ReplacementSpan implements ReactSpan { - import android.graphics.drawable.Drawable; - import android.text.Spannable; - import android.text.style.ReplacementSpan; - import android.view.View; - import android.widget.TextView; + /** + * For TextInlineImageSpan we need to update the Span to know that the window is attached and the + * TextView that we will set as the callback on the Drawable. + * + * @param spannable The spannable that may contain TextInlineImageSpans + * @param view The view which will be set as the callback for the Drawable + */ + public static void possiblyUpdateInlineImageSpans(Spannable spannable, TextView view) { + TextInlineImageSpan[] spans = + spannable.getSpans(0, spannable.length(), TextInlineImageSpan.class); + for (TextInlineImageSpan span : spans) { + span.onAttachedToWindow(); + span.setTextView(view); + } + } - /** - * Base class for inline image spans. - */ - public abstract class TextInlineImageSpan extends ReplacementSpan implements ReactSpan { + /** Get the drawable that is span represents. */ + public abstract @Nullable Drawable getDrawable(); - /** - * For TextInlineImageSpan we need to update the Span to know that the window is attached and - * the TextView that we will set as the callback on the Drawable. - * - * @param spannable The spannable that may contain TextInlineImageSpans - * @param view The view which will be set as the callback for the Drawable - */ - public static void possiblyUpdateInlineImageSpans(Spannable spannable, TextView view) { - TextInlineImageSpan[] spans = - spannable.getSpans(0, spannable.length(), TextInlineImageSpan.class); - for (TextInlineImageSpan span : spans) { - span.onAttachedToWindow(); - span.setTextView(view); - } - } + /** Called by the text view from {@link View#onDetachedFromWindow()}, */ + public abstract void onDetachedFromWindow(); - /** - * Get the drawable that is span represents. - */ - public abstract @Nullable Drawable getDrawable(); + /** Called by the text view from {@link View#onStartTemporaryDetach()}. */ + public abstract void onStartTemporaryDetach(); - /** - * Called by the text view from {@link View#onDetachedFromWindow()}, - */ - public abstract void onDetachedFromWindow(); + /** Called by the text view from {@link View#onAttachedToWindow()}. */ + public abstract void onAttachedToWindow(); - /** - * Called by the text view from {@link View#onStartTemporaryDetach()}. - */ - public abstract void onStartTemporaryDetach(); + /** Called by the text view from {@link View#onFinishTemporaryDetach()}. */ + public abstract void onFinishTemporaryDetach(); - /** - * Called by the text view from {@link View#onAttachedToWindow()}. - */ - public abstract void onAttachedToWindow(); + /** Set the textview that will contain this span. */ + public abstract void setTextView(TextView textView); - /** - * Called by the text view from {@link View#onFinishTemporaryDetach()}. - */ - public abstract void onFinishTemporaryDetach(); + /** Get the width of the span. */ + public abstract int getWidth(); - /** - * Set the textview that will contain this span. - */ - public abstract void setTextView(TextView textView); - - /** - * Get the width of the span. - */ - public abstract int getWidth(); - - /** - * Get the height of the span. - */ - public abstract int getHeight(); - } + /** Get the height of the span. */ + public abstract int getHeight(); +} diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/text/TextInlineViewPlaceholderSpan.java b/ReactAndroid/src/main/java/com/facebook/react/views/text/TextInlineViewPlaceholderSpan.java index 9e6726efe3d..d957475a904 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/text/TextInlineViewPlaceholderSpan.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/text/TextInlineViewPlaceholderSpan.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.text; import android.graphics.Canvas; @@ -39,8 +38,7 @@ public class TextInlineViewPlaceholderSpan extends ReplacementSpan implements Re } @Override - public int getSize( - Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) { + public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) { // NOTE: This getSize code is copied from DynamicDrawableSpan and modified to not use a Drawable if (fm != null) { @@ -56,6 +54,13 @@ public class TextInlineViewPlaceholderSpan extends ReplacementSpan implements Re @Override public void draw( - Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) { - } + Canvas canvas, + CharSequence text, + int start, + int end, + float x, + int top, + int y, + int bottom, + Paint paint) {} } diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/text/TextLayoutManager.java b/ReactAndroid/src/main/java/com/facebook/react/views/text/TextLayoutManager.java index 2faecc18cff..89d1b39c521 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/text/TextLayoutManager.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/text/TextLayoutManager.java @@ -1,10 +1,9 @@ /** * Copyright (c) 2014-present, Facebook, Inc. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.text; import static com.facebook.react.views.text.TextAttributeProps.UNSET; @@ -29,9 +28,7 @@ import com.facebook.yoga.YogaMeasureOutput; import java.util.ArrayList; import java.util.List; -/** - * Class responsible of creating {@link Spanned} object for the JS representation of Text - */ +/** Class responsible of creating {@link Spanned} object for the JS representation of Text */ public class TextLayoutManager { // It's important to pass the ANTI_ALIAS_FLAG flag to the constructor rather than setting it @@ -56,47 +53,46 @@ public class TextLayoutManager { int start = sb.length(); // ReactRawText - TextAttributeProps textAttributes = new TextAttributeProps(new ReactStylesDiffMap(fragment.getMap("textAttributes"))); + TextAttributeProps textAttributes = + new TextAttributeProps(new ReactStylesDiffMap(fragment.getMap("textAttributes"))); - sb.append(TextTransform.apply( - fragment.getString("string"), - textAttributes.mTextTransform)); + sb.append(TextTransform.apply(fragment.getString("string"), textAttributes.mTextTransform)); // TODO: add support for TextInlineImage and BaseText int end = sb.length(); if (end >= start) { if (textAttributes.mIsColorSet) { - ops.add(new SetSpanOperation(start, end, new ReactForegroundColorSpan(textAttributes.mColor))); + ops.add( + new SetSpanOperation( + start, end, new ReactForegroundColorSpan(textAttributes.mColor))); } if (textAttributes.mIsBackgroundColorSet) { ops.add( - new SetSpanOperation( - start, end, new ReactBackgroundColorSpan(textAttributes.mBackgroundColor))); + new SetSpanOperation( + start, end, new ReactBackgroundColorSpan(textAttributes.mBackgroundColor))); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { if (!Float.isNaN(textAttributes.mLetterSpacing)) { - ops.add(new SetSpanOperation( - start, - end, - new CustomLetterSpacingSpan(textAttributes.mLetterSpacing))); + ops.add( + new SetSpanOperation( + start, end, new CustomLetterSpacingSpan(textAttributes.mLetterSpacing))); } } ops.add( - new SetSpanOperation( - start, end, new ReactAbsoluteSizeSpan(textAttributes.mFontSize))); + new SetSpanOperation(start, end, new ReactAbsoluteSizeSpan(textAttributes.mFontSize))); if (textAttributes.mFontStyle != UNSET - || textAttributes.mFontWeight != UNSET - || textAttributes.mFontFamily != null) { + || textAttributes.mFontWeight != UNSET + || textAttributes.mFontFamily != null) { ops.add( - new SetSpanOperation( - start, - end, - new CustomStyleSpan( - textAttributes.mFontStyle, - textAttributes.mFontWeight, - textAttributes.mFontFamily, - context.getAssets()))); + new SetSpanOperation( + start, + end, + new CustomStyleSpan( + textAttributes.mFontStyle, + textAttributes.mFontWeight, + textAttributes.mFontFamily, + context.getAssets()))); } if (textAttributes.mIsUnderlineTextDecorationSet) { ops.add(new SetSpanOperation(start, end, new ReactUnderlineSpan())); @@ -106,19 +102,19 @@ public class TextLayoutManager { } if (textAttributes.mTextShadowOffsetDx != 0 || textAttributes.mTextShadowOffsetDy != 0) { ops.add( - new SetSpanOperation( - start, - end, - new ShadowStyleSpan( - textAttributes.mTextShadowOffsetDx, - textAttributes.mTextShadowOffsetDy, - textAttributes.mTextShadowRadius, - textAttributes.mTextShadowColor))); + new SetSpanOperation( + start, + end, + new ShadowStyleSpan( + textAttributes.mTextShadowOffsetDx, + textAttributes.mTextShadowOffsetDy, + textAttributes.mTextShadowRadius, + textAttributes.mTextShadowColor))); } if (!Float.isNaN(textAttributes.getEffectiveLineHeight())) { ops.add( - new SetSpanOperation( - start, end, new CustomLineHeightSpan(textAttributes.getEffectiveLineHeight()))); + new SetSpanOperation( + start, end, new CustomLineHeightSpan(textAttributes.getEffectiveLineHeight()))); } int reactTag = fragment.getInt("reactTag"); @@ -128,14 +124,13 @@ public class TextLayoutManager { } protected static Spannable getOrCreateSpannableForText( - Context context, - ReadableMap attributedString) { + Context context, ReadableMap attributedString) { Spannable preparedSpannableText; String attributedStringPayload = attributedString.toString(); synchronized (sSpannableCacheLock) { preparedSpannableText = sSpannableCache.get(attributedStringPayload); - //TODO: T31905686 implement proper equality of attributedStrings + // TODO: T31905686 implement proper equality of attributedStrings if (preparedSpannableText != null) { return preparedSpannableText; } @@ -149,8 +144,7 @@ public class TextLayoutManager { } private static Spannable createSpannableFromAttributedString( - Context context, - ReadableMap attributedString) { + Context context, ReadableMap attributedString) { SpannableStringBuilder sb = new SpannableStringBuilder(); @@ -196,71 +190,75 @@ public class TextLayoutManager { } Spanned text = preparedSpannableText; BoringLayout.Metrics boring = BoringLayout.isBoring(text, textPaint); - float desiredWidth = boring == null ? - Layout.getDesiredWidth(text, textPaint) : Float.NaN; + float desiredWidth = boring == null ? Layout.getDesiredWidth(text, textPaint) : Float.NaN; // technically, width should never be negative, but there is currently a bug in boolean unconstrainedWidth = widthYogaMeasureMode == YogaMeasureMode.UNDEFINED || width < 0; Layout layout; - if (boring == null && - (unconstrainedWidth || - (!YogaConstants.isUndefined(desiredWidth) && desiredWidth <= width))) { + if (boring == null + && (unconstrainedWidth + || (!YogaConstants.isUndefined(desiredWidth) && desiredWidth <= width))) { // Is used when the width is not known and the text is not boring, ie. if it contains // unicode characters. int hintWidth = (int) Math.ceil(desiredWidth); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { - layout = new StaticLayout( - text, - textPaint, - hintWidth, - Layout.Alignment.ALIGN_NORMAL, - 1.f, - 0.f, - includeFontPadding); + layout = + new StaticLayout( + text, + textPaint, + hintWidth, + Layout.Alignment.ALIGN_NORMAL, + 1.f, + 0.f, + includeFontPadding); } else { - layout = StaticLayout.Builder.obtain(text, 0, text.length(), textPaint, hintWidth) - .setAlignment(Layout.Alignment.ALIGN_NORMAL) - .setLineSpacing(0.f, 1.f) - .setIncludePad(includeFontPadding) - .setBreakStrategy(textBreakStrategy) - .setHyphenationFrequency(Layout.HYPHENATION_FREQUENCY_NORMAL) - .build(); + layout = + StaticLayout.Builder.obtain(text, 0, text.length(), textPaint, hintWidth) + .setAlignment(Layout.Alignment.ALIGN_NORMAL) + .setLineSpacing(0.f, 1.f) + .setIncludePad(includeFontPadding) + .setBreakStrategy(textBreakStrategy) + .setHyphenationFrequency(Layout.HYPHENATION_FREQUENCY_NORMAL) + .build(); } } else if (boring != null && (unconstrainedWidth || boring.width <= width)) { // Is used for single-line, boring text when the width is either unknown or bigger // than the width of the text. - layout = BoringLayout.make( - text, - textPaint, - boring.width, - Layout.Alignment.ALIGN_NORMAL, - 1.f, - 0.f, - boring, - includeFontPadding); + layout = + BoringLayout.make( + text, + textPaint, + boring.width, + Layout.Alignment.ALIGN_NORMAL, + 1.f, + 0.f, + boring, + includeFontPadding); } else { // Is used for multiline, boring text and the width is known. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { - layout = new StaticLayout( - text, - textPaint, - (int) width, - Layout.Alignment.ALIGN_NORMAL, - 1.f, - 0.f, - includeFontPadding); + layout = + new StaticLayout( + text, + textPaint, + (int) width, + Layout.Alignment.ALIGN_NORMAL, + 1.f, + 0.f, + includeFontPadding); } else { - layout = StaticLayout.Builder.obtain(text, 0, text.length(), textPaint, (int) width) - .setAlignment(Layout.Alignment.ALIGN_NORMAL) - .setLineSpacing(0.f, 1.f) - .setIncludePad(includeFontPadding) - .setBreakStrategy(textBreakStrategy) - .setHyphenationFrequency(Layout.HYPHENATION_FREQUENCY_NORMAL) - .build(); + layout = + StaticLayout.Builder.obtain(text, 0, text.length(), textPaint, (int) width) + .setAlignment(Layout.Alignment.ALIGN_NORMAL) + .setLineSpacing(0.f, 1.f) + .setIncludePad(includeFontPadding) + .setBreakStrategy(textBreakStrategy) + .setHyphenationFrequency(Layout.HYPHENATION_FREQUENCY_NORMAL) + .build(); } } @@ -271,8 +269,8 @@ public class TextLayoutManager { width = layout.getWidth(); if (maximumNumberOfLines != UNSET - && maximumNumberOfLines != 0 - && maximumNumberOfLines < layout.getLineCount()) { + && maximumNumberOfLines != 0 + && maximumNumberOfLines < layout.getLineCount()) { height = layout.getLineBottom(maximumNumberOfLines - 1); } else { height = layout.getHeight(); diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/text/TextTransform.java b/ReactAndroid/src/main/java/com/facebook/react/views/text/TextTransform.java index 515e5bb4134..1278054108b 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/text/TextTransform.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/text/TextTransform.java @@ -1,19 +1,20 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.text; import java.text.BreakIterator; -/** - * Types of text transforms for CustomTextTransformSpan - */ +/** Types of text transforms for CustomTextTransformSpan */ public enum TextTransform { - NONE, UPPERCASE, LOWERCASE, CAPITALIZE, UNSET; + NONE, + UPPERCASE, + LOWERCASE, + CAPITALIZE, + UNSET; public static String apply(String text, TextTransform textTransform) { if (text == null) { @@ -21,7 +22,7 @@ public enum TextTransform { } String transformed; - switch(textTransform) { + switch (textTransform) { case UPPERCASE: transformed = text.toUpperCase(); break; diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/text/frescosupport/FrescoBasedReactTextInlineImageShadowNode.java b/ReactAndroid/src/main/java/com/facebook/react/views/text/frescosupport/FrescoBasedReactTextInlineImageShadowNode.java index 9a065eb203f..1b168d21361 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/text/frescosupport/FrescoBasedReactTextInlineImageShadowNode.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/text/frescosupport/FrescoBasedReactTextInlineImageShadowNode.java @@ -1,38 +1,29 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.text.frescosupport; -import com.facebook.react.uimanager.LayoutShadowNode; -import javax.annotation.Nullable; - -import java.util.Locale; - import android.content.Context; import android.content.res.Resources; import android.net.Uri; - import com.facebook.common.util.UriUtil; -import com.facebook.yoga.YogaConstants; import com.facebook.drawee.controller.AbstractDraweeControllerBuilder; import com.facebook.react.bridge.Dynamic; import com.facebook.react.bridge.JSApplicationIllegalArgumentException; import com.facebook.react.bridge.ReadableArray; -import com.facebook.react.bridge.ReadableType; -import com.facebook.react.uimanager.ViewProps; import com.facebook.react.bridge.ReadableMap; +import com.facebook.react.bridge.ReadableType; import com.facebook.react.uimanager.annotations.ReactProp; import com.facebook.react.views.text.ReactTextInlineImageShadowNode; import com.facebook.react.views.text.TextInlineImageSpan; +import com.facebook.yoga.YogaConstants; +import java.util.Locale; +import javax.annotation.Nullable; -/** - * Shadow node that represents an inline image. Loading is done using Fresco. - * - */ +/** Shadow node that represents an inline image. Loading is done using Fresco. */ public class FrescoBasedReactTextInlineImageShadowNode extends ReactTextInlineImageShadowNode { private @Nullable Uri mUri; @@ -44,8 +35,7 @@ public class FrescoBasedReactTextInlineImageShadowNode extends ReactTextInlineIm private int mTintColor = 0; public FrescoBasedReactTextInlineImageShadowNode( - AbstractDraweeControllerBuilder draweeControllerBuilder, - @Nullable Object callerContext) { + AbstractDraweeControllerBuilder draweeControllerBuilder, @Nullable Object callerContext) { mDraweeControllerBuilder = draweeControllerBuilder; mCallerContext = callerContext; } @@ -53,7 +43,7 @@ public class FrescoBasedReactTextInlineImageShadowNode extends ReactTextInlineIm @ReactProp(name = "src") public void setSource(@Nullable ReadableArray sources) { final String source = - (sources == null || sources.size() == 0) ? null : sources.getMap(0).getString("uri"); + (sources == null || sources.size() == 0) ? null : sources.getMap(0).getString("uri"); Uri uri = null; if (source != null) { try { @@ -85,9 +75,7 @@ public class FrescoBasedReactTextInlineImageShadowNode extends ReactTextInlineIm mTintColor = tintColor; } - /** - * Besides width/height, all other layout props on inline images are ignored - */ + /** Besides width/height, all other layout props on inline images are ignored */ @Override public void setWidth(Dynamic width) { if (width.getType() == ReadableType.Number) { @@ -107,7 +95,7 @@ public class FrescoBasedReactTextInlineImageShadowNode extends ReactTextInlineIm "Inline images must not have percentage based height"); } } - + public @Nullable Uri getUri() { return mUri; } @@ -122,14 +110,11 @@ public class FrescoBasedReactTextInlineImageShadowNode extends ReactTextInlineIm return null; } name = name.toLowerCase(Locale.getDefault()).replace("-", "_"); - int resId = context.getResources().getIdentifier( - name, - "drawable", - context.getPackageName()); + int resId = context.getResources().getIdentifier(name, "drawable", context.getPackageName()); return new Uri.Builder() - .scheme(UriUtil.LOCAL_RESOURCE_SCHEME) - .path(String.valueOf(resId)) - .build(); + .scheme(UriUtil.LOCAL_RESOURCE_SCHEME) + .path(String.valueOf(resId)) + .build(); } @Override @@ -143,14 +128,14 @@ public class FrescoBasedReactTextInlineImageShadowNode extends ReactTextInlineIm int width = (int) Math.ceil(mWidth); int height = (int) Math.ceil(mHeight); return new FrescoBasedReactTextInlineImageSpan( - resources, - height, - width, - mTintColor, - getUri(), - getHeaders(), - getDraweeControllerBuilder(), - getCallerContext()); + resources, + height, + width, + mTintColor, + getUri(), + getHeaders(), + getDraweeControllerBuilder(), + getCallerContext()); } public AbstractDraweeControllerBuilder getDraweeControllerBuilder() { diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/text/frescosupport/FrescoBasedReactTextInlineImageSpan.java b/ReactAndroid/src/main/java/com/facebook/react/views/text/frescosupport/FrescoBasedReactTextInlineImageSpan.java index 30dd1bb63a8..428d22f9358 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/text/frescosupport/FrescoBasedReactTextInlineImageSpan.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/text/frescosupport/FrescoBasedReactTextInlineImageSpan.java @@ -1,24 +1,18 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.text.frescosupport; -import android.graphics.Color; -import android.graphics.PorterDuff; -import com.facebook.react.uimanager.PixelUtil; -import javax.annotation.Nullable; - import android.content.res.Resources; import android.graphics.Canvas; import android.graphics.Paint; +import android.graphics.PorterDuff; import android.graphics.drawable.Drawable; import android.net.Uri; import android.widget.TextView; - import com.facebook.drawee.controller.AbstractDraweeControllerBuilder; import com.facebook.drawee.generic.GenericDraweeHierarchy; import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder; @@ -27,19 +21,21 @@ import com.facebook.drawee.view.DraweeHolder; import com.facebook.imagepipeline.request.ImageRequest; import com.facebook.imagepipeline.request.ImageRequestBuilder; import com.facebook.react.bridge.ReadableMap; -import com.facebook.react.views.text.TextInlineImageSpan; import com.facebook.react.modules.fresco.ReactNetworkImageRequest; +import com.facebook.react.uimanager.PixelUtil; +import com.facebook.react.views.text.TextInlineImageSpan; +import javax.annotation.Nullable; /** - * FrescoBasedTextInlineImageSpan is a span for Images that are inside . It computes - * its size based on the input size. When it is time to draw, it will use the Fresco framework to - * get the right Drawable and let that draw. + * FrescoBasedTextInlineImageSpan is a span for Images that are inside . It computes its size + * based on the input size. When it is time to draw, it will use the Fresco framework to get the + * right Drawable and let that draw. * - * Since Fresco needs to callback to the TextView that contains this, in the ViewManager, you must - * tell the Span about the TextView + *

Since Fresco needs to callback to the TextView that contains this, in the ViewManager, you + * must tell the Span about the TextView * - * Note: It borrows code from DynamicDrawableSpan and if that code updates how it computes size or - * draws, we need to update this as well. + *

Note: It borrows code from DynamicDrawableSpan and if that code updates how it computes size + * or draws, we need to update this as well. */ public class FrescoBasedReactTextInlineImageSpan extends TextInlineImageSpan { @@ -65,23 +61,19 @@ public class FrescoBasedReactTextInlineImageSpan extends TextInlineImageSpan { ReadableMap headers, AbstractDraweeControllerBuilder draweeControllerBuilder, @Nullable Object callerContext) { - mDraweeHolder = new DraweeHolder( - GenericDraweeHierarchyBuilder.newInstance(resources) - .build() - ); + mDraweeHolder = new DraweeHolder(GenericDraweeHierarchyBuilder.newInstance(resources).build()); mDraweeControllerBuilder = draweeControllerBuilder; mCallerContext = callerContext; mTintColor = tintColor; mUri = (uri != null) ? uri : Uri.EMPTY; mHeaders = headers; - mWidth = (int)(PixelUtil.toPixelFromDIP(width)); - mHeight = (int)(PixelUtil.toPixelFromDIP(height)); - + mWidth = (int) (PixelUtil.toPixelFromDIP(width)); + mHeight = (int) (PixelUtil.toPixelFromDIP(height)); } /** - * The ReactTextView that holds this ImageSpan is responsible for passing these methods on so - * that we can do proper lifetime management for Fresco + * The ReactTextView that holds this ImageSpan is responsible for passing these methods on so that + * we can do proper lifetime management for Fresco */ public void onDetachedFromWindow() { mDraweeHolder.onDetach(); @@ -104,8 +96,7 @@ public class FrescoBasedReactTextInlineImageSpan extends TextInlineImageSpan { } @Override - public int getSize( - Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) { + public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) { // NOTE: This getSize code is copied from DynamicDrawableSpan and modified to not use a Drawable if (fm != null) { @@ -136,24 +127,25 @@ public class FrescoBasedReactTextInlineImageSpan extends TextInlineImageSpan { Paint paint) { if (mDrawable == null) { ImageRequestBuilder imageRequestBuilder = ImageRequestBuilder.newBuilderWithSource(mUri); - ImageRequest imageRequest = ReactNetworkImageRequest.fromBuilderWithHeaders(imageRequestBuilder, mHeaders); + ImageRequest imageRequest = + ReactNetworkImageRequest.fromBuilderWithHeaders(imageRequestBuilder, mHeaders); - DraweeController draweeController = mDraweeControllerBuilder - .reset() - .setOldController(mDraweeHolder.getController()) - .setCallerContext(mCallerContext) - .setImageRequest(imageRequest) - .build(); + DraweeController draweeController = + mDraweeControllerBuilder + .reset() + .setOldController(mDraweeHolder.getController()) + .setCallerContext(mCallerContext) + .setImageRequest(imageRequest) + .build(); mDraweeHolder.setController(draweeController); mDraweeControllerBuilder.reset(); mDrawable = mDraweeHolder.getTopLevelDrawable(); mDrawable.setBounds(0, 0, mWidth, mHeight); - if(mTintColor != 0) { + if (mTintColor != 0) { mDrawable.setColorFilter(mTintColor, PorterDuff.Mode.SRC_IN); } mDrawable.setCallback(mTextView); - } // NOTE: This drawing code is copied from DynamicDrawableSpan @@ -161,8 +153,8 @@ public class FrescoBasedReactTextInlineImageSpan extends TextInlineImageSpan { canvas.save(); // Align to center - int fontHeight = (int)(paint.descent() - paint.ascent()); - int centerY = y + (int)paint.descent() - fontHeight / 2; + int fontHeight = (int) (paint.descent() - paint.ascent()); + int centerY = y + (int) paint.descent() - fontHeight / 2; int transY = centerY - (mDrawable.getBounds().bottom - mDrawable.getBounds().top) / 2; canvas.translate(x, transY); diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/text/frescosupport/FrescoBasedReactTextInlineImageViewManager.java b/ReactAndroid/src/main/java/com/facebook/react/views/text/frescosupport/FrescoBasedReactTextInlineImageViewManager.java index 7192982a0eb..429350ccf95 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/text/frescosupport/FrescoBasedReactTextInlineImageViewManager.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/text/frescosupport/FrescoBasedReactTextInlineImageViewManager.java @@ -1,21 +1,18 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.text.frescosupport; -import javax.annotation.Nullable; - import android.view.View; - import com.facebook.drawee.backends.pipeline.Fresco; import com.facebook.drawee.controller.AbstractDraweeControllerBuilder; import com.facebook.react.module.annotations.ReactModule; import com.facebook.react.uimanager.ThemedReactContext; import com.facebook.react.uimanager.ViewManager; +import javax.annotation.Nullable; /** * Manages Images embedded in Text nodes using Fresco. Since they are used only as a virtual nodes @@ -23,7 +20,7 @@ import com.facebook.react.uimanager.ViewManager; */ @ReactModule(name = FrescoBasedReactTextInlineImageViewManager.REACT_CLASS) public class FrescoBasedReactTextInlineImageViewManager - extends ViewManager { + extends ViewManager { public static final String REACT_CLASS = "RCTTextInlineImage"; @@ -35,8 +32,8 @@ public class FrescoBasedReactTextInlineImageViewManager } public FrescoBasedReactTextInlineImageViewManager( - @Nullable AbstractDraweeControllerBuilder draweeControllerBuilder, - @Nullable Object callerContext) { + @Nullable AbstractDraweeControllerBuilder draweeControllerBuilder, + @Nullable Object callerContext) { mDraweeControllerBuilder = draweeControllerBuilder; mCallerContext = callerContext; } @@ -54,11 +51,10 @@ public class FrescoBasedReactTextInlineImageViewManager @Override public FrescoBasedReactTextInlineImageShadowNode createShadowNodeInstance() { return new FrescoBasedReactTextInlineImageShadowNode( - (mDraweeControllerBuilder != null) ? - mDraweeControllerBuilder : - Fresco.newDraweeControllerBuilder(), - mCallerContext - ); + (mDraweeControllerBuilder != null) + ? mDraweeControllerBuilder + : Fresco.newDraweeControllerBuilder(), + mCallerContext); } @Override @@ -67,6 +63,5 @@ public class FrescoBasedReactTextInlineImageViewManager } @Override - public void updateExtraData(View root, Object extraData) { - } + public void updateExtraData(View root, Object extraData) {} } diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ContentSizeWatcher.java b/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ContentSizeWatcher.java index b2b94dd41b1..d1a4990ae70 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ContentSizeWatcher.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ContentSizeWatcher.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.textinput; public interface ContentSizeWatcher { diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactContentSizeChangedEvent.java b/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactContentSizeChangedEvent.java index 9c3ef1c0d33..1f1a03ec710 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactContentSizeChangedEvent.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactContentSizeChangedEvent.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.textinput; import com.facebook.react.bridge.Arguments; @@ -12,9 +11,7 @@ import com.facebook.react.bridge.WritableMap; import com.facebook.react.uimanager.events.Event; import com.facebook.react.uimanager.events.RCTEventEmitter; -/** - * Event emitted by EditText native view when content size changes. - */ +/** Event emitted by EditText native view when content size changes. */ public class ReactContentSizeChangedEvent extends Event { public static final String EVENT_NAME = "topContentSizeChange"; @@ -22,10 +19,7 @@ public class ReactContentSizeChangedEvent extends Event { private float mContentWidth; private float mContentHeight; - public ReactContentSizeChangedEvent( - int viewId, - float contentSizeWidth, - float contentSizeHeight) { + public ReactContentSizeChangedEvent(int viewId, float contentSizeWidth, float contentSizeHeight) { super(viewId); mContentWidth = contentSizeWidth; mContentHeight = contentSizeHeight; diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactEditText.java b/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactEditText.java index 94f346ec40d..b86fc5067ae 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactEditText.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactEditText.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.textinput; import android.content.Context; @@ -17,8 +16,8 @@ import android.text.Editable; import android.text.InputType; import android.text.SpannableStringBuilder; import android.text.Spanned; -import android.text.TextWatcher; import android.text.TextUtils; +import android.text.TextWatcher; import android.text.method.KeyListener; import android.text.method.QwertyKeyListener; import android.util.TypedValue; @@ -48,12 +47,12 @@ import javax.annotation.Nullable; * A wrapper around the EditText that lets us better control what happens when an EditText gets * focused or blurred, and when to display the soft keyboard and when not to. * - * ReactEditTexts have setFocusableInTouchMode set to false automatically because touches on the - * EditText are managed on the JS side. This also removes the nasty side effect that EditTexts - * have, which is that focus is always maintained on one of the EditTexts. + *

ReactEditTexts have setFocusableInTouchMode set to false automatically because touches on the + * EditText are managed on the JS side. This also removes the nasty side effect that EditTexts have, + * which is that focus is always maintained on one of the EditTexts. * - * The wrapper stops the EditText from triggering *TextChanged events, in the case where JS - * has called this explicitly. This is the default behavior on other platforms as well. + *

The wrapper stops the EditText from triggering *TextChanged events, in the case where JS has + * called this explicitly. This is the default behavior on other platforms as well. * VisibleForTesting from {@link TextInputEventsTestCase}. */ public class ReactEditText extends EditText { @@ -94,8 +93,9 @@ public class ReactEditText extends EditText { setFocusableInTouchMode(false); mReactBackgroundManager = new ReactViewBackgroundManager(this); - mInputMethodManager = (InputMethodManager) - Assertions.assertNotNull(getContext().getSystemService(Context.INPUT_METHOD_SERVICE)); + mInputMethodManager = + (InputMethodManager) + Assertions.assertNotNull(getContext().getSystemService(Context.INPUT_METHOD_SERVICE)); mDefaultGravityHorizontal = getGravity() & (Gravity.HORIZONTAL_GRAVITY_MASK | Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK); mDefaultGravityVertical = getGravity() & Gravity.VERTICAL_GRAVITY_MASK; @@ -119,20 +119,22 @@ public class ReactEditText extends EditText { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && Build.VERSION.SDK_INT <= Build.VERSION_CODES.O_MR1) { setLayerType(View.LAYER_TYPE_SOFTWARE, null); - } + } - ViewCompat.setAccessibilityDelegate(this, new AccessibilityDelegateCompat() { - @Override - public boolean performAccessibilityAction(View host, int action, Bundle args) { - if (action == AccessibilityNodeInfo.ACTION_CLICK) { - mShouldAllowFocus = true; - requestFocus(); - mShouldAllowFocus = false; - return true; - } - return super.performAccessibilityAction(host, action, args); - } - }); + ViewCompat.setAccessibilityDelegate( + this, + new AccessibilityDelegateCompat() { + @Override + public boolean performAccessibilityAction(View host, int action, Bundle args) { + if (action == AccessibilityNodeInfo.ACTION_CLICK) { + mShouldAllowFocus = true; + requestFocus(); + mShouldAllowFocus = false; + return true; + } + return super.performAccessibilityAction(host, action, args); + } + }); } // After the text changes inside an EditText, TextView checks if a layout() has been requested. @@ -162,10 +164,10 @@ public class ReactEditText extends EditText { break; case MotionEvent.ACTION_MOVE: if (mDetectScrollMovement) { - if (!canScrollVertically(-1) && - !canScrollVertically(1) && - !canScrollHorizontally(-1) && - !canScrollHorizontally(1)) { + if (!canScrollVertically(-1) + && !canScrollVertically(1) + && !canScrollHorizontally(-1) + && !canScrollHorizontally(1)) { // We cannot scroll, let parent views take care of these touches. this.getParent().requestDisallowInterceptTouchEvent(false); } @@ -201,7 +203,8 @@ public class ReactEditText extends EditText { ReactContext reactContext = (ReactContext) getContext(); InputConnection inputConnection = super.onCreateInputConnection(outAttrs); if (inputConnection != null && mOnKeyPress) { - inputConnection = new ReactEditTextInputConnectionWrapper(inputConnection, reactContext, this); + inputConnection = + new ReactEditTextInputConnectionWrapper(inputConnection, reactContext, this); } if (isMultiline() && getBlurOnSubmit()) { @@ -291,8 +294,7 @@ public class ReactEditText extends EditText { } @Override - protected void onFocusChanged( - boolean focused, int direction, Rect previouslyFocusedRect) { + protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { super.onFocusChanged(focused, direction, previouslyFocusedRect); if (focused && mSelectionWatcher != null) { mSelectionWatcher.onSelectionChanged(getSelectionStart(), getSelectionEnd()); @@ -364,8 +366,10 @@ public class ReactEditText extends EditText { super.setTypeface(tf); /** - * If set forces multiline on input, because of a restriction on Android source that enables multiline only for inputs of type Text and Multiline on method {@link android.widget.TextView#isMultilineInputType(int)}} - * Source: {@Link TextView.java} + * If set forces multiline on input, because of a restriction on Android source that enables + * multiline only for inputs of type Text and Multiline on method {@link + * android.widget.TextView#isMultilineInputType(int)}} Source: {@Link TextView.java} */ if (isMultiline()) { setSingleLine(false); @@ -396,8 +400,7 @@ public class ReactEditText extends EditText { // VisibleForTesting from {@link TextInputEventsTestCase}. public void maybeSetText(ReactTextUpdate reactTextUpdate) { - if( isSecureText() && - TextUtils.equals(getText(), reactTextUpdate.getText())) { + if (isSecureText() && TextUtils.equals(getText(), reactTextUpdate.getText())) { return; } @@ -447,8 +450,8 @@ public class ReactEditText extends EditText { getText().removeSpan(spans[spanIdx]); } - if ((getText().getSpanFlags(spans[spanIdx]) & Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) != - Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) { + if ((getText().getSpanFlags(spans[spanIdx]) & Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) + != Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) { continue; } Object span = spans[spanIdx]; @@ -501,11 +504,9 @@ public class ReactEditText extends EditText { } private boolean isSecureText() { - return - (getInputType() & - (InputType.TYPE_NUMBER_VARIATION_PASSWORD | - InputType.TYPE_TEXT_VARIATION_PASSWORD)) - != 0; + return (getInputType() + & (InputType.TYPE_NUMBER_VARIATION_PASSWORD | InputType.TYPE_TEXT_VARIATION_PASSWORD)) + != 0; } private void onContentSizeChange() { @@ -528,8 +529,10 @@ public class ReactEditText extends EditText { gravityHorizontal = mDefaultGravityHorizontal; } setGravity( - (getGravity() & ~Gravity.HORIZONTAL_GRAVITY_MASK & - ~Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) | gravityHorizontal); + (getGravity() + & ~Gravity.HORIZONTAL_GRAVITY_MASK + & ~Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) + | gravityHorizontal); } /* package */ void setGravityVertical(int gravityVertical) { @@ -643,7 +646,7 @@ public class ReactEditText extends EditText { public void onFinishTemporaryDetach() { super.onFinishTemporaryDetach(); if (mContainsImages) { - Spanned text = getText(); + Spanned text = getText(); TextInlineImageSpan[] spans = text.getSpans(0, text.length(), TextInlineImageSpan.class); for (TextInlineImageSpan span : spans) { span.onFinishTemporaryDetach(); @@ -703,7 +706,7 @@ public class ReactEditText extends EditText { protected void applyTextAttributes() { // In general, the `getEffective*` functions return `Float.NaN` if the // property hasn't been set. - + // `getEffectiveFontSize` always returns a value so don't need to check for anything like // `Float.NaN`. setTextSize(TypedValue.COMPLEX_UNIT_PX, mTextAttributes.getEffectiveFontSize()); @@ -717,8 +720,8 @@ public class ReactEditText extends EditText { } /** - * This class will redirect *TextChanged calls to the listeners only in the case where the text - * is changed by the user, and not explicitly set by JS. + * This class will redirect *TextChanged calls to the listeners only in the case where the text is + * changed by the user, and not explicitly set by JS. */ private class TextWatcherDelegator implements TextWatcher { @Override @@ -762,8 +765,7 @@ public class ReactEditText extends EditText { private int mInputType = 0; - public InternalKeyListener() { - } + public InternalKeyListener() {} public void setInputType(int inputType) { mInputType = inputType; diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactEditTextInputConnectionWrapper.java b/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactEditTextInputConnectionWrapper.java index f9aa450b19e..260c82f695c 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactEditTextInputConnectionWrapper.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactEditTextInputConnectionWrapper.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.textinput; import android.view.KeyEvent; @@ -17,37 +16,37 @@ import com.facebook.react.uimanager.events.EventDispatcher; import javax.annotation.Nullable; /** - * A class to implement the TextInput 'onKeyPress' API on android for soft keyboards. - * It is instantiated in {@link ReactEditText#onCreateInputConnection(EditorInfo)}. + * A class to implement the TextInput 'onKeyPress' API on android for soft keyboards. It is + * instantiated in {@link ReactEditText#onCreateInputConnection(EditorInfo)}. * - * Android IMEs interface with EditText views through the {@link InputConnection} interface, - * so any observable change in state of the EditText via the soft-keyboard, should be a side effect of + *

Android IMEs interface with EditText views through the {@link InputConnection} interface, so + * any observable change in state of the EditText via the soft-keyboard, should be a side effect of * one or more of the methods in {@link InputConnectionWrapper}. * - * {@link InputConnection#setComposingText(CharSequence, int)} is used to set the composing region - * (the underlined text) in the {@link android.widget.EditText} view, i.e. when React Native's - * TextInput has the property 'autoCorrect' set to true. When text is being composed in the composing - * state within the EditText, each key press will result in a call to - * {@link InputConnection#setComposingText(CharSequence, int)} with a CharSequence argument equal to - * that of the entire composing region, rather than a single character diff. - * We can reason about the keyPress based on the resultant cursor position changes of the EditText after - * applying this change. For example if the cursor moved backwards by one character when composing, - * it's likely it was a delete; if it moves forward by a character, likely to be a key press of that character. + *

{@link InputConnection#setComposingText(CharSequence, int)} is used to set the composing + * region (the underlined text) in the {@link android.widget.EditText} view, i.e. when React + * Native's TextInput has the property 'autoCorrect' set to true. When text is being composed in the + * composing state within the EditText, each key press will result in a call to {@link + * InputConnection#setComposingText(CharSequence, int)} with a CharSequence argument equal to that + * of the entire composing region, rather than a single character diff. We can reason about the + * keyPress based on the resultant cursor position changes of the EditText after applying this + * change. For example if the cursor moved backwards by one character when composing, it's likely it + * was a delete; if it moves forward by a character, likely to be a key press of that character. * - * IMEs can also call {@link InputConnection#beginBatchEdit()} to signify a batch of operations. One - * such example is committing a word currently in composing state with the press of the space key. - * It is IME dependent but the stock Android keyboard behavior seems to be to commit the currently composing - * text with {@link InputConnection#setComposingText(CharSequence, int)} and commits a space character - * with a separate call to {@link InputConnection#setComposingText(CharSequence, int)}. - * Here we chose to emit the last input of a batch edit as that tends to be the user input, but - * it's completely arbitrary. + *

IMEs can also call {@link InputConnection#beginBatchEdit()} to signify a batch of operations. + * One such example is committing a word currently in composing state with the press of the space + * key. It is IME dependent but the stock Android keyboard behavior seems to be to commit the + * currently composing text with {@link InputConnection#setComposingText(CharSequence, int)} and + * commits a space character with a separate call to {@link + * InputConnection#setComposingText(CharSequence, int)}. Here we chose to emit the last input of a + * batch edit as that tends to be the user input, but it's completely arbitrary. * - * Another function of this class is to detect backspaces when the cursor at the beginning of the + *

Another function of this class is to detect backspaces when the cursor at the beginning of the * {@link android.widget.EditText}, i.e no text is deleted. * - * N.B. this class is only applicable for soft keyboards behavior. For hardware keyboards - * {@link android.view.View#onKeyDown(int, KeyEvent)} can be overridden to obtain the keycode of the - * key pressed. + *

N.B. this class is only applicable for soft keyboards behavior. For hardware keyboards {@link + * android.view.View#onKeyDown(int, KeyEvent)} can be overridden to obtain the keycode of the key + * pressed. */ class ReactEditTextInputConnectionWrapper extends InputConnectionWrapper { public static final String NEWLINE_RAW_VALUE = "\n"; @@ -60,10 +59,7 @@ class ReactEditTextInputConnectionWrapper extends InputConnectionWrapper { private @Nullable String mKey = null; public ReactEditTextInputConnectionWrapper( - InputConnection target, - final ReactContext reactContext, - final ReactEditText editText - ) { + InputConnection target, final ReactContext reactContext, final ReactEditText editText) { super(target, false); mEventDispatcher = reactContext.getNativeModule(UIManagerModule.class).getEventDispatcher(); mEditText = editText; @@ -131,10 +127,10 @@ class ReactEditTextInputConnectionWrapper extends InputConnectionWrapper { // in each case, respectively. @Override public boolean sendKeyEvent(KeyEvent event) { - if(event.getAction() == KeyEvent.ACTION_DOWN) { + if (event.getAction() == KeyEvent.ACTION_DOWN) { if (event.getKeyCode() == KeyEvent.KEYCODE_DEL) { dispatchKeyEvent(BACKSPACE_KEY_VALUE); - } else if(event.getKeyCode() == KeyEvent.KEYCODE_ENTER) { + } else if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER) { dispatchKeyEvent(ENTER_KEY_VALUE); } } @@ -153,9 +149,6 @@ class ReactEditTextInputConnectionWrapper extends InputConnectionWrapper { if (key.equals(NEWLINE_RAW_VALUE)) { key = ENTER_KEY_VALUE; } - mEventDispatcher.dispatchEvent( - new ReactTextInputKeyPressEvent( - mEditText.getId(), - key)); + mEventDispatcher.dispatchEvent(new ReactTextInputKeyPressEvent(mEditText.getId(), key)); } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextChangedEvent.java b/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextChangedEvent.java index 46e3012f000..379f8294010 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextChangedEvent.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextChangedEvent.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.textinput; import com.facebook.react.bridge.Arguments; @@ -13,8 +12,8 @@ import com.facebook.react.uimanager.events.Event; import com.facebook.react.uimanager.events.RCTEventEmitter; /** - * Event emitted by EditText native view when text changes. - * VisibleForTesting from {@link TextInputEventsTestCase}. + * Event emitted by EditText native view when text changes. VisibleForTesting from {@link + * TextInputEventsTestCase}. */ public class ReactTextChangedEvent extends Event { @@ -23,10 +22,7 @@ public class ReactTextChangedEvent extends Event { private String mText; private int mEventCount; - public ReactTextChangedEvent( - int viewId, - String text, - int eventCount) { + public ReactTextChangedEvent(int viewId, String text, int eventCount) { super(viewId); mText = text; mEventCount = eventCount; diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextInputBlurEvent.java b/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextInputBlurEvent.java index 92ebd129158..b875172e9fa 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextInputBlurEvent.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextInputBlurEvent.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.textinput; import com.facebook.react.bridge.Arguments; @@ -12,9 +11,7 @@ import com.facebook.react.bridge.WritableMap; import com.facebook.react.uimanager.events.Event; import com.facebook.react.uimanager.events.RCTEventEmitter; -/** - * Event emitted by EditText native view when it loses focus. - */ +/** Event emitted by EditText native view when it loses focus. */ /* package */ class ReactTextInputBlurEvent extends Event { private static final String EVENT_NAME = "topBlur"; diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextInputEndEditingEvent.java b/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextInputEndEditingEvent.java index c8afefd9e45..3bb29974195 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextInputEndEditingEvent.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextInputEndEditingEvent.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.textinput; import com.facebook.react.bridge.Arguments; @@ -13,8 +12,8 @@ import com.facebook.react.uimanager.events.Event; import com.facebook.react.uimanager.events.RCTEventEmitter; /** - * Event emitted by EditText native view when text editing ends, - * because of the user leaving the text input. + * Event emitted by EditText native view when text editing ends, because of the user leaving the + * text input. */ class ReactTextInputEndEditingEvent extends Event { @@ -22,9 +21,7 @@ class ReactTextInputEndEditingEvent extends Event private String mText; - public ReactTextInputEndEditingEvent( - int viewId, - String text) { + public ReactTextInputEndEditingEvent(int viewId, String text) { super(viewId); mText = text; } diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextInputEvent.java b/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextInputEvent.java index 143e7e4d897..1a627c57476 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextInputEvent.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextInputEvent.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.textinput; import com.facebook.react.bridge.Arguments; @@ -13,8 +12,8 @@ import com.facebook.react.uimanager.events.Event; import com.facebook.react.uimanager.events.RCTEventEmitter; /** - * Event emitted by EditText native view when text changes. - * VisibleForTesting from {@link TextInputEventsTestCase}. + * Event emitted by EditText native view when text changes. VisibleForTesting from {@link + * TextInputEventsTestCase}. */ public class ReactTextInputEvent extends Event { @@ -26,11 +25,7 @@ public class ReactTextInputEvent extends Event { private int mRangeEnd; public ReactTextInputEvent( - int viewId, - String text, - String previousText, - int rangeStart, - int rangeEnd) { + int viewId, String text, String previousText, int rangeStart, int rangeEnd) { super(viewId); mText = text; mPreviousText = previousText; diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextInputFocusEvent.java b/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextInputFocusEvent.java index 5be8f9e3eb0..ed303af6bcd 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextInputFocusEvent.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextInputFocusEvent.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.textinput; import com.facebook.react.bridge.Arguments; @@ -12,9 +11,7 @@ import com.facebook.react.bridge.WritableMap; import com.facebook.react.uimanager.events.Event; import com.facebook.react.uimanager.events.RCTEventEmitter; -/** - * Event emitted by EditText native view when it receives focus. - */ +/** Event emitted by EditText native view when it receives focus. */ /* package */ class ReactTextInputFocusEvent extends Event { private static final String EVENT_NAME = "topFocus"; diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextInputKeyPressEvent.java b/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextInputKeyPressEvent.java index 388aa65d500..f806bb2898e 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextInputKeyPressEvent.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextInputKeyPressEvent.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.textinput; import com.facebook.react.bridge.Arguments; @@ -12,9 +11,7 @@ import com.facebook.react.bridge.WritableMap; import com.facebook.react.uimanager.events.Event; import com.facebook.react.uimanager.events.RCTEventEmitter; -/** - * Event emitted by EditText native view when key pressed - */ +/** Event emitted by EditText native view when key pressed */ public class ReactTextInputKeyPressEvent extends Event { public static final String EVENT_NAME = "topKeyPress"; diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextInputLocalData.java b/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextInputLocalData.java index b5a1559054b..08380ac5a03 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextInputLocalData.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextInputLocalData.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.textinput; import android.os.Build; @@ -21,7 +20,7 @@ public final class ReactTextInputLocalData { private final int mMaxLines; private final int mInputType; private final int mBreakStrategy; - private final CharSequence mPlaceholder; + private final CharSequence mPlaceholder; public ReactTextInputLocalData(EditText editText) { mText = new SpannableStringBuilder(editText.getText()); diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextInputManager.java b/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextInputManager.java index 88f1ab974c6..0fd50130d25 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextInputManager.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextInputManager.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.textinput; import static android.view.View.FOCUS_FORWARD; @@ -13,28 +12,25 @@ import android.graphics.PorterDuff; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.os.Build; -import androidx.core.content.ContextCompat; import android.text.Editable; import android.text.InputFilter; import android.text.InputType; import android.text.Layout; import android.text.Spannable; import android.text.TextWatcher; -import android.util.TypedValue; import android.view.Gravity; import android.view.KeyEvent; import android.view.View; import android.view.inputmethod.EditorInfo; import android.widget.TextView; +import androidx.core.content.ContextCompat; import com.facebook.common.logging.FLog; import com.facebook.infer.annotation.Assertions; import com.facebook.react.bridge.Dynamic; import com.facebook.react.bridge.JSApplicationIllegalArgumentException; import com.facebook.react.bridge.ReactContext; import com.facebook.react.bridge.ReadableArray; -import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.ReadableType; -import com.facebook.react.bridge.UIManager; import com.facebook.react.common.MapBuilder; import com.facebook.react.module.annotations.ReactModule; import com.facebook.react.uimanager.BaseViewManager; @@ -61,32 +57,32 @@ import java.util.LinkedList; import java.util.Map; import javax.annotation.Nullable; -/** - * Manages instances of TextInput. - */ +/** Manages instances of TextInput. */ @ReactModule(name = ReactTextInputManager.REACT_CLASS) public class ReactTextInputManager extends BaseViewManager { public static final String TAG = ReactTextInputManager.class.getSimpleName(); protected static final String REACT_CLASS = "AndroidTextInput"; private static final int[] SPACING_TYPES = { - Spacing.ALL, Spacing.LEFT, Spacing.RIGHT, Spacing.TOP, Spacing.BOTTOM, + Spacing.ALL, Spacing.LEFT, Spacing.RIGHT, Spacing.TOP, Spacing.BOTTOM, }; private static final int FOCUS_TEXT_INPUT = 1; private static final int BLUR_TEXT_INPUT = 2; private static final int INPUT_TYPE_KEYBOARD_NUMBER_PAD = InputType.TYPE_CLASS_NUMBER; - private static final int INPUT_TYPE_KEYBOARD_DECIMAL_PAD = INPUT_TYPE_KEYBOARD_NUMBER_PAD | - InputType.TYPE_NUMBER_FLAG_DECIMAL; - private static final int INPUT_TYPE_KEYBOARD_NUMBERED = INPUT_TYPE_KEYBOARD_DECIMAL_PAD | - InputType.TYPE_NUMBER_FLAG_SIGNED; - private static final int PASSWORD_VISIBILITY_FLAG = InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD & - ~InputType.TYPE_TEXT_VARIATION_PASSWORD; - private static final int KEYBOARD_TYPE_FLAGS = INPUT_TYPE_KEYBOARD_NUMBERED | - InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS | - InputType.TYPE_CLASS_TEXT | InputType.TYPE_CLASS_PHONE | - PASSWORD_VISIBILITY_FLAG; + private static final int INPUT_TYPE_KEYBOARD_DECIMAL_PAD = + INPUT_TYPE_KEYBOARD_NUMBER_PAD | InputType.TYPE_NUMBER_FLAG_DECIMAL; + private static final int INPUT_TYPE_KEYBOARD_NUMBERED = + INPUT_TYPE_KEYBOARD_DECIMAL_PAD | InputType.TYPE_NUMBER_FLAG_SIGNED; + private static final int PASSWORD_VISIBILITY_FLAG = + InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD & ~InputType.TYPE_TEXT_VARIATION_PASSWORD; + private static final int KEYBOARD_TYPE_FLAGS = + INPUT_TYPE_KEYBOARD_NUMBERED + | InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS + | InputType.TYPE_CLASS_TEXT + | InputType.TYPE_CLASS_PHONE + | PASSWORD_VISIBILITY_FLAG; private static final String KEYBOARD_TYPE_EMAIL_ADDRESS = "email-address"; private static final String KEYBOARD_TYPE_NUMERIC = "numeric"; @@ -129,8 +125,7 @@ public class ReactTextInputManager extends BaseViewManager getExportedCustomDirectEventTypeConstants() { return MapBuilder.builder() - .put(ScrollEventType.getJSEventName(ScrollEventType.SCROLL), MapBuilder.of("registrationName", "onScroll")) + .put( + ScrollEventType.getJSEventName(ScrollEventType.SCROLL), + MapBuilder.of("registrationName", "onScroll")) .build(); } @@ -174,9 +171,7 @@ public class ReactTextInputManager extends BaseViewManager= 500 || "bold".equals(fontWeightString)) { fontWeight = Typeface.BOLD; - } else if ("normal".equals(fontWeightString) || - (fontWeightNumeric != -1 && fontWeightNumeric < 500)) { + } else if ("normal".equals(fontWeightString) + || (fontWeightNumeric != -1 && fontWeightNumeric < 500)) { fontWeight = Typeface.NORMAL; } Typeface currentTypeface = view.getTypeface(); @@ -273,9 +265,9 @@ public class ReactTextInputManager extends BaseViewManager>> 24); + float rgbComponent = + color == null ? YogaConstants.UNDEFINED : (float) ((int) color & 0x00FFFFFF); + float alphaComponent = color == null ? YogaConstants.UNDEFINED : (float) ((int) color >>> 24); view.setBorderColor(SPACING_TYPES[index], rgbComponent, alphaComponent); } @@ -792,13 +800,11 @@ public class ReactTextInputManager extends BaseViewManagerReturn -1 if the input string is not a valid numeric fontWeight (100, 200, ..., 900), + * otherwise return the weight. */ private static int parseNumericFontWeight(String fontWeightString) { // This should be much faster than using regex to verify input and Integer.parseInt - return fontWeightString.length() == 3 && fontWeightString.endsWith("00") - && fontWeightString.charAt(0) <= '9' && fontWeightString.charAt(0) >= '1' ? - 100 * (fontWeightString.charAt(0) - '0') : -1; + return fontWeightString.length() == 3 + && fontWeightString.endsWith("00") + && fontWeightString.charAt(0) <= '9' + && fontWeightString.charAt(0) >= '1' + ? 100 * (fontWeightString.charAt(0) - '0') + : -1; } private static void updateStagedInputTypeFlag( - ReactEditText view, - int flagsToUnset, - int flagsToSet) { + ReactEditText view, int flagsToUnset, int flagsToSet) { view.setStagedInputType((view.getStagedInputType() & ~flagsToUnset) | flagsToSet); } @@ -830,8 +837,7 @@ public class ReactTextInputManager extends BaseViewManager 0 || - actionId == EditorInfo.IME_NULL) { + if ((actionId & EditorInfo.IME_MASK_ACTION) > 0 || actionId == EditorInfo.IME_NULL) { boolean blurOnSubmit = editText.getBlurOnSubmit(); - boolean isMultiline = ((editText.getInputType() & - InputType.TYPE_TEXT_FLAG_MULTI_LINE) != 0); + boolean isMultiline = + ((editText.getInputType() & InputType.TYPE_TEXT_FLAG_MULTI_LINE) != 0); // Motivation: - // * blurOnSubmit && isMultiline => Clear focus; prevent default behaviour (return true); - // * blurOnSubmit && !isMultiline => Clear focus; prevent default behaviour (return true); + // * blurOnSubmit && isMultiline => Clear focus; prevent default behaviour (return + // true); + // * blurOnSubmit && !isMultiline => Clear focus; prevent default behaviour (return + // true); // * !blurOnSubmit && isMultiline => Perform default behaviour (return false); // * !blurOnSubmit && !isMultiline => Prevent default behaviour (return true). // Additionally we always generate a `submit` event. @@ -931,8 +924,7 @@ public class ReactTextInputManager extends BaseViewManagerThis source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.textinput; import com.facebook.react.bridge.Arguments; @@ -12,21 +11,15 @@ import com.facebook.react.bridge.WritableMap; import com.facebook.react.uimanager.events.Event; import com.facebook.react.uimanager.events.RCTEventEmitter; -/** - * Event emitted by EditText native view when the text selection changes. - */ -/* package */ class ReactTextInputSelectionEvent - extends Event { +/** Event emitted by EditText native view when the text selection changes. */ +/* package */ class ReactTextInputSelectionEvent extends Event { private static final String EVENT_NAME = "topSelectionChange"; private int mSelectionStart; private int mSelectionEnd; - public ReactTextInputSelectionEvent( - int viewId, - int selectionStart, - int selectionEnd) { + public ReactTextInputSelectionEvent(int viewId, int selectionStart, int selectionEnd) { super(viewId); mSelectionStart = selectionStart; mSelectionEnd = selectionEnd; diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextInputShadowNode.java b/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextInputShadowNode.java index fe5845310b3..069e8081bdf 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextInputShadowNode.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextInputShadowNode.java @@ -1,19 +1,18 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.textinput; import android.annotation.TargetApi; import android.os.Build; -import androidx.core.view.ViewCompat; import android.text.Layout; import android.util.TypedValue; import android.view.ViewGroup; import android.widget.EditText; +import androidx.core.view.ViewCompat; import com.facebook.infer.annotation.Assertions; import com.facebook.react.bridge.JSApplicationIllegalArgumentException; import com.facebook.react.bridge.ReadableMap; @@ -51,8 +50,10 @@ public class ReactTextInputShadowNode extends ReactBaseTextShadowNode private int mSelectionEnd = UNSET; public ReactTextInputShadowNode() { - mTextBreakStrategy = (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) ? - Layout.BREAK_STRATEGY_SIMPLE : Layout.BREAK_STRATEGY_HIGH_QUALITY; + mTextBreakStrategy = + (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) + ? Layout.BREAK_STRATEGY_SIMPLE + : Layout.BREAK_STRATEGY_HIGH_QUALITY; initMeasureFunction(); } @@ -110,15 +111,15 @@ public class ReactTextInputShadowNode extends ReactBaseTextShadowNode editText.setLines(mNumberOfLines); } - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && - editText.getBreakStrategy() != mTextBreakStrategy) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M + && editText.getBreakStrategy() != mTextBreakStrategy) { editText.setBreakStrategy(mTextBreakStrategy); } } - // make sure the placeholder content is also being measured - editText.setHint(getPlaceholder()); - editText.measure( + // make sure the placeholder content is also being measured + editText.setHint(getPlaceholder()); + editText.measure( MeasureUtil.getMeasureSpec(width, widthMode), MeasureUtil.getMeasureSpec(height, heightMode)); @@ -175,8 +176,7 @@ public class ReactTextInputShadowNode extends ReactBaseTextShadowNode @ReactProp(name = PROP_SELECTION) public void setSelection(@Nullable ReadableMap selection) { mSelectionStart = mSelectionEnd = UNSET; - if (selection == null) - return; + if (selection == null) return; if (selection.hasKey("start") && selection.hasKey("end")) { mSelectionStart = selection.getInt("start"); @@ -198,7 +198,8 @@ public class ReactTextInputShadowNode extends ReactBaseTextShadowNode } else if ("balanced".equals(textBreakStrategy)) { mTextBreakStrategy = Layout.BREAK_STRATEGY_BALANCED; } else { - throw new JSApplicationIllegalArgumentException("Invalid textBreakStrategy: " + textBreakStrategy); + throw new JSApplicationIllegalArgumentException( + "Invalid textBreakStrategy: " + textBreakStrategy); } } @@ -214,7 +215,7 @@ public class ReactTextInputShadowNode extends ReactBaseTextShadowNode getText(), /* supportsInlineViews: */ false, /* nativeViewHierarchyOptimizer: */ null // only needed to support inline views - ), + ), mMostRecentEventCount, mContainsImages, getPadding(Spacing.LEFT), diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextInputSubmitEditingEvent.java b/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextInputSubmitEditingEvent.java index b75146c6e11..18eb8cb84f1 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextInputSubmitEditingEvent.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextInputSubmitEditingEvent.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.textinput; import com.facebook.react.bridge.Arguments; @@ -12,9 +11,7 @@ import com.facebook.react.bridge.WritableMap; import com.facebook.react.uimanager.events.Event; import com.facebook.react.uimanager.events.RCTEventEmitter; -/** - * Event emitted by EditText native view when the user submits the text. - */ +/** Event emitted by EditText native view when the user submits the text. */ /* package */ class ReactTextInputSubmitEditingEvent extends Event { @@ -22,9 +19,7 @@ import com.facebook.react.uimanager.events.RCTEventEmitter; private String mText; - public ReactTextInputSubmitEditingEvent( - int viewId, - String text) { + public ReactTextInputSubmitEditingEvent(int viewId, String text) { super(viewId); mText = text; } diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ScrollWatcher.java b/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ScrollWatcher.java index 5902cc082b0..42a4b2bf43a 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ScrollWatcher.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ScrollWatcher.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.textinput; public interface ScrollWatcher { diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/textinput/SelectionWatcher.java b/ReactAndroid/src/main/java/com/facebook/react/views/textinput/SelectionWatcher.java index 13bbdd20b4a..ca4b412e486 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/textinput/SelectionWatcher.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/textinput/SelectionWatcher.java @@ -1,15 +1,14 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.textinput; /** - * Implement this interface to be informed of selection changes in the ReactTextEdit - * This is used by the ReactTextInputManager to forward events from the EditText to JS + * Implement this interface to be informed of selection changes in the ReactTextEdit This is used by + * the ReactTextInputManager to forward events from the EditText to JS */ interface SelectionWatcher { public void onSelectionChanged(int start, int end); diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/unimplementedview/ReactUnimplementedView.java b/ReactAndroid/src/main/java/com/facebook/react/views/unimplementedview/ReactUnimplementedView.java index f32e6eb0428..c07178a5794 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/unimplementedview/ReactUnimplementedView.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/unimplementedview/ReactUnimplementedView.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.unimplementedview; import android.content.Context; @@ -19,7 +18,9 @@ public class ReactUnimplementedView extends LinearLayout { public ReactUnimplementedView(Context context) { super(context); mTextView = new AppCompatTextView(context); - mTextView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT)); + mTextView.setLayoutParams( + new LinearLayout.LayoutParams( + LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT)); mTextView.setGravity(Gravity.CENTER); mTextView.setTextColor(Color.WHITE); diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/unimplementedview/ReactUnimplementedViewManager.java b/ReactAndroid/src/main/java/com/facebook/react/views/unimplementedview/ReactUnimplementedViewManager.java index 9d8f685d2b4..fab14cc30a0 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/unimplementedview/ReactUnimplementedViewManager.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/unimplementedview/ReactUnimplementedViewManager.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.unimplementedview; import static com.facebook.react.views.unimplementedview.ReactUnimplementedViewManager.REACT_CLASS; @@ -16,8 +15,8 @@ import com.facebook.react.uimanager.annotations.ReactProp; import javax.annotation.Nullable; /** - * ViewManager for {@link ReactUnimplementedView} to represent a component that is not - * yet supported. + * ViewManager for {@link ReactUnimplementedView} to represent a component that is not yet + * supported. */ @ReactModule(name = ReactUnimplementedViewManager.REACT_CLASS) public class ReactUnimplementedViewManager extends ViewGroupManager { diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/view/ColorUtil.java b/ReactAndroid/src/main/java/com/facebook/react/views/view/ColorUtil.java index 5b4bd245a6e..e6625749262 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/view/ColorUtil.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/view/ColorUtil.java @@ -1,24 +1,23 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.view; import android.graphics.PixelFormat; /** - * Simple utility class for manipulating colors, based on Fresco's - * DrawableUtils (https://github.com/facebook/fresco). - * For a small helper like this, copying is simpler than adding - * a dependency on com.facebook.fresco.drawee. + * Simple utility class for manipulating colors, based on Fresco's DrawableUtils + * (https://github.com/facebook/fresco). For a small helper like this, copying is simpler than + * adding a dependency on com.facebook.fresco.drawee. */ public class ColorUtil { /** * Multiplies the color with the given alpha. + * * @param color color to be multiplied * @param alpha value between 0 and 255 * @return multiplied color @@ -38,6 +37,7 @@ public class ColorUtil { /** * Gets the opacity from a color. Inspired by Android ColorDrawable. + * * @return opacity expressed by one of PixelFormat constants */ public static int getOpacityFromColor(int color) { diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/view/MeasureUtil.java b/ReactAndroid/src/main/java/com/facebook/react/views/view/MeasureUtil.java index 44cdf5f2cce..763f1491e19 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/view/MeasureUtil.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/view/MeasureUtil.java @@ -6,7 +6,6 @@ package com.facebook.react.views.view; import android.view.View; - import com.facebook.yoga.YogaMeasureMode; public class MeasureUtil { diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactDrawableHelper.java b/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactDrawableHelper.java index 51b24ceeaa2..8f68c957208 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactDrawableHelper.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactDrawableHelper.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.view; import android.annotation.TargetApi; @@ -16,7 +15,6 @@ import android.graphics.drawable.Drawable; import android.graphics.drawable.RippleDrawable; import android.os.Build; import android.util.TypedValue; - import com.facebook.react.bridge.JSApplicationIllegalArgumentException; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.SoftAssertions; @@ -32,61 +30,58 @@ public class ReactDrawableHelper { @TargetApi(Build.VERSION_CODES.LOLLIPOP) public static Drawable createDrawableFromJSDescription( - Context context, - ReadableMap drawableDescriptionDict) { + Context context, ReadableMap drawableDescriptionDict) { String type = drawableDescriptionDict.getString("type"); if ("ThemeAttrAndroid".equals(type)) { String attr = drawableDescriptionDict.getString("attribute"); SoftAssertions.assertNotNull(attr); int attrID = context.getResources().getIdentifier(attr, "attr", "android"); if (attrID == 0) { - throw new JSApplicationIllegalArgumentException("Attribute " + attr + - " couldn't be found in the resource list"); + throw new JSApplicationIllegalArgumentException( + "Attribute " + attr + " couldn't be found in the resource list"); } if (context.getTheme().resolveAttribute(attrID, sResolveOutValue, true)) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { - return context.getResources() + return context + .getResources() .getDrawable(sResolveOutValue.resourceId, context.getTheme()); } else { return context.getResources().getDrawable(sResolveOutValue.resourceId); } } else { - throw new JSApplicationIllegalArgumentException("Attribute " + attr + - " couldn't be resolved into a drawable"); + throw new JSApplicationIllegalArgumentException( + "Attribute " + attr + " couldn't be resolved into a drawable"); } } else if ("RippleAndroid".equals(type)) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { - throw new JSApplicationIllegalArgumentException("Ripple drawable is not available on " + - "android API <21"); + throw new JSApplicationIllegalArgumentException( + "Ripple drawable is not available on " + "android API <21"); } int color; - if (drawableDescriptionDict.hasKey(ViewProps.COLOR) && - !drawableDescriptionDict.isNull(ViewProps.COLOR)) { + if (drawableDescriptionDict.hasKey(ViewProps.COLOR) + && !drawableDescriptionDict.isNull(ViewProps.COLOR)) { color = drawableDescriptionDict.getInt(ViewProps.COLOR); } else { - if (context.getTheme().resolveAttribute( - android.R.attr.colorControlHighlight, - sResolveOutValue, - true)) { + if (context + .getTheme() + .resolveAttribute(android.R.attr.colorControlHighlight, sResolveOutValue, true)) { color = context.getResources().getColor(sResolveOutValue.resourceId); } else { - throw new JSApplicationIllegalArgumentException("Attribute colorControlHighlight " + - "couldn't be resolved into a drawable"); + throw new JSApplicationIllegalArgumentException( + "Attribute colorControlHighlight " + "couldn't be resolved into a drawable"); } } Drawable mask = null; - if (!drawableDescriptionDict.hasKey("borderless") || - drawableDescriptionDict.isNull("borderless") || - !drawableDescriptionDict.getBoolean("borderless")) { + if (!drawableDescriptionDict.hasKey("borderless") + || drawableDescriptionDict.isNull("borderless") + || !drawableDescriptionDict.getBoolean("borderless")) { mask = new ColorDrawable(Color.WHITE); } - ColorStateList colorStateList = new ColorStateList( - new int[][] {new int[]{}}, - new int[] {color}); + ColorStateList colorStateList = + new ColorStateList(new int[][] {new int[] {}}, new int[] {color}); return new RippleDrawable(colorStateList, null, mask); } else { - throw new JSApplicationIllegalArgumentException( - "Invalid type for android drawable: " + type); + throw new JSApplicationIllegalArgumentException("Invalid type for android drawable: " + type); } } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewBackgroundDrawable.java b/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewBackgroundDrawable.java index 6fffa363d0c..31e932825a0 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewBackgroundDrawable.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewBackgroundDrawable.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.view; import android.content.Context; @@ -65,7 +64,7 @@ public class ReactViewBackgroundDrawable extends Drawable { case DASHED: return new DashPathEffect( - new float[] {borderWidth*3, borderWidth*3, borderWidth*3, borderWidth*3}, 0); + new float[] {borderWidth * 3, borderWidth * 3, borderWidth * 3, borderWidth * 3}, 0); case DOTTED: return new DashPathEffect( @@ -187,7 +186,8 @@ public class ReactViewBackgroundDrawable extends Drawable { super.getOutline(outline); return; } - if ((!YogaConstants.isUndefined(mBorderRadius) && mBorderRadius > 0) || mBorderCornerRadii != null) { + if ((!YogaConstants.isUndefined(mBorderRadius) && mBorderRadius > 0) + || mBorderCornerRadii != null) { updatePath(); outline.setConvexPath(mPathForBorderRadiusOutline); @@ -244,9 +244,8 @@ public class ReactViewBackgroundDrawable extends Drawable { } public void setBorderStyle(@Nullable String style) { - BorderStyle borderStyle = style == null - ? null - : BorderStyle.valueOf(style.toUpperCase(Locale.US)); + BorderStyle borderStyle = + style == null ? null : BorderStyle.valueOf(style.toUpperCase(Locale.US)); if (mBorderStyle != borderStyle) { mBorderStyle = borderStyle; mNeedUpdatePathForBorderRadius = true; @@ -255,7 +254,7 @@ public class ReactViewBackgroundDrawable extends Drawable { } public void setRadius(float radius) { - if (!FloatUtil.floatsEqual(mBorderRadius,radius)) { + if (!FloatUtil.floatsEqual(mBorderRadius, radius)) { mBorderRadius = radius; mNeedUpdatePathForBorderRadius = true; invalidateSelf(); @@ -345,12 +344,12 @@ public class ReactViewBackgroundDrawable extends Drawable { || borderWidth.left > 0 || borderWidth.right > 0) { - //If it's a full and even border draw inner rect path with stroke + // If it's a full and even border draw inner rect path with stroke final float fullBorderWidth = getFullBorderWidth(); - if (borderWidth.top == fullBorderWidth && - borderWidth.bottom == fullBorderWidth && - borderWidth.left == fullBorderWidth && - borderWidth.right == fullBorderWidth) { + if (borderWidth.top == fullBorderWidth + && borderWidth.bottom == fullBorderWidth + && borderWidth.left == fullBorderWidth + && borderWidth.right == fullBorderWidth) { if (fullBorderWidth > 0) { int borderColor = getBorderColor(Spacing.ALL); mPaint.setColor(ColorUtil.multiplyColorAlpha(borderColor, mAlpha)); @@ -359,7 +358,7 @@ public class ReactViewBackgroundDrawable extends Drawable { canvas.drawPath(mCenterDrawPath, mPaint); } } - //In the case of uneven border widths/colors draw quadrilateral in each direction + // In the case of uneven border widths/colors draw quadrilateral in each direction else { mPaint.setStyle(Paint.Style.FILL); @@ -398,9 +397,9 @@ public class ReactViewBackgroundDrawable extends Drawable { final boolean isColorStartDefined = isBorderColorDefined(Spacing.START); final boolean isColorEndDefined = isBorderColorDefined(Spacing.END); final boolean isDirectionAwareColorLeftDefined = - isRTL ? isColorEndDefined : isColorStartDefined; + isRTL ? isColorEndDefined : isColorStartDefined; final boolean isDirectionAwareColorRightDefined = - isRTL ? isColorStartDefined : isColorEndDefined; + isRTL ? isColorStartDefined : isColorEndDefined; if (isDirectionAwareColorLeftDefined) { colorLeft = directionAwareColorLeft; @@ -536,10 +535,8 @@ public class ReactViewBackgroundDrawable extends Drawable { mInnerClipTempRectForBorderRadius.right -= borderWidth.right; final float borderRadius = getFullBorderRadius(); - float topLeftRadius = - getBorderRadiusOrDefaultTo(borderRadius, BorderRadiusLocation.TOP_LEFT); - float topRightRadius = - getBorderRadiusOrDefaultTo(borderRadius, BorderRadiusLocation.TOP_RIGHT); + float topLeftRadius = getBorderRadiusOrDefaultTo(borderRadius, BorderRadiusLocation.TOP_LEFT); + float topRightRadius = getBorderRadiusOrDefaultTo(borderRadius, BorderRadiusLocation.TOP_RIGHT); float bottomLeftRadius = getBorderRadiusOrDefaultTo(borderRadius, BorderRadiusLocation.BOTTOM_LEFT); float bottomRightRadius = @@ -646,32 +643,32 @@ public class ReactViewBackgroundDrawable extends Drawable { } mPathForBorderRadiusOutline.addRoundRect( - mTempRectForBorderRadiusOutline, - new float[] { - topLeftRadius + extraRadiusForOutline, - topLeftRadius + extraRadiusForOutline, - topRightRadius + extraRadiusForOutline, - topRightRadius + extraRadiusForOutline, - bottomRightRadius + extraRadiusForOutline, - bottomRightRadius + extraRadiusForOutline, - bottomLeftRadius + extraRadiusForOutline, - bottomLeftRadius + extraRadiusForOutline - }, - Path.Direction.CW); + mTempRectForBorderRadiusOutline, + new float[] { + topLeftRadius + extraRadiusForOutline, + topLeftRadius + extraRadiusForOutline, + topRightRadius + extraRadiusForOutline, + topRightRadius + extraRadiusForOutline, + bottomRightRadius + extraRadiusForOutline, + bottomRightRadius + extraRadiusForOutline, + bottomLeftRadius + extraRadiusForOutline, + bottomLeftRadius + extraRadiusForOutline + }, + Path.Direction.CW); mCenterDrawPath.addRoundRect( - mTempRectForCenterDrawPath, - new float[] { - innerTopLeftRadiusX + (innerTopLeftRadiusX > 0 ? extraRadiusForOutline : 0), - innerTopLeftRadiusY + (innerTopLeftRadiusY > 0 ? extraRadiusForOutline : 0), - innerTopRightRadiusX + (innerTopRightRadiusX > 0 ? extraRadiusForOutline : 0), - innerTopRightRadiusY + (innerTopRightRadiusY > 0 ? extraRadiusForOutline : 0), - innerBottomRightRadiusX + (innerBottomRightRadiusX > 0 ? extraRadiusForOutline : 0), - innerBottomRightRadiusY + (innerBottomRightRadiusY > 0 ? extraRadiusForOutline : 0), - innerBottomLeftRadiusX + (innerBottomLeftRadiusX > 0 ? extraRadiusForOutline : 0), - innerBottomLeftRadiusY + (innerBottomLeftRadiusY > 0 ? extraRadiusForOutline : 0) - }, - Path.Direction.CW); + mTempRectForCenterDrawPath, + new float[] { + innerTopLeftRadiusX + (innerTopLeftRadiusX > 0 ? extraRadiusForOutline : 0), + innerTopLeftRadiusY + (innerTopLeftRadiusY > 0 ? extraRadiusForOutline : 0), + innerTopRightRadiusX + (innerTopRightRadiusX > 0 ? extraRadiusForOutline : 0), + innerTopRightRadiusY + (innerTopRightRadiusY > 0 ? extraRadiusForOutline : 0), + innerBottomRightRadiusX + (innerBottomRightRadiusX > 0 ? extraRadiusForOutline : 0), + innerBottomRightRadiusY + (innerBottomRightRadiusY > 0 ? extraRadiusForOutline : 0), + innerBottomLeftRadiusX + (innerBottomLeftRadiusX > 0 ? extraRadiusForOutline : 0), + innerBottomLeftRadiusY + (innerBottomLeftRadiusY > 0 ? extraRadiusForOutline : 0) + }, + Path.Direction.CW); /** * Rounded Multi-Colored Border Algorithm: @@ -881,11 +878,10 @@ public class ReactViewBackgroundDrawable extends Drawable { /** * Step 1: * - * Translate the line so that the ellipse is at the origin. + *

Translate the line so that the ellipse is at the origin. * - * Why? It makes the math easier by changing the ellipse equation from - * ((x - ellipseCenterX)/a)^2 + ((y - ellipseCenterY)/b)^2 = 1 to - * (x/a)^2 + (y/b)^2 = 1. + *

Why? It makes the math easier by changing the ellipse equation from ((x - + * ellipseCenterX)/a)^2 + ((y - ellipseCenterY)/b)^2 = 1 to (x/a)^2 + (y/b)^2 = 1. */ lineStartX -= ellipseCenterX; lineStartY -= ellipseCenterY; @@ -895,8 +891,7 @@ public class ReactViewBackgroundDrawable extends Drawable { /** * Step 2: * - * Ellipse equation: (x/a)^2 + (y/b)^2 = 1 - * Line equation: y = mx + c + *

Ellipse equation: (x/a)^2 + (y/b)^2 = 1 Line equation: y = mx + c */ final double a = Math.abs(ellipseBoundsRight - ellipseBoundsLeft) / 2; final double b = Math.abs(ellipseBoundsBottom - ellipseBoundsTop) / 2; @@ -906,10 +901,10 @@ public class ReactViewBackgroundDrawable extends Drawable { /** * Step 3: * - * Substitute the Line equation into the Ellipse equation. Solve for x. - * Eventually, you'll have to use the quadratic formula. + *

Substitute the Line equation into the Ellipse equation. Solve for x. Eventually, you'll + * have to use the quadratic formula. * - * Quadratic formula: Ax^2 + Bx + C = 0 + *

Quadratic formula: Ax^2 + Bx + C = 0 */ final double A = (b * b + a * a * m * m); final double B = 2 * a * a * c * m; @@ -918,7 +913,7 @@ public class ReactViewBackgroundDrawable extends Drawable { /** * Step 4: * - * Apply Quadratic formula. D = determinant / 2A + *

Apply Quadratic formula. D = determinant / 2A */ final double D = Math.sqrt(-C / A + Math.pow(B / (2 * A), 2)); final double x2 = -B / (2 * A) - D; @@ -927,7 +922,7 @@ public class ReactViewBackgroundDrawable extends Drawable { /** * Step 5: * - * Undo the space transformation in Step 5. + *

Undo the space transformation in Step 5. */ final double x = x2 + ellipseCenterX; final double y = y2 + ellipseCenterY; @@ -952,29 +947,27 @@ public class ReactViewBackgroundDrawable extends Drawable { return width; } - /** - * Set type of border - */ + /** Set type of border */ private void updatePathEffect() { - mPathEffectForBorderStyle = mBorderStyle != null - ? BorderStyle.getPathEffect(mBorderStyle, getFullBorderWidth()) - : null; + mPathEffectForBorderStyle = + mBorderStyle != null ? BorderStyle.getPathEffect(mBorderStyle, getFullBorderWidth()) : null; mPaint.setPathEffect(mPathEffectForBorderStyle); } /** For rounded borders we use default "borderWidth" property. */ public float getFullBorderWidth() { - return (mBorderWidth != null && !YogaConstants.isUndefined(mBorderWidth.getRaw(Spacing.ALL))) ? - mBorderWidth.getRaw(Spacing.ALL) : 0f; + return (mBorderWidth != null && !YogaConstants.isUndefined(mBorderWidth.getRaw(Spacing.ALL))) + ? mBorderWidth.getRaw(Spacing.ALL) + : 0f; } /** - * Quickly determine if all the set border colors are equal. Bitwise AND all the set colors - * together, then OR them all together. If the AND and the OR are the same, then the colors - * are compatible, so return this color. + * Quickly determine if all the set border colors are equal. Bitwise AND all the set colors + * together, then OR them all together. If the AND and the OR are the same, then the colors are + * compatible, so return this color. * - * Used to avoid expensive path creation and expensive calls to canvas.drawPath + *

Used to avoid expensive path creation and expensive calls to canvas.drawPath * * @return A compatible border color, or zero if the border colors are not compatible. */ @@ -987,14 +980,16 @@ public class ReactViewBackgroundDrawable extends Drawable { int colorTop, int colorRight, int colorBottom) { - int andSmear = (borderLeft > 0 ? colorLeft : ALL_BITS_SET) & - (borderTop > 0 ? colorTop : ALL_BITS_SET) & - (borderRight > 0 ? colorRight : ALL_BITS_SET) & - (borderBottom > 0 ? colorBottom : ALL_BITS_SET); - int orSmear = (borderLeft > 0 ? colorLeft : ALL_BITS_UNSET) | - (borderTop > 0 ? colorTop : ALL_BITS_UNSET) | - (borderRight > 0 ? colorRight : ALL_BITS_UNSET) | - (borderBottom > 0 ? colorBottom : ALL_BITS_UNSET); + int andSmear = + (borderLeft > 0 ? colorLeft : ALL_BITS_SET) + & (borderTop > 0 ? colorTop : ALL_BITS_SET) + & (borderRight > 0 ? colorRight : ALL_BITS_SET) + & (borderBottom > 0 ? colorBottom : ALL_BITS_SET); + int orSmear = + (borderLeft > 0 ? colorLeft : ALL_BITS_UNSET) + | (borderTop > 0 ? colorTop : ALL_BITS_UNSET) + | (borderRight > 0 ? colorRight : ALL_BITS_UNSET) + | (borderBottom > 0 ? colorBottom : ALL_BITS_UNSET); return andSmear == orSmear ? andSmear : 0; } @@ -1047,8 +1042,10 @@ public class ReactViewBackgroundDrawable extends Drawable { final boolean isColorStartDefined = isBorderColorDefined(Spacing.START); final boolean isColorEndDefined = isBorderColorDefined(Spacing.END); - final boolean isDirectionAwareColorLeftDefined = isRTL ? isColorEndDefined : isColorStartDefined; - final boolean isDirectionAwareColorRightDefined = isRTL ? isColorStartDefined : isColorEndDefined; + final boolean isDirectionAwareColorLeftDefined = + isRTL ? isColorEndDefined : isColorStartDefined; + final boolean isDirectionAwareColorRightDefined = + isRTL ? isColorStartDefined : isColorEndDefined; if (isDirectionAwareColorLeftDefined) { colorLeft = directionAwareColorLeft; @@ -1064,15 +1061,16 @@ public class ReactViewBackgroundDrawable extends Drawable { int top = bounds.top; // Check for fast path to border drawing. - int fastBorderColor = fastBorderCompatibleColorOrZero( - borderLeft, - borderTop, - borderRight, - borderBottom, - colorLeft, - colorTop, - colorRight, - colorBottom); + int fastBorderColor = + fastBorderCompatibleColorOrZero( + borderLeft, + borderTop, + borderRight, + borderBottom, + colorLeft, + colorTop, + colorRight, + colorBottom); if (fastBorderColor != 0) { if (Color.alpha(fastBorderColor) != 0) { // Border color is not transparent. @@ -1206,8 +1204,8 @@ public class ReactViewBackgroundDrawable extends Drawable { } private static int colorFromAlphaAndRGBComponents(float alpha, float rgb) { - int rgbComponent = 0x00FFFFFF & (int)rgb; - int alphaComponent = 0xFF000000 & ((int)alpha) << 24; + int rgbComponent = 0x00FFFFFF & (int) rgb; + int alphaComponent = 0xFF000000 & ((int) alpha) << 24; return rgbComponent | alphaComponent; } @@ -1265,11 +1263,6 @@ public class ReactViewBackgroundDrawable extends Drawable { } } - return new RectF( - borderLeftWidth, - borderTopWidth, - borderRightWidth, - borderBottomWidth - ); + return new RectF(borderLeftWidth, borderTopWidth, borderRightWidth, borderBottomWidth); } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewBackgroundManager.java b/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewBackgroundManager.java index e8041d8fbc1..be360accee3 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewBackgroundManager.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewBackgroundManager.java @@ -8,8 +8,8 @@ package com.facebook.react.views.view; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.graphics.drawable.LayerDrawable; -import androidx.core.view.ViewCompat; import android.view.View; +import androidx.core.view.ViewCompat; import javax.annotation.Nullable; /** Class that manages the background for views and borders. */ diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewGroup.java b/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewGroup.java index 4e89e9dbf59..aafe2a692c2 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewGroup.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewGroup.java @@ -1,12 +1,13 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.view; +import static com.facebook.react.common.ReactConstants.TAG; + import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.Context; @@ -27,7 +28,6 @@ import com.facebook.common.logging.FLog; import com.facebook.infer.annotation.Assertions; import com.facebook.react.bridge.ReactContext; import com.facebook.react.common.annotations.VisibleForTesting; -import com.facebook.react.common.ReactConstants; import com.facebook.react.modules.i18nmanager.I18nUtil; import com.facebook.react.touch.OnInterceptTouchEventListener; import com.facebook.react.touch.ReactHitSlopView; @@ -46,15 +46,16 @@ import com.facebook.react.uimanager.ViewProps; import com.facebook.yoga.YogaConstants; import javax.annotation.Nullable; -import static com.facebook.react.common.ReactConstants.TAG; - /** * Backing for a React View. Has support for borders, but since borders aren't common, lazy * initializes most of the storage needed for them. */ -public class ReactViewGroup extends ViewGroup implements - ReactInterceptingViewGroup, ReactClippingViewGroup, ReactPointerEventsView, ReactHitSlopView, - ReactZIndexedViewGroup { +public class ReactViewGroup extends ViewGroup + implements ReactInterceptingViewGroup, + ReactClippingViewGroup, + ReactPointerEventsView, + ReactHitSlopView, + ReactZIndexedViewGroup { private static final int ARRAY_CAPACITY_INCREMENT = 12; private static final int DEFAULT_BACKGROUND_COLOR = Color.TRANSPARENT; @@ -131,8 +132,7 @@ public class ReactViewGroup extends ViewGroup implements MeasureSpecAssertions.assertExplicitMeasureSpec(widthMeasureSpec, heightMeasureSpec); setMeasuredDimension( - MeasureSpec.getSize(widthMeasureSpec), - MeasureSpec.getSize(heightMeasureSpec)); + MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.getSize(heightMeasureSpec)); } @Override @@ -203,8 +203,8 @@ public class ReactViewGroup extends ViewGroup implements @Override public boolean onInterceptTouchEvent(MotionEvent ev) { - if (mOnInterceptTouchEventListener != null && - mOnInterceptTouchEventListener.onInterceptTouchEvent(this, ev)) { + if (mOnInterceptTouchEventListener != null + && mOnInterceptTouchEventListener.onInterceptTouchEvent(this, ev)) { return true; } // We intercept the touch event if the children are not supposed to receive it. @@ -237,9 +237,7 @@ public class ReactViewGroup extends ViewGroup implements return mNeedsOffscreenAlphaCompositing; } - /** - * See the documentation of needsOffscreenAlphaCompositing in View.js. - */ + /** See the documentation of needsOffscreenAlphaCompositing in View.js. */ public void setNeedsOffscreenAlphaCompositing(boolean needsOffscreenAlphaCompositing) { mNeedsOffscreenAlphaCompositing = needsOffscreenAlphaCompositing; } @@ -258,9 +256,9 @@ public class ReactViewGroup extends ViewGroup implements if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) { final int UPDATED_LAYER_TYPE = - backgroundDrawable.hasRoundedBorders() - ? View.LAYER_TYPE_SOFTWARE - : View.LAYER_TYPE_HARDWARE; + backgroundDrawable.hasRoundedBorders() + ? View.LAYER_TYPE_SOFTWARE + : View.LAYER_TYPE_HARDWARE; if (UPDATED_LAYER_TYPE != getLayerType()) { setLayerType(UPDATED_LAYER_TYPE, null); @@ -361,8 +359,9 @@ public class ReactViewGroup extends ViewGroup implements private void updateSubviewClipStatus(Rect clippingRect, int idx, int clippedSoFar) { View child = Assertions.assertNotNull(mAllChildren)[idx]; sHelperRect.set(child.getLeft(), child.getTop(), child.getRight(), child.getBottom()); - boolean intersects = clippingRect - .intersects(sHelperRect.left, sHelperRect.top, sHelperRect.right, sHelperRect.bottom); + boolean intersects = + clippingRect.intersects( + sHelperRect.left, sHelperRect.top, sHelperRect.right, sHelperRect.bottom); boolean needUpdateClippingRecursive = false; // We never want to clip children that are being animated, as this can easily break layout : // when layout animation changes size and/or position of views contained inside a listview that @@ -407,8 +406,9 @@ public class ReactViewGroup extends ViewGroup implements // do fast check whether intersect state changed sHelperRect.set(subview.getLeft(), subview.getTop(), subview.getRight(), subview.getBottom()); - boolean intersects = mClippingRect - .intersects(sHelperRect.left, sHelperRect.top, sHelperRect.right, sHelperRect.bottom); + boolean intersects = + mClippingRect.intersects( + sHelperRect.left, sHelperRect.top, sHelperRect.right, sHelperRect.bottom); // If it was intersecting before, should be attached to the parent boolean oldIntersects = (subview.getParent() != null); @@ -445,7 +445,8 @@ public class ReactViewGroup extends ViewGroup implements @Override public void addView(View child, int index, ViewGroup.LayoutParams params) { - // This will get called for every overload of addView so there is not need to override every method. + // This will get called for every overload of addView so there is not need to override every + // method. mDrawingOrderHelper.handleAddView(child); setChildrenDrawingOrderEnabled(mDrawingOrderHelper.shouldEnableCustomDrawingOrder()); @@ -628,7 +629,7 @@ public class ReactViewGroup extends ViewGroup implements Drawable backgroundDrawable = getBackground(); updateBackgroundDrawable( null); // required so that drawable callback is cleared before we add the - // drawable back as a part of LayerDrawable + // drawable back as a part of LayerDrawable if (backgroundDrawable == null) { updateBackgroundDrawable(mReactBackgroundDrawable); } else { @@ -691,9 +692,10 @@ public class ReactViewGroup extends ViewGroup implements if (rootView != null) { rootView.handleException(e); } else { - if (getContext() instanceof ReactContext) { + if (getContext() instanceof ReactContext) { ReactContext reactContext = (ReactContext) getContext(); - reactContext.handleException(new IllegalViewOperationException("StackOverflowException", this, e)); + reactContext.handleException( + new IllegalViewOperationException("StackOverflowException", this, e)); } else { throw e; } @@ -721,9 +723,9 @@ public class ReactViewGroup extends ViewGroup implements final RectF borderWidth = mReactBackgroundDrawable.getDirectionAwareBorderInsets(); if (borderWidth.top > 0 - || borderWidth.left > 0 - || borderWidth.bottom > 0 - || borderWidth.right > 0) { + || borderWidth.left > 0 + || borderWidth.bottom > 0 + || borderWidth.right > 0) { left += borderWidth.left; top += borderWidth.top; right -= borderWidth.right; @@ -732,32 +734,32 @@ public class ReactViewGroup extends ViewGroup implements final float borderRadius = mReactBackgroundDrawable.getFullBorderRadius(); float topLeftBorderRadius = - mReactBackgroundDrawable.getBorderRadiusOrDefaultTo( - borderRadius, ReactViewBackgroundDrawable.BorderRadiusLocation.TOP_LEFT); + mReactBackgroundDrawable.getBorderRadiusOrDefaultTo( + borderRadius, ReactViewBackgroundDrawable.BorderRadiusLocation.TOP_LEFT); float topRightBorderRadius = - mReactBackgroundDrawable.getBorderRadiusOrDefaultTo( - borderRadius, ReactViewBackgroundDrawable.BorderRadiusLocation.TOP_RIGHT); + mReactBackgroundDrawable.getBorderRadiusOrDefaultTo( + borderRadius, ReactViewBackgroundDrawable.BorderRadiusLocation.TOP_RIGHT); float bottomLeftBorderRadius = - mReactBackgroundDrawable.getBorderRadiusOrDefaultTo( - borderRadius, ReactViewBackgroundDrawable.BorderRadiusLocation.BOTTOM_LEFT); + mReactBackgroundDrawable.getBorderRadiusOrDefaultTo( + borderRadius, ReactViewBackgroundDrawable.BorderRadiusLocation.BOTTOM_LEFT); float bottomRightBorderRadius = - mReactBackgroundDrawable.getBorderRadiusOrDefaultTo( - borderRadius, ReactViewBackgroundDrawable.BorderRadiusLocation.BOTTOM_RIGHT); + mReactBackgroundDrawable.getBorderRadiusOrDefaultTo( + borderRadius, ReactViewBackgroundDrawable.BorderRadiusLocation.BOTTOM_RIGHT); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { final boolean isRTL = mLayoutDirection == View.LAYOUT_DIRECTION_RTL; float topStartBorderRadius = - mReactBackgroundDrawable.getBorderRadius( - ReactViewBackgroundDrawable.BorderRadiusLocation.TOP_START); + mReactBackgroundDrawable.getBorderRadius( + ReactViewBackgroundDrawable.BorderRadiusLocation.TOP_START); float topEndBorderRadius = - mReactBackgroundDrawable.getBorderRadius( - ReactViewBackgroundDrawable.BorderRadiusLocation.TOP_END); + mReactBackgroundDrawable.getBorderRadius( + ReactViewBackgroundDrawable.BorderRadiusLocation.TOP_END); float bottomStartBorderRadius = - mReactBackgroundDrawable.getBorderRadius( - ReactViewBackgroundDrawable.BorderRadiusLocation.BOTTOM_START); + mReactBackgroundDrawable.getBorderRadius( + ReactViewBackgroundDrawable.BorderRadiusLocation.BOTTOM_START); float bottomEndBorderRadius = - mReactBackgroundDrawable.getBorderRadius( - ReactViewBackgroundDrawable.BorderRadiusLocation.BOTTOM_END); + mReactBackgroundDrawable.getBorderRadius( + ReactViewBackgroundDrawable.BorderRadiusLocation.BOTTOM_END); if (I18nUtil.getInstance().doLeftAndRightSwapInRTL(getContext())) { if (YogaConstants.isUndefined(topStartBorderRadius)) { @@ -777,13 +779,13 @@ public class ReactViewGroup extends ViewGroup implements } final float directionAwareTopLeftRadius = - isRTL ? topEndBorderRadius : topStartBorderRadius; + isRTL ? topEndBorderRadius : topStartBorderRadius; final float directionAwareTopRightRadius = - isRTL ? topStartBorderRadius : topEndBorderRadius; + isRTL ? topStartBorderRadius : topEndBorderRadius; final float directionAwareBottomLeftRadius = - isRTL ? bottomEndBorderRadius : bottomStartBorderRadius; + isRTL ? bottomEndBorderRadius : bottomStartBorderRadius; final float directionAwareBottomRightRadius = - isRTL ? bottomStartBorderRadius : bottomEndBorderRadius; + isRTL ? bottomStartBorderRadius : bottomEndBorderRadius; topLeftBorderRadius = directionAwareTopLeftRadius; topRightBorderRadius = directionAwareTopRightRadius; @@ -791,13 +793,13 @@ public class ReactViewGroup extends ViewGroup implements bottomRightBorderRadius = directionAwareBottomRightRadius; } else { final float directionAwareTopLeftRadius = - isRTL ? topEndBorderRadius : topStartBorderRadius; + isRTL ? topEndBorderRadius : topStartBorderRadius; final float directionAwareTopRightRadius = - isRTL ? topStartBorderRadius : topEndBorderRadius; + isRTL ? topStartBorderRadius : topEndBorderRadius; final float directionAwareBottomLeftRadius = - isRTL ? bottomEndBorderRadius : bottomStartBorderRadius; + isRTL ? bottomEndBorderRadius : bottomStartBorderRadius; final float directionAwareBottomRightRadius = - isRTL ? bottomStartBorderRadius : bottomEndBorderRadius; + isRTL ? bottomStartBorderRadius : bottomEndBorderRadius; if (!YogaConstants.isUndefined(directionAwareTopLeftRadius)) { topLeftBorderRadius = directionAwareTopLeftRadius; @@ -818,27 +820,27 @@ public class ReactViewGroup extends ViewGroup implements } if (topLeftBorderRadius > 0 - || topRightBorderRadius > 0 - || bottomRightBorderRadius > 0 - || bottomLeftBorderRadius > 0) { + || topRightBorderRadius > 0 + || bottomRightBorderRadius > 0 + || bottomLeftBorderRadius > 0) { if (mPath == null) { mPath = new Path(); } mPath.rewind(); mPath.addRoundRect( - new RectF(left, top, right, bottom), - new float[]{ - Math.max(topLeftBorderRadius - borderWidth.left, 0), - Math.max(topLeftBorderRadius - borderWidth.top, 0), - Math.max(topRightBorderRadius - borderWidth.right, 0), - Math.max(topRightBorderRadius - borderWidth.top, 0), - Math.max(bottomRightBorderRadius - borderWidth.right, 0), - Math.max(bottomRightBorderRadius - borderWidth.bottom, 0), - Math.max(bottomLeftBorderRadius - borderWidth.left, 0), - Math.max(bottomLeftBorderRadius - borderWidth.bottom, 0), - }, - Path.Direction.CW); + new RectF(left, top, right, bottom), + new float[] { + Math.max(topLeftBorderRadius - borderWidth.left, 0), + Math.max(topLeftBorderRadius - borderWidth.top, 0), + Math.max(topRightBorderRadius - borderWidth.right, 0), + Math.max(topRightBorderRadius - borderWidth.top, 0), + Math.max(bottomRightBorderRadius - borderWidth.right, 0), + Math.max(bottomRightBorderRadius - borderWidth.bottom, 0), + Math.max(bottomLeftBorderRadius - borderWidth.left, 0), + Math.max(bottomLeftBorderRadius - borderWidth.bottom, 0), + }, + Path.Direction.CW); canvas.clipPath(mPath); hasClipPath = true; } @@ -875,8 +877,8 @@ public class ReactViewGroup extends ViewGroup implements float rotationX = getRotationX(); float rotationY = getRotationY(); - boolean isFrontfaceVisible = (rotationX >= -90.f && rotationX < 90.f) && - (rotationY >= -90.f && rotationY < 90.f); + boolean isFrontfaceVisible = + (rotationX >= -90.f && rotationX < 90.f) && (rotationY >= -90.f && rotationY < 90.f); if (isFrontfaceVisible) { setAlpha(mBackfaceOpacity); diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewManager.java b/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewManager.java index 75e95947622..fb383e3dd2d 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewManager.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewManager.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.view; import android.annotation.TargetApi; @@ -33,14 +32,11 @@ import java.util.Locale; import java.util.Map; import javax.annotation.Nullable; -/** - * View manager for AndroidViews (plain React Views). - */ +/** View manager for AndroidViews (plain React Views). */ @ReactModule(name = ReactViewManager.REACT_CLASS) public class ReactViewManager extends ViewGroupManager { - @VisibleForTesting - public static final String REACT_CLASS = ViewProps.VIEW_CLASS_NAME; + @VisibleForTesting public static final String REACT_CLASS = ViewProps.VIEW_CLASS_NAME; private static final int[] SPACING_TYPES = { Spacing.ALL, @@ -93,19 +89,19 @@ public class ReactViewManager extends ViewGroupManager { view.setNextFocusUpId(viewId); } - @ReactPropGroup(names = { - ViewProps.BORDER_RADIUS, - ViewProps.BORDER_TOP_LEFT_RADIUS, - ViewProps.BORDER_TOP_RIGHT_RADIUS, - ViewProps.BORDER_BOTTOM_RIGHT_RADIUS, - ViewProps.BORDER_BOTTOM_LEFT_RADIUS, - ViewProps.BORDER_TOP_START_RADIUS, - ViewProps.BORDER_TOP_END_RADIUS, - ViewProps.BORDER_BOTTOM_START_RADIUS, - ViewProps.BORDER_BOTTOM_END_RADIUS, - }, - defaultFloat = YogaConstants.UNDEFINED - ) + @ReactPropGroup( + names = { + ViewProps.BORDER_RADIUS, + ViewProps.BORDER_TOP_LEFT_RADIUS, + ViewProps.BORDER_TOP_RIGHT_RADIUS, + ViewProps.BORDER_BOTTOM_RIGHT_RADIUS, + ViewProps.BORDER_BOTTOM_LEFT_RADIUS, + ViewProps.BORDER_TOP_START_RADIUS, + ViewProps.BORDER_TOP_END_RADIUS, + ViewProps.BORDER_BOTTOM_START_RADIUS, + ViewProps.BORDER_BOTTOM_END_RADIUS, + }, + defaultFloat = YogaConstants.UNDEFINED) public void setBorderRadius(ReactViewGroup view, int index, float borderRadius) { if (!YogaConstants.isUndefined(borderRadius) && borderRadius < 0) { borderRadius = YogaConstants.UNDEFINED; @@ -132,12 +128,18 @@ public class ReactViewManager extends ViewGroupManager { if (hitSlop == null) { view.setHitSlopRect(null); } else { - view.setHitSlopRect(new Rect( - hitSlop.hasKey("left") ? (int) PixelUtil.toPixelFromDIP(hitSlop.getDouble("left")) : 0, - hitSlop.hasKey("top") ? (int) PixelUtil.toPixelFromDIP(hitSlop.getDouble("top")) : 0, - hitSlop.hasKey("right") ? (int) PixelUtil.toPixelFromDIP(hitSlop.getDouble("right")) : 0, - hitSlop.hasKey("bottom") ? (int) PixelUtil.toPixelFromDIP(hitSlop.getDouble("bottom")) : 0 - )); + view.setHitSlopRect( + new Rect( + hitSlop.hasKey("left") + ? (int) PixelUtil.toPixelFromDIP(hitSlop.getDouble("left")) + : 0, + hitSlop.hasKey("top") ? (int) PixelUtil.toPixelFromDIP(hitSlop.getDouble("top")) : 0, + hitSlop.hasKey("right") + ? (int) PixelUtil.toPixelFromDIP(hitSlop.getDouble("right")) + : 0, + hitSlop.hasKey("bottom") + ? (int) PixelUtil.toPixelFromDIP(hitSlop.getDouble("bottom")) + : 0)); } } @@ -154,42 +156,44 @@ public class ReactViewManager extends ViewGroupManager { @ReactProp(name = "nativeBackgroundAndroid") public void setNativeBackground(ReactViewGroup view, @Nullable ReadableMap bg) { - view.setTranslucentBackgroundDrawable(bg == null ? - null : ReactDrawableHelper.createDrawableFromJSDescription(view.getContext(), bg)); + view.setTranslucentBackgroundDrawable( + bg == null + ? null + : ReactDrawableHelper.createDrawableFromJSDescription(view.getContext(), bg)); } @TargetApi(Build.VERSION_CODES.M) @ReactProp(name = "nativeForegroundAndroid") public void setNativeForeground(ReactViewGroup view, @Nullable ReadableMap fg) { - view.setForeground(fg == null - ? null - : ReactDrawableHelper.createDrawableFromJSDescription(view.getContext(), fg)); + view.setForeground( + fg == null + ? null + : ReactDrawableHelper.createDrawableFromJSDescription(view.getContext(), fg)); } - @ReactProp(name = com.facebook.react.uimanager.ReactClippingViewGroupHelper.PROP_REMOVE_CLIPPED_SUBVIEWS) + @ReactProp( + name = com.facebook.react.uimanager.ReactClippingViewGroupHelper.PROP_REMOVE_CLIPPED_SUBVIEWS) public void setRemoveClippedSubviews(ReactViewGroup view, boolean removeClippedSubviews) { view.setRemoveClippedSubviews(removeClippedSubviews); } @ReactProp(name = ViewProps.NEEDS_OFFSCREEN_ALPHA_COMPOSITING) public void setNeedsOffscreenAlphaCompositing( - ReactViewGroup view, - boolean needsOffscreenAlphaCompositing) { + ReactViewGroup view, boolean needsOffscreenAlphaCompositing) { view.setNeedsOffscreenAlphaCompositing(needsOffscreenAlphaCompositing); } @ReactPropGroup( - names = { - ViewProps.BORDER_WIDTH, - ViewProps.BORDER_LEFT_WIDTH, - ViewProps.BORDER_RIGHT_WIDTH, - ViewProps.BORDER_TOP_WIDTH, - ViewProps.BORDER_BOTTOM_WIDTH, - ViewProps.BORDER_START_WIDTH, - ViewProps.BORDER_END_WIDTH, - }, - defaultFloat = YogaConstants.UNDEFINED - ) + names = { + ViewProps.BORDER_WIDTH, + ViewProps.BORDER_LEFT_WIDTH, + ViewProps.BORDER_RIGHT_WIDTH, + ViewProps.BORDER_TOP_WIDTH, + ViewProps.BORDER_BOTTOM_WIDTH, + ViewProps.BORDER_START_WIDTH, + ViewProps.BORDER_END_WIDTH, + }, + defaultFloat = YogaConstants.UNDEFINED) public void setBorderWidth(ReactViewGroup view, int index, float width) { if (!YogaConstants.isUndefined(width) && width < 0) { width = YogaConstants.UNDEFINED; @@ -203,20 +207,20 @@ public class ReactViewManager extends ViewGroupManager { } @ReactPropGroup( - names = { - ViewProps.BORDER_COLOR, - ViewProps.BORDER_LEFT_COLOR, - ViewProps.BORDER_RIGHT_COLOR, - ViewProps.BORDER_TOP_COLOR, - ViewProps.BORDER_BOTTOM_COLOR, - ViewProps.BORDER_START_COLOR, - ViewProps.BORDER_END_COLOR - }, - customType = "Color" - ) + names = { + ViewProps.BORDER_COLOR, + ViewProps.BORDER_LEFT_COLOR, + ViewProps.BORDER_RIGHT_COLOR, + ViewProps.BORDER_TOP_COLOR, + ViewProps.BORDER_BOTTOM_COLOR, + ViewProps.BORDER_START_COLOR, + ViewProps.BORDER_END_COLOR + }, + customType = "Color") public void setBorderColor(ReactViewGroup view, int index, Integer color) { - float rgbComponent = color == null ? YogaConstants.UNDEFINED : (float) ((int)color & 0x00FFFFFF); - float alphaComponent = color == null ? YogaConstants.UNDEFINED : (float) ((int)color >>> 24); + float rgbComponent = + color == null ? YogaConstants.UNDEFINED : (float) ((int) color & 0x00FFFFFF); + float alphaComponent = color == null ? YogaConstants.UNDEFINED : (float) ((int) color >>> 24); view.setBorderColor(SPACING_TYPES[index], rgbComponent, alphaComponent); } @@ -230,22 +234,25 @@ public class ReactViewManager extends ViewGroupManager { public void setFocusable(final ReactViewGroup view, boolean focusable) { if (focusable) { view.setOnClickListener( - new View.OnClickListener() { - @Override - public void onClick(View v) { - final EventDispatcher mEventDispatcher = ((ReactContext)view.getContext()).getNativeModule(UIManagerModule.class) - .getEventDispatcher(); - mEventDispatcher.dispatchEvent(new ViewGroupClickEvent(view.getId())); - }}); + new View.OnClickListener() { + @Override + public void onClick(View v) { + final EventDispatcher mEventDispatcher = + ((ReactContext) view.getContext()) + .getNativeModule(UIManagerModule.class) + .getEventDispatcher(); + mEventDispatcher.dispatchEvent(new ViewGroupClickEvent(view.getId())); + } + }); // Clickable elements are focusable. On API 26, this is taken care by setClickable. // Explicitly calling setFocusable here for backward compatibility. view.setFocusable(true /*isFocusable*/); - } - else { + } else { view.setOnClickListener(null); view.setClickable(false); - // Don't set view.setFocusable(false) because we might still want it to be focusable for accessibiliy reasons + // Don't set view.setFocusable(false) because we might still want it to be focusable for + // accessibiliy reasons } } @@ -288,34 +295,36 @@ public class ReactViewManager extends ViewGroupManager { @Override public void receiveCommand(ReactViewGroup root, int commandId, @Nullable ReadableArray args) { switch (commandId) { - case CMD_HOTSPOT_UPDATE: { - handleHotspotUpdate(root, args); - break; - } - case CMD_SET_PRESSED: { - handleSetPressed(root, args); - break; - } + case CMD_HOTSPOT_UPDATE: + { + handleHotspotUpdate(root, args); + break; + } + case CMD_SET_PRESSED: + { + handleSetPressed(root, args); + break; + } } } @Override public void receiveCommand(ReactViewGroup root, String commandId, @Nullable ReadableArray args) { switch (commandId) { - case "hotspotUpdate": { - handleHotspotUpdate(root, args); - break; - } - case "setPressed": { - handleSetPressed(root, args); - break; - } + case "hotspotUpdate": + { + handleHotspotUpdate(root, args); + break; + } + case "setPressed": + { + handleSetPressed(root, args); + break; + } } } - private void handleSetPressed( - ReactViewGroup root, - @Nullable ReadableArray args) { + private void handleSetPressed(ReactViewGroup root, @Nullable ReadableArray args) { if (args == null || args.size() != 1) { throw new JSApplicationIllegalArgumentException( "Illegal number of arguments for 'setPressed' command"); @@ -323,9 +332,7 @@ public class ReactViewManager extends ViewGroupManager { root.setPressed(args.getBoolean(0)); } - private void handleHotspotUpdate( - ReactViewGroup root, - @Nullable ReadableArray args) { + private void handleHotspotUpdate(ReactViewGroup root, @Nullable ReadableArray args) { if (args == null || args.size() != 2) { throw new JSApplicationIllegalArgumentException( "Illegal number of arguments for 'updateHotspot' command"); diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/view/ViewGroupClickEvent.java b/ReactAndroid/src/main/java/com/facebook/react/views/view/ViewGroupClickEvent.java index 16fa8a2cce6..af6621aa710 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/view/ViewGroupClickEvent.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/view/ViewGroupClickEvent.java @@ -1,13 +1,10 @@ package com.facebook.react.views.view; - import com.facebook.react.bridge.Arguments; import com.facebook.react.uimanager.events.Event; import com.facebook.react.uimanager.events.RCTEventEmitter; -/** - * Represents a Click on the ReactViewGroup - */ +/** Represents a Click on the ReactViewGroup */ public class ViewGroupClickEvent extends Event { private static final String EVENT_NAME = "topClick"; diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/viewpager/PageScrollEvent.java b/ReactAndroid/src/main/java/com/facebook/react/views/viewpager/PageScrollEvent.java index a7ac123e617..869da50118f 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/viewpager/PageScrollEvent.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/viewpager/PageScrollEvent.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.viewpager; import com.facebook.react.bridge.Arguments; @@ -16,11 +15,10 @@ import com.facebook.react.uimanager.events.RCTEventEmitter; * Event emitted by {@link ReactViewPager} when user scrolls between pages (or when animating * between pages). * - * Additional data provided by this event: - * - position - index of first page from the left that is currently visible - * - offset - value from range [0,1) describing stage between page transitions. Value x means that - * (1 - x) fraction of the page at "position" index is visible, and x fraction of the next page - * is visible. + *

Additional data provided by this event: - position - index of first page from the left that is + * currently visible - offset - value from range [0,1) describing stage between page transitions. + * Value x means that (1 - x) fraction of the page at "position" index is visible, and x fraction of + * the next page is visible. */ /* package */ class PageScrollEvent extends Event { @@ -34,8 +32,7 @@ import com.facebook.react.uimanager.events.RCTEventEmitter; mPosition = position; // folly::toJson default options don't support serialize NaN or Infinite value - mOffset = (Float.isInfinite(offset) || Float.isNaN(offset)) - ? 0.0f : offset; + mOffset = (Float.isInfinite(offset) || Float.isNaN(offset)) ? 0.0f : offset; } @Override diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/viewpager/PageScrollStateChangedEvent.java b/ReactAndroid/src/main/java/com/facebook/react/views/viewpager/PageScrollStateChangedEvent.java index 295165da2a5..c5be6e04c18 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/viewpager/PageScrollStateChangedEvent.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/viewpager/PageScrollStateChangedEvent.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.viewpager; import com.facebook.react.bridge.Arguments; @@ -15,8 +14,7 @@ import com.facebook.react.uimanager.events.RCTEventEmitter; /** * Event emitted by {@link ReactViewPager} when user scrolling state changed. * - * Additional data provided by this event: - * - pageScrollState - {Idle,Dragging,Settling} + *

Additional data provided by this event: - pageScrollState - {Idle,Dragging,Settling} */ class PageScrollStateChangedEvent extends Event { diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/viewpager/PageSelectedEvent.java b/ReactAndroid/src/main/java/com/facebook/react/views/viewpager/PageSelectedEvent.java index ed8e3c4bdd4..c9cdd6ba3f6 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/viewpager/PageSelectedEvent.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/viewpager/PageSelectedEvent.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.viewpager; import com.facebook.react.bridge.Arguments; @@ -15,8 +14,7 @@ import com.facebook.react.uimanager.events.RCTEventEmitter; /** * Event emitted by {@link ReactViewPager} when selected page changes. * - * Additional data provided by this event: - * - position - index of page that has been selected + *

Additional data provided by this event: - position - index of page that has been selected */ /* package */ class PageSelectedEvent extends Event { diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/viewpager/ReactViewPager.java b/ReactAndroid/src/main/java/com/facebook/react/views/viewpager/ReactViewPager.java index 73ff7edc9af..b63cb9f8ca0 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/viewpager/ReactViewPager.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/viewpager/ReactViewPager.java @@ -1,17 +1,16 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.viewpager; -import androidx.viewpager.widget.PagerAdapter; -import androidx.viewpager.widget.ViewPager; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; +import androidx.viewpager.widget.PagerAdapter; +import androidx.viewpager.widget.ViewPager; import com.facebook.common.logging.FLog; import com.facebook.react.bridge.ReactContext; import com.facebook.react.common.ReactConstants; @@ -56,9 +55,7 @@ public class ReactViewPager extends ViewPager { setOffscreenPageLimit(mViews.size()); } - /** - * Replace a set of views to the ViewPager adapter and update the ViewPager - */ + /** Replace a set of views to the ViewPager adapter and update the ViewPager */ void setViews(List views) { mViews.clear(); mViews.addAll(views); @@ -70,9 +67,8 @@ public class ReactViewPager extends ViewPager { } /** - * Remove all the views from the adapter and de-parents them from the ViewPager - * After calling this, it is expected that notifyDataSetChanged should be called soon - * afterwards. + * Remove all the views from the adapter and de-parents them from the ViewPager After calling + * this, it is expected that notifyDataSetChanged should be called soon afterwards. */ void removeAllViewsFromAdapter(ViewPager pager) { mViews.clear(); @@ -94,8 +90,9 @@ public class ReactViewPager extends ViewPager { @Override public int getItemPosition(Object object) { // if we've removed all views, we want to return POSITION_NONE intentionally - return mIsViewPagerInIntentionallyInconsistentState || !mViews.contains(object) ? - POSITION_NONE : mViews.indexOf(object); + return mIsViewPagerInIntentionallyInconsistentState || !mViews.contains(object) + ? POSITION_NONE + : mViews.indexOf(object); } @Override @@ -120,15 +117,13 @@ public class ReactViewPager extends ViewPager { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { - mEventDispatcher.dispatchEvent( - new PageScrollEvent(getId(), position, positionOffset)); + mEventDispatcher.dispatchEvent(new PageScrollEvent(getId(), position, positionOffset)); } @Override public void onPageSelected(int position) { if (!mIsCurrentItemFromJs) { - mEventDispatcher.dispatchEvent( - new PageSelectedEvent(getId(), position)); + mEventDispatcher.dispatchEvent(new PageSelectedEvent(getId(), position)); } } @@ -148,8 +143,7 @@ public class ReactViewPager extends ViewPager { default: throw new IllegalStateException("Unsupported pageScrollState"); } - mEventDispatcher.dispatchEvent( - new PageScrollStateChangedEvent(getId(), pageScrollState)); + mEventDispatcher.dispatchEvent(new PageScrollStateChangedEvent(getId(), pageScrollState)); } } @@ -219,7 +213,6 @@ public class ReactViewPager extends ViewPager { mScrollEnabled = scrollEnabled; } - @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); @@ -229,15 +222,16 @@ public class ReactViewPager extends ViewPager { post(measureAndLayout); } - private final Runnable measureAndLayout = new Runnable() { - @Override - public void run() { - measure( + private final Runnable measureAndLayout = + new Runnable() { + @Override + public void run() { + measure( MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(getHeight(), MeasureSpec.EXACTLY)); - layout(getLeft(), getTop(), getRight(), getBottom()); - } - }; + layout(getLeft(), getTop(), getRight(), getBottom()); + } + }; /*package*/ void addViewToAdapter(View child, int index) { getAdapter().addView(child, index); diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/viewpager/ReactViewPagerManager.java b/ReactAndroid/src/main/java/com/facebook/react/views/viewpager/ReactViewPagerManager.java index a08cf3939bb..f14cecf575d 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/viewpager/ReactViewPagerManager.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/viewpager/ReactViewPagerManager.java @@ -1,16 +1,12 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.viewpager; -import java.util.Map; - import android.view.View; - import com.facebook.infer.annotation.Assertions; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.common.MapBuilder; @@ -19,12 +15,10 @@ import com.facebook.react.uimanager.PixelUtil; import com.facebook.react.uimanager.ThemedReactContext; import com.facebook.react.uimanager.ViewGroupManager; import com.facebook.react.uimanager.annotations.ReactProp; - +import java.util.Map; import javax.annotation.Nullable; -/** - * Instance of {@link ViewManager} that provides native {@link ViewPager} view. - */ +/** Instance of {@link ViewManager} that provides native {@link ViewPager} view. */ @ReactModule(name = ReactViewPagerManager.REACT_CLASS) public class ReactViewPagerManager extends ViewGroupManager { @@ -57,64 +51,60 @@ public class ReactViewPagerManager extends ViewGroupManager { public Map getExportedCustomDirectEventTypeConstants() { return MapBuilder.of( PageScrollEvent.EVENT_NAME, MapBuilder.of("registrationName", "onPageScroll"), - PageScrollStateChangedEvent.EVENT_NAME, MapBuilder.of("registrationName", "onPageScrollStateChanged"), + PageScrollStateChangedEvent.EVENT_NAME, + MapBuilder.of("registrationName", "onPageScrollStateChanged"), PageSelectedEvent.EVENT_NAME, MapBuilder.of("registrationName", "onPageSelected")); } @Override - public Map getCommandsMap() { + public Map getCommandsMap() { return MapBuilder.of( - "setPage", - COMMAND_SET_PAGE, - "setPageWithoutAnimation", - COMMAND_SET_PAGE_WITHOUT_ANIMATION); + "setPage", COMMAND_SET_PAGE, "setPageWithoutAnimation", COMMAND_SET_PAGE_WITHOUT_ANIMATION); } @Override public void receiveCommand( - ReactViewPager viewPager, - int commandType, - @Nullable ReadableArray args) { + ReactViewPager viewPager, int commandType, @Nullable ReadableArray args) { Assertions.assertNotNull(viewPager); Assertions.assertNotNull(args); switch (commandType) { - case COMMAND_SET_PAGE: { - viewPager.setCurrentItemFromJs(args.getInt(0), true); - return; - } - case COMMAND_SET_PAGE_WITHOUT_ANIMATION: { - viewPager.setCurrentItemFromJs(args.getInt(0), false); - return; - } + case COMMAND_SET_PAGE: + { + viewPager.setCurrentItemFromJs(args.getInt(0), true); + return; + } + case COMMAND_SET_PAGE_WITHOUT_ANIMATION: + { + viewPager.setCurrentItemFromJs(args.getInt(0), false); + return; + } default: - throw new IllegalArgumentException(String.format( - "Unsupported command %d received by %s.", - commandType, - getClass().getSimpleName())); + throw new IllegalArgumentException( + String.format( + "Unsupported command %d received by %s.", commandType, getClass().getSimpleName())); } } @Override public void receiveCommand( - ReactViewPager viewPager, - String commandType, - @Nullable ReadableArray args) { + ReactViewPager viewPager, String commandType, @Nullable ReadableArray args) { Assertions.assertNotNull(viewPager); Assertions.assertNotNull(args); switch (commandType) { - case "setPage": { - viewPager.setCurrentItemFromJs(args.getInt(0), true); - return; - } - case "setPageWithoutAnimation": { - viewPager.setCurrentItemFromJs(args.getInt(0), false); - return; - } + case "setPage": + { + viewPager.setCurrentItemFromJs(args.getInt(0), true); + return; + } + case "setPageWithoutAnimation": + { + viewPager.setCurrentItemFromJs(args.getInt(0), false); + return; + } default: - throw new IllegalArgumentException(String.format( - "Unsupported command %d received by %s.", - commandType, - getClass().getSimpleName())); + throw new IllegalArgumentException( + String.format( + "Unsupported command %d received by %s.", commandType, getClass().getSimpleName())); } } diff --git a/ReactAndroid/src/main/java/com/facebook/systrace/Systrace.java b/ReactAndroid/src/main/java/com/facebook/systrace/Systrace.java index fd9a575ae15..4024dd90b00 100644 --- a/ReactAndroid/src/main/java/com/facebook/systrace/Systrace.java +++ b/ReactAndroid/src/main/java/com/facebook/systrace/Systrace.java @@ -1,18 +1,17 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.systrace; import android.os.Build; import android.os.Trace; /** - * Systrace stub that mostly does nothing but delegates to Trace for beginning/ending sections. - * The internal version of this file has not been opensourced yet. + * Systrace stub that mostly does nothing but delegates to Trace for beginning/ending sections. The + * internal version of this file has not been opensourced yet. */ public class Systrace { @@ -38,21 +37,15 @@ public class Systrace { } } - public static void registerListener(TraceListener listener) { - } + public static void registerListener(TraceListener listener) {} - public static void unregisterListener(TraceListener listener) { - } + public static void unregisterListener(TraceListener listener) {} public static boolean isTracing(long tag) { return false; } - public static void traceInstant( - long tag, - final String title, - EventScope scope) { - } + public static void traceInstant(long tag, final String title, EventScope scope) {} public static void beginSection(long tag, final String sectionName) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { @@ -66,45 +59,21 @@ public class Systrace { } } - public static void beginAsyncSection( - long tag, - final String sectionName, - final int cookie) { - } + public static void beginAsyncSection(long tag, final String sectionName, final int cookie) {} public static void beginAsyncSection( long tag, final String sectionName, final int cookie, final long startNanos) {} - public static void endAsyncSection( - long tag, - final String sectionName, - final int cookie) { - } + public static void endAsyncSection(long tag, final String sectionName, final int cookie) {} public static void endAsyncSection( long tag, final String sectionName, final int cookie, final long endNanos) {} - public static void traceCounter( - long tag, - final String counterName, - final int counterValue) { - } + public static void traceCounter(long tag, final String counterName, final int counterValue) {} - public static void startAsyncFlow( - long tag, - final String sectionName, - final int cookie) { - } + public static void startAsyncFlow(long tag, final String sectionName, final int cookie) {} - public static void stepAsyncFlow( - long tag, - final String sectionName, - final int cookie) { - } + public static void stepAsyncFlow(long tag, final String sectionName, final int cookie) {} - public static void endAsyncFlow( - long tag, - final String sectionName, - final int cookie) { - } + public static void endAsyncFlow(long tag, final String sectionName, final int cookie) {} } diff --git a/ReactAndroid/src/main/java/com/facebook/systrace/SystraceMessage.java b/ReactAndroid/src/main/java/com/facebook/systrace/SystraceMessage.java index 448d972780e..8b33b078662 100644 --- a/ReactAndroid/src/main/java/com/facebook/systrace/SystraceMessage.java +++ b/ReactAndroid/src/main/java/com/facebook/systrace/SystraceMessage.java @@ -1,15 +1,12 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.systrace; -/** - * Systrace stub. - */ +/** Systrace stub. */ public final class SystraceMessage { private static final Builder NOOP_BUILDER = new NoopBuilder(); @@ -22,7 +19,7 @@ public final class SystraceMessage { return NOOP_BUILDER; } - public static abstract class Builder { + public abstract static class Builder { public abstract void flush(); @@ -41,8 +38,7 @@ public final class SystraceMessage { private static class NoopBuilder extends Builder { @Override - public void flush() { - } + public void flush() {} @Override public Builder arg(String key, Object value) { diff --git a/ReactAndroid/src/main/java/com/facebook/systrace/TraceListener.java b/ReactAndroid/src/main/java/com/facebook/systrace/TraceListener.java index 7c217a22613..814a75b31ce 100644 --- a/ReactAndroid/src/main/java/com/facebook/systrace/TraceListener.java +++ b/ReactAndroid/src/main/java/com/facebook/systrace/TraceListener.java @@ -7,5 +7,6 @@ package com.facebook.systrace; public interface TraceListener { void onTraceStarted(); + void onTraceStopped(); } diff --git a/ReactAndroid/src/test/java/com/facebook/common/logging/FakeLoggingDelegate.java b/ReactAndroid/src/test/java/com/facebook/common/logging/FakeLoggingDelegate.java index 3e944404b7e..1a2cc03c0bf 100644 --- a/ReactAndroid/src/test/java/com/facebook/common/logging/FakeLoggingDelegate.java +++ b/ReactAndroid/src/test/java/com/facebook/common/logging/FakeLoggingDelegate.java @@ -1,16 +1,14 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.common.logging; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; - import javax.annotation.Nullable; public final class FakeLoggingDelegate implements LoggingDelegate { @@ -21,11 +19,7 @@ public final class FakeLoggingDelegate implements LoggingDelegate { public final String msg; public final @Nullable Throwable tr; - private LogLine( - int priority, - String tag, - String msg, - @Nullable Throwable tr) { + private LogLine(int priority, String tag, String msg, @Nullable Throwable tr) { this.priority = priority; this.tag = tag; @@ -34,35 +28,30 @@ public final class FakeLoggingDelegate implements LoggingDelegate { } } - public static final int ASSERT = FLog.ASSERT; - public static final int DEBUG = FLog.DEBUG; - public static final int ERROR = FLog.ERROR; - public static final int INFO = FLog.INFO; + public static final int ASSERT = FLog.ASSERT; + public static final int DEBUG = FLog.DEBUG; + public static final int ERROR = FLog.ERROR; + public static final int INFO = FLog.INFO; public static final int VERBOSE = FLog.VERBOSE; - public static final int WARN = FLog.WARN; + public static final int WARN = FLog.WARN; /** - * There is no log level for Terrible Failures (we emit them at the Error - * Log-level), but to test that WTF errors are being logged, we are making up - * a new log level here, guaranteed to be larger than any of the other log - * levels. + * There is no log level for Terrible Failures (we emit them at the Error Log-level), but to test + * that WTF errors are being logged, we are making up a new log level here, guaranteed to be + * larger than any of the other log levels. */ public static final int WTF = - 1 + Collections.max(Arrays.asList(ASSERT, DEBUG, ERROR, INFO, VERBOSE, WARN)); + 1 + Collections.max(Arrays.asList(ASSERT, DEBUG, ERROR, INFO, VERBOSE, WARN)); private int mMinLogLevel = FLog.VERBOSE; private final ArrayList mLogs = new ArrayList<>(); /** Test Harness */ - private static boolean matchLogQuery( - int priority, - String tag, - @Nullable String throwMsg, - LogLine line) { + int priority, String tag, @Nullable String throwMsg, LogLine line) { return priority == line.priority - && tag.equals(line.tag) - && (throwMsg == null || throwMsg.equals(line.tr.getMessage())); + && tag.equals(line.tag) + && (throwMsg == null || throwMsg.equals(line.tr.getMessage())); } public boolean logContains(int priority, String tag, String throwMsg) { @@ -76,7 +65,6 @@ public final class FakeLoggingDelegate implements LoggingDelegate { } /** LoggingDelegate API */ - public int getMinimumLoggingLevel() { return mMinLogLevel; } diff --git a/ReactAndroid/src/test/java/com/facebook/react/CompositeReactPackageTest.java b/ReactAndroid/src/test/java/com/facebook/react/CompositeReactPackageTest.java index 788d935547a..8a0cdf64604 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/CompositeReactPackageTest.java +++ b/ReactAndroid/src/test/java/com/facebook/react/CompositeReactPackageTest.java @@ -1,44 +1,38 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react; -import java.util.Arrays; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import com.facebook.react.bridge.NativeModule; -import com.facebook.react.bridge.ReactApplicationContext; -import com.facebook.react.uimanager.ViewManager; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.Rule; - -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.modules.junit4.rule.PowerMockRule; -import org.robolectric.RobolectricTestRunner; - import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import com.facebook.react.bridge.NativeModule; +import com.facebook.react.bridge.ReactApplicationContext; +import com.facebook.react.uimanager.ViewManager; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.modules.junit4.rule.PowerMockRule; +import org.robolectric.RobolectricTestRunner; + @RunWith(RobolectricTestRunner.class) @PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "androidx.*", "android.*"}) public class CompositeReactPackageTest { - @Rule - public PowerMockRule rule = new PowerMockRule(); + @Rule public PowerMockRule rule = new PowerMockRule(); @Mock ReactPackage packageNo1; @Mock ReactPackage packageNo2; @@ -99,11 +93,11 @@ public class CompositeReactPackageTest { NativeModule moduleNo4 = mock(NativeModule.class); when(moduleNo4.getName()).thenReturn("ModuleNo4"); - when(packageNo1.createNativeModules(reactContext)).thenReturn( - Arrays.asList(new NativeModule[]{moduleNo1, moduleNo2})); + when(packageNo1.createNativeModules(reactContext)) + .thenReturn(Arrays.asList(new NativeModule[] {moduleNo1, moduleNo2})); - when(packageNo2.createNativeModules(reactContext)).thenReturn( - Arrays.asList(new NativeModule[]{moduleNo3, moduleNo4})); + when(packageNo2.createNativeModules(reactContext)) + .thenReturn(Arrays.asList(new NativeModule[] {moduleNo3, moduleNo4})); // When List compositeModules = composite.createNativeModules(reactContext); @@ -112,8 +106,8 @@ public class CompositeReactPackageTest { // Wrapping lists into sets to be order-independent. // Note that there should be no module2 returned. - Set expected = new HashSet<>( - Arrays.asList(new NativeModule[]{moduleNo1, moduleNo3, moduleNo4})); + Set expected = + new HashSet<>(Arrays.asList(new NativeModule[] {moduleNo1, moduleNo3, moduleNo4})); Set actual = new HashSet<>(compositeModules); assertEquals(expected, actual); @@ -139,11 +133,11 @@ public class CompositeReactPackageTest { ViewManager managerNo4 = mock(ViewManager.class); when(managerNo4.getName()).thenReturn("ManagerNo4"); - when(packageNo1.createViewManagers(reactContext)).thenReturn( - Arrays.asList(new ViewManager[]{managerNo1, managerNo2})); + when(packageNo1.createViewManagers(reactContext)) + .thenReturn(Arrays.asList(new ViewManager[] {managerNo1, managerNo2})); - when(packageNo2.createViewManagers(reactContext)).thenReturn( - Arrays.asList(new ViewManager[]{managerNo3, managerNo4})); + when(packageNo2.createViewManagers(reactContext)) + .thenReturn(Arrays.asList(new ViewManager[] {managerNo3, managerNo4})); // When List compositeModules = composite.createViewManagers(reactContext); @@ -152,9 +146,8 @@ public class CompositeReactPackageTest { // Wrapping lists into sets to be order-independent. // Note that there should be no managerNo2 returned. - Set expected = new HashSet<>( - Arrays.asList(new ViewManager[]{managerNo1, managerNo3, managerNo4}) - ); + Set expected = + new HashSet<>(Arrays.asList(new ViewManager[] {managerNo1, managerNo3, managerNo4})); Set actual = new HashSet<>(compositeModules); assertEquals(expected, actual); diff --git a/ReactAndroid/src/test/java/com/facebook/react/RootViewTest.java b/ReactAndroid/src/test/java/com/facebook/react/RootViewTest.java index 99975aeb61e..671bbdcee71 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/RootViewTest.java +++ b/ReactAndroid/src/test/java/com/facebook/react/RootViewTest.java @@ -1,46 +1,11 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react; -import java.util.Date; - -import android.util.DisplayMetrics; -import android.view.MotionEvent; - -import com.facebook.react.bridge.Arguments; -import com.facebook.react.bridge.ReactContext; -import com.facebook.react.bridge.ReactApplicationContext; -import com.facebook.react.bridge.CatalystInstance; -import com.facebook.react.bridge.ReactTestHelper; -import com.facebook.react.bridge.JavaOnlyArray; -import com.facebook.react.bridge.JavaOnlyMap; -import com.facebook.react.bridge.WritableArray; -import com.facebook.react.common.SystemClock; -import com.facebook.react.uimanager.UIManagerModule; -import com.facebook.react.uimanager.DisplayMetricsHolder; -import com.facebook.react.uimanager.events.Event; -import com.facebook.react.uimanager.events.EventDispatcher; -import com.facebook.react.uimanager.events.RCTEventEmitter; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.Rule; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.modules.junit4.rule.PowerMockRule; -import org.robolectric.RobolectricTestRunner; -import org.robolectric.RuntimeEnvironment; - import static org.fest.assertions.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; @@ -50,13 +15,42 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; +import android.view.MotionEvent; +import com.facebook.react.bridge.Arguments; +import com.facebook.react.bridge.CatalystInstance; +import com.facebook.react.bridge.JavaOnlyArray; +import com.facebook.react.bridge.JavaOnlyMap; +import com.facebook.react.bridge.ReactApplicationContext; +import com.facebook.react.bridge.ReactContext; +import com.facebook.react.bridge.ReactTestHelper; +import com.facebook.react.bridge.WritableArray; +import com.facebook.react.common.SystemClock; +import com.facebook.react.uimanager.DisplayMetricsHolder; +import com.facebook.react.uimanager.UIManagerModule; +import com.facebook.react.uimanager.events.Event; +import com.facebook.react.uimanager.events.EventDispatcher; +import com.facebook.react.uimanager.events.RCTEventEmitter; +import java.util.Date; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.rule.PowerMockRule; +import org.robolectric.RobolectricTestRunner; +import org.robolectric.RuntimeEnvironment; + @PrepareForTest({Arguments.class, SystemClock.class}) @RunWith(RobolectricTestRunner.class) @PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "androidx.*", "android.*"}) public class RootViewTest { - @Rule - public PowerMockRule rule = new PowerMockRule(); + @Rule public PowerMockRule rule = new PowerMockRule(); private ReactContext mReactContext; private CatalystInstance mCatalystInstanceMock; @@ -65,25 +59,31 @@ public class RootViewTest { public void setUp() { final long ts = SystemClock.uptimeMillis(); PowerMockito.mockStatic(Arguments.class); - PowerMockito.when(Arguments.createArray()).thenAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - return new JavaOnlyArray(); - } - }); - PowerMockito.when(Arguments.createMap()).thenAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - return new JavaOnlyMap(); - } - }); + PowerMockito.when(Arguments.createArray()) + .thenAnswer( + new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + return new JavaOnlyArray(); + } + }); + PowerMockito.when(Arguments.createMap()) + .thenAnswer( + new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + return new JavaOnlyMap(); + } + }); PowerMockito.mockStatic(SystemClock.class); - PowerMockito.when(SystemClock.uptimeMillis()).thenAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - return ts; - } - }); + PowerMockito.when(SystemClock.uptimeMillis()) + .thenAnswer( + new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + return ts; + } + }); mCatalystInstanceMock = ReactTestHelper.createMockCatalystInstance(); mReactContext = new ReactApplicationContext(RuntimeEnvironment.application); @@ -103,8 +103,7 @@ public class RootViewTest { UIManagerModule uiManager = mock(UIManagerModule.class); EventDispatcher eventDispatcher = mock(EventDispatcher.class); RCTEventEmitter eventEmitterModuleMock = mock(RCTEventEmitter.class); - when(mCatalystInstanceMock.getNativeModule(UIManagerModule.class)) - .thenReturn(uiManager); + when(mCatalystInstanceMock.getNativeModule(UIManagerModule.class)).thenReturn(uiManager); when(uiManager.getEventDispatcher()).thenReturn(eventDispatcher); int rootViewId = 7; @@ -117,8 +116,7 @@ public class RootViewTest { long ts = SystemClock.uptimeMillis(); // Test ACTION_DOWN event - rootView.onTouchEvent( - MotionEvent.obtain(100, ts, MotionEvent.ACTION_DOWN, 0, 0, 0)); + rootView.onTouchEvent(MotionEvent.obtain(100, ts, MotionEvent.ACTION_DOWN, 0, 0, 0)); ArgumentCaptor downEventCaptor = ArgumentCaptor.forClass(Event.class); verify(eventDispatcher).dispatchEvent(downEventCaptor.capture()); @@ -128,29 +126,29 @@ public class RootViewTest { ArgumentCaptor downActionTouchesArgCaptor = ArgumentCaptor.forClass(JavaOnlyArray.class); - verify(eventEmitterModuleMock).receiveTouches( - eq("topTouchStart"), - downActionTouchesArgCaptor.capture(), - any(JavaOnlyArray.class)); + verify(eventEmitterModuleMock) + .receiveTouches( + eq("topTouchStart"), downActionTouchesArgCaptor.capture(), any(JavaOnlyArray.class)); verifyNoMoreInteractions(eventEmitterModuleMock); assertThat(downActionTouchesArgCaptor.getValue().size()).isEqualTo(1); - assertThat(downActionTouchesArgCaptor.getValue().getMap(0)).isEqualTo( - JavaOnlyMap.of( - "pageX", - 0., - "pageY", - 0., - "locationX", - 0., - "locationY", - 0., - "target", - rootViewId, - "timestamp", - (double) ts, - "identifier", - 0.)); + assertThat(downActionTouchesArgCaptor.getValue().getMap(0)) + .isEqualTo( + JavaOnlyMap.of( + "pageX", + 0., + "pageY", + 0., + "locationX", + 0., + "locationY", + 0., + "target", + rootViewId, + "timestamp", + (double) ts, + "identifier", + 0.)); // Test ACTION_UP event reset(eventEmitterModuleMock, eventDispatcher); @@ -159,35 +157,34 @@ public class RootViewTest { ArgumentCaptor upActionTouchesArgCaptor = ArgumentCaptor.forClass(JavaOnlyArray.class); - rootView.onTouchEvent( - MotionEvent.obtain(50, ts, MotionEvent.ACTION_UP, 0, 0, 0)); + rootView.onTouchEvent(MotionEvent.obtain(50, ts, MotionEvent.ACTION_UP, 0, 0, 0)); verify(eventDispatcher).dispatchEvent(upEventCaptor.capture()); verifyNoMoreInteractions(eventDispatcher); upEventCaptor.getValue().dispatch(eventEmitterModuleMock); - verify(eventEmitterModuleMock).receiveTouches( - eq("topTouchEnd"), - upActionTouchesArgCaptor.capture(), - any(WritableArray.class)); + verify(eventEmitterModuleMock) + .receiveTouches( + eq("topTouchEnd"), upActionTouchesArgCaptor.capture(), any(WritableArray.class)); verifyNoMoreInteractions(eventEmitterModuleMock); assertThat(upActionTouchesArgCaptor.getValue().size()).isEqualTo(1); - assertThat(upActionTouchesArgCaptor.getValue().getMap(0)).isEqualTo( - JavaOnlyMap.of( - "pageX", - 0., - "pageY", - 0., - "locationX", - 0., - "locationY", - 0., - "target", - rootViewId, - "timestamp", - (double) ts, - "identifier", - 0.)); + assertThat(upActionTouchesArgCaptor.getValue().getMap(0)) + .isEqualTo( + JavaOnlyMap.of( + "pageX", + 0., + "pageY", + 0., + "locationX", + 0., + "locationY", + 0., + "target", + rootViewId, + "timestamp", + (double) ts, + "identifier", + 0.)); // Test other action reset(eventDispatcher); diff --git a/ReactAndroid/src/test/java/com/facebook/react/animated/NativeAnimatedInterpolationTest.java b/ReactAndroid/src/test/java/com/facebook/react/animated/NativeAnimatedInterpolationTest.java index a43308b7d41..88b9506f90b 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/animated/NativeAnimatedInterpolationTest.java +++ b/ReactAndroid/src/test/java/com/facebook/react/animated/NativeAnimatedInterpolationTest.java @@ -1,18 +1,17 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.animated; +import static org.fest.assertions.api.Assertions.assertThat; + import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; -import static org.fest.assertions.api.Assertions.assertThat; - /** * Tests method used by {@link InterpolationAnimatedNode} to interpolate value of the input nodes. */ @@ -21,12 +20,11 @@ public class NativeAnimatedInterpolationTest { private double simpleInterpolation(double value, double[] input, double[] output) { return InterpolationAnimatedNode.interpolate( - value, - input, - output, - InterpolationAnimatedNode.EXTRAPOLATE_TYPE_EXTEND, - InterpolationAnimatedNode.EXTRAPOLATE_TYPE_EXTEND - ); + value, + input, + output, + InterpolationAnimatedNode.EXTRAPOLATE_TYPE_EXTEND, + InterpolationAnimatedNode.EXTRAPOLATE_TYPE_EXTEND); } @Test @@ -82,39 +80,43 @@ public class NativeAnimatedInterpolationTest { public void testClampExtrapolate() { double[] input = new double[] {10d, 20d}; double[] output = new double[] {0d, 1d}; - assertThat(InterpolationAnimatedNode.interpolate( - 30d, - input, - output, - InterpolationAnimatedNode.EXTRAPOLATE_TYPE_CLAMP, - InterpolationAnimatedNode.EXTRAPOLATE_TYPE_CLAMP - )).isEqualTo(1); - assertThat(InterpolationAnimatedNode.interpolate( - 5d, - input, - output, - InterpolationAnimatedNode.EXTRAPOLATE_TYPE_CLAMP, - InterpolationAnimatedNode.EXTRAPOLATE_TYPE_CLAMP - )).isEqualTo(0); + assertThat( + InterpolationAnimatedNode.interpolate( + 30d, + input, + output, + InterpolationAnimatedNode.EXTRAPOLATE_TYPE_CLAMP, + InterpolationAnimatedNode.EXTRAPOLATE_TYPE_CLAMP)) + .isEqualTo(1); + assertThat( + InterpolationAnimatedNode.interpolate( + 5d, + input, + output, + InterpolationAnimatedNode.EXTRAPOLATE_TYPE_CLAMP, + InterpolationAnimatedNode.EXTRAPOLATE_TYPE_CLAMP)) + .isEqualTo(0); } @Test public void testIdentityExtrapolate() { double[] input = new double[] {10d, 20d}; double[] output = new double[] {0d, 1d}; - assertThat(InterpolationAnimatedNode.interpolate( - 30d, - input, - output, - InterpolationAnimatedNode.EXTRAPOLATE_TYPE_IDENTITY, - InterpolationAnimatedNode.EXTRAPOLATE_TYPE_IDENTITY - )).isEqualTo(30); - assertThat(InterpolationAnimatedNode.interpolate( - 5d, - input, - output, - InterpolationAnimatedNode.EXTRAPOLATE_TYPE_IDENTITY, - InterpolationAnimatedNode.EXTRAPOLATE_TYPE_IDENTITY - )).isEqualTo(5); + assertThat( + InterpolationAnimatedNode.interpolate( + 30d, + input, + output, + InterpolationAnimatedNode.EXTRAPOLATE_TYPE_IDENTITY, + InterpolationAnimatedNode.EXTRAPOLATE_TYPE_IDENTITY)) + .isEqualTo(30); + assertThat( + InterpolationAnimatedNode.interpolate( + 5d, + input, + output, + InterpolationAnimatedNode.EXTRAPOLATE_TYPE_IDENTITY, + InterpolationAnimatedNode.EXTRAPOLATE_TYPE_IDENTITY)) + .isEqualTo(5); } } diff --git a/ReactAndroid/src/test/java/com/facebook/react/animated/NativeAnimatedNodeTraversalTest.java b/ReactAndroid/src/test/java/com/facebook/react/animated/NativeAnimatedNodeTraversalTest.java index b0ea8c01b44..1ba4a368f6b 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/animated/NativeAnimatedNodeTraversalTest.java +++ b/ReactAndroid/src/test/java/com/facebook/react/animated/NativeAnimatedNodeTraversalTest.java @@ -1,26 +1,33 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.animated; +import static org.fest.assertions.api.Assertions.assertThat; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyInt; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.atMost; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; + import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.Callback; import com.facebook.react.bridge.JavaOnlyArray; import com.facebook.react.bridge.JavaOnlyMap; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.common.MapBuilder; -import com.facebook.react.uimanager.UIImplementation; import com.facebook.react.uimanager.UIManagerModule; import com.facebook.react.uimanager.events.Event; import com.facebook.react.uimanager.events.EventDispatcher; import com.facebook.react.uimanager.events.RCTEventEmitter; - import java.util.Map; - import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -34,20 +41,7 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.rule.PowerMockRule; import org.robolectric.RobolectricTestRunner; -import static org.fest.assertions.api.Assertions.assertThat; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyInt; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.atMost; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.reset; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; - -/** - * Tests the animated nodes graph traversal algorithm from {@link NativeAnimatedNodesManager}. - */ +/** Tests the animated nodes graph traversal algorithm from {@link NativeAnimatedNodesManager}. */ @PrepareForTest({Arguments.class}) @RunWith(RobolectricTestRunner.class) @PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "androidx.*", "android.*"}) @@ -56,8 +50,7 @@ public class NativeAnimatedNodeTraversalTest { private static long FRAME_LEN_NANOS = 1000000000L / 60L; private static long INITIAL_FRAME_TIME_NANOS = 14599233201256L; /* random */ - @Rule - public PowerMockRule rule = new PowerMockRule(); + @Rule public PowerMockRule rule = new PowerMockRule(); private long mFrameTimeNanos; private UIManagerModule mUIManagerMock; @@ -71,55 +64,66 @@ public class NativeAnimatedNodeTraversalTest { @Before public void setUp() { PowerMockito.mockStatic(Arguments.class); - PowerMockito.when(Arguments.createArray()).thenAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - return new JavaOnlyArray(); - } - }); - PowerMockito.when(Arguments.createMap()).thenAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - return new JavaOnlyMap(); - } - }); + PowerMockito.when(Arguments.createArray()) + .thenAnswer( + new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + return new JavaOnlyArray(); + } + }); + PowerMockito.when(Arguments.createMap()) + .thenAnswer( + new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + return new JavaOnlyMap(); + } + }); mFrameTimeNanos = INITIAL_FRAME_TIME_NANOS; mUIManagerMock = mock(UIManagerModule.class); mEventDispatcherMock = mock(EventDispatcher.class); - PowerMockito.when(mUIManagerMock.getEventDispatcher()).thenAnswer(new Answer() { - @Override - public EventDispatcher answer(InvocationOnMock invocation) throws Throwable { - return mEventDispatcherMock; - } - }); - PowerMockito.when(mUIManagerMock.getConstants()).thenAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - return MapBuilder.of("customDirectEventTypes", MapBuilder.newHashMap()); - } - }); - PowerMockito - .when(mUIManagerMock.getDirectEventNamesResolver()) - .thenAnswer(new Answer() { - @Override - public UIManagerModule.CustomEventNamesResolver answer(InvocationOnMock invocation) throws Throwable { - return new UIManagerModule.CustomEventNamesResolver() { - @Override - public String resolveCustomEventName(String eventName) { - Map directEventTypes = - (Map) mUIManagerMock.getConstants().get("customDirectEventTypes"); - if (directEventTypes != null) { - Map customEventType = (Map) directEventTypes.get(eventName); - if (customEventType != null) { - return customEventType.get("registrationName"); + PowerMockito.when(mUIManagerMock.getEventDispatcher()) + .thenAnswer( + new Answer() { + @Override + public EventDispatcher answer(InvocationOnMock invocation) throws Throwable { + return mEventDispatcherMock; } - } - return eventName; - } - }; - } - }); + }); + PowerMockito.when(mUIManagerMock.getConstants()) + .thenAnswer( + new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + return MapBuilder.of("customDirectEventTypes", MapBuilder.newHashMap()); + } + }); + PowerMockito.when(mUIManagerMock.getDirectEventNamesResolver()) + .thenAnswer( + new Answer() { + @Override + public UIManagerModule.CustomEventNamesResolver answer(InvocationOnMock invocation) + throws Throwable { + return new UIManagerModule.CustomEventNamesResolver() { + @Override + public String resolveCustomEventName(String eventName) { + Map directEventTypes = + (Map) + mUIManagerMock.getConstants().get("customDirectEventTypes"); + if (directEventTypes != null) { + Map customEventType = + (Map) directEventTypes.get(eventName); + if (customEventType != null) { + return customEventType.get("registrationName"); + } + } + return eventName; + } + }; + } + }); mNativeAnimatedNodesManager = new NativeAnimatedNodesManager(mUIManagerMock); } @@ -127,19 +131,16 @@ public class NativeAnimatedNodeTraversalTest { * Generates a simple animated nodes graph and attaches the props node to a given {@param viewTag} * Parameter {@param opacity} is used as a initial value for the "opacity" attribute. * - * Nodes are connected as follows (nodes IDs in parens): - * ValueNode(1) -> StyleNode(2) -> PropNode(3) + *

Nodes are connected as follows (nodes IDs in parens): ValueNode(1) -> StyleNode(2) -> + * PropNode(3) */ private void createSimpleAnimatedViewWithOpacity(int viewTag, double opacity) { mNativeAnimatedNodesManager.createAnimatedNode( - 1, - JavaOnlyMap.of("type", "value", "value", opacity, "offset", 0d)); + 1, JavaOnlyMap.of("type", "value", "value", opacity, "offset", 0d)); mNativeAnimatedNodesManager.createAnimatedNode( - 2, - JavaOnlyMap.of("type", "style", "style", JavaOnlyMap.of("opacity", 1))); + 2, JavaOnlyMap.of("type", "style", "style", JavaOnlyMap.of("opacity", 1))); mNativeAnimatedNodesManager.createAnimatedNode( - 3, - JavaOnlyMap.of("type", "props", "props", JavaOnlyMap.of("style", 2))); + 3, JavaOnlyMap.of("type", "props", "props", JavaOnlyMap.of("style", 2))); mNativeAnimatedNodesManager.connectAnimatedNodes(1, 2); mNativeAnimatedNodesManager.connectAnimatedNodes(2, 3); mNativeAnimatedNodesManager.connectAnimatedNodeToView(3, viewTag); @@ -152,21 +153,15 @@ public class NativeAnimatedNodeTraversalTest { JavaOnlyArray frames = JavaOnlyArray.of(0d, 0.2d, 0.4d, 0.6d, 0.8d, 1d); Callback animationCallback = mock(Callback.class); mNativeAnimatedNodesManager.startAnimatingNode( - 1, - 1, - JavaOnlyMap.of("type", "frames", "frames", frames, "toValue", 1d), - animationCallback); + 1, 1, JavaOnlyMap.of("type", "frames", "frames", frames, "toValue", 1d), animationCallback); - ArgumentCaptor stylesCaptor = - ArgumentCaptor.forClass(ReadableMap.class); + ArgumentCaptor stylesCaptor = ArgumentCaptor.forClass(ReadableMap.class); for (int i = 0; i < frames.size(); i++) { reset(mUIManagerMock); mNativeAnimatedNodesManager.runUpdates(nextFrameTime()); - verify(mUIManagerMock) - .synchronouslyUpdateViewOnUIThread(eq(1000), stylesCaptor.capture()); - assertThat(stylesCaptor.getValue().getDouble("opacity")) - .isEqualTo(frames.getDouble(i)); + verify(mUIManagerMock).synchronouslyUpdateViewOnUIThread(eq(1000), stylesCaptor.capture()); + assertThat(stylesCaptor.getValue().getDouble("opacity")).isEqualTo(frames.getDouble(i)); } reset(mUIManagerMock); @@ -181,22 +176,19 @@ public class NativeAnimatedNodeTraversalTest { JavaOnlyArray frames = JavaOnlyArray.of(0d, 0.2d, 0.4d, 0.6d, 0.8d, 1d); Callback animationCallback = mock(Callback.class); mNativeAnimatedNodesManager.startAnimatingNode( - 1, - 1, - JavaOnlyMap.of("type", "frames", "frames", frames, "toValue", 1d, "iterations", 5), - animationCallback); + 1, + 1, + JavaOnlyMap.of("type", "frames", "frames", frames, "toValue", 1d, "iterations", 5), + animationCallback); - ArgumentCaptor stylesCaptor = - ArgumentCaptor.forClass(ReadableMap.class); + ArgumentCaptor stylesCaptor = ArgumentCaptor.forClass(ReadableMap.class); for (int iteration = 0; iteration < 5; iteration++) { for (int i = 0; i < frames.size(); i++) { reset(mUIManagerMock); mNativeAnimatedNodesManager.runUpdates(nextFrameTime()); - verify(mUIManagerMock) - .synchronouslyUpdateViewOnUIThread(eq(1000), stylesCaptor.capture()); - assertThat(stylesCaptor.getValue().getDouble("opacity")) - .isEqualTo(frames.getDouble(i)); + verify(mUIManagerMock).synchronouslyUpdateViewOnUIThread(eq(1000), stylesCaptor.capture()); + assertThat(stylesCaptor.getValue().getDouble("opacity")).isEqualTo(frames.getDouble(i)); } } @@ -217,10 +209,10 @@ public class NativeAnimatedNodeTraversalTest { mNativeAnimatedNodesManager.startListeningToAnimatedNodeValue(nodeId, valueListener); mNativeAnimatedNodesManager.startAnimatingNode( - 1, - nodeId, - JavaOnlyMap.of("type", "frames", "frames", frames, "toValue", 1d), - animationCallback); + 1, + nodeId, + JavaOnlyMap.of("type", "frames", "frames", frames, "toValue", 1d), + animationCallback); mNativeAnimatedNodesManager.runUpdates(nextFrameTime()); verify(valueListener).onValueUpdate(eq(0d)); @@ -244,10 +236,10 @@ public class NativeAnimatedNodeTraversalTest { mNativeAnimatedNodesManager.startListeningToAnimatedNodeValue(nodeId, valueListener); mNativeAnimatedNodesManager.startAnimatingNode( - 1, - nodeId, - JavaOnlyMap.of("type", "frames", "frames", frames, "toValue", 1d), - animationCallback); + 1, + nodeId, + JavaOnlyMap.of("type", "frames", "frames", frames, "toValue", 1d), + animationCallback); for (int i = 0; i < frames.size(); i++) { reset(valueListener); @@ -260,18 +252,14 @@ public class NativeAnimatedNodeTraversalTest { verifyNoMoreInteractions(valueListener); } - public void performSpringAnimationTestWithConfig(JavaOnlyMap config, boolean testForCriticallyDamped) { + public void performSpringAnimationTestWithConfig( + JavaOnlyMap config, boolean testForCriticallyDamped) { createSimpleAnimatedViewWithOpacity(1000, 0d); Callback animationCallback = mock(Callback.class); - mNativeAnimatedNodesManager.startAnimatingNode( - 1, - 1, - config, - animationCallback); + mNativeAnimatedNodesManager.startAnimatingNode(1, 1, config, animationCallback); - ArgumentCaptor stylesCaptor = - ArgumentCaptor.forClass(ReadableMap.class); + ArgumentCaptor stylesCaptor = ArgumentCaptor.forClass(ReadableMap.class); reset(mUIManagerMock); mNativeAnimatedNodesManager.runUpdates(nextFrameTime()); @@ -285,7 +273,7 @@ public class NativeAnimatedNodeTraversalTest { reset(mUIManagerMock); mNativeAnimatedNodesManager.runUpdates(nextFrameTime()); verify(mUIManagerMock, atMost(1)) - .synchronouslyUpdateViewOnUIThread(eq(1000), stylesCaptor.capture()); + .synchronouslyUpdateViewOnUIThread(eq(1000), stylesCaptor.capture()); double currentValue = stylesCaptor.getValue().getDouble("opacity"); if (currentValue > 1d) { wasGreaterThanOne = true; @@ -296,7 +284,8 @@ public class NativeAnimatedNodeTraversalTest { } // verify that we've reach the final value at the end of animation assertThat(previousValue).isEqualTo(1d); - // verify that value has reached some maximum value that is greater than the final value (bounce) + // verify that value has reached some maximum value that is greater than the final value + // (bounce) if (testForCriticallyDamped) { assertThat(!wasGreaterThanOne); } else { @@ -310,55 +299,51 @@ public class NativeAnimatedNodeTraversalTest { @Test public void testUnderdampedSpringAnimation() { performSpringAnimationTestWithConfig( - JavaOnlyMap.of( - "type", - "spring", - "stiffness", - 230.2d, - "damping", - 22d, - "mass", - 1d, - "initialVelocity", - 0d, - "toValue", - 1d, - "restSpeedThreshold", - 0.001d, - "restDisplacementThreshold", - 0.001d, - "overshootClamping", - false - ), - false - ); + JavaOnlyMap.of( + "type", + "spring", + "stiffness", + 230.2d, + "damping", + 22d, + "mass", + 1d, + "initialVelocity", + 0d, + "toValue", + 1d, + "restSpeedThreshold", + 0.001d, + "restDisplacementThreshold", + 0.001d, + "overshootClamping", + false), + false); } @Test public void testCriticallyDampedSpringAnimation() { performSpringAnimationTestWithConfig( - JavaOnlyMap.of( - "type", - "spring", - "stiffness", - 1000d, - "damping", - 500d, - "mass", - 3.0d, - "initialVelocity", - 0d, - "toValue", - 1d, - "restSpeedThreshold", - 0.001d, - "restDisplacementThreshold", - 0.001d, - "overshootClamping", - false - ), - true - ); + JavaOnlyMap.of( + "type", + "spring", + "stiffness", + 1000d, + "damping", + 500d, + "mass", + 3.0d, + "initialVelocity", + 0d, + "toValue", + 1d, + "restSpeedThreshold", + 0.001d, + "restDisplacementThreshold", + 0.001d, + "overshootClamping", + false), + true); } @Test @@ -367,34 +352,32 @@ public class NativeAnimatedNodeTraversalTest { Callback animationCallback = mock(Callback.class); mNativeAnimatedNodesManager.startAnimatingNode( - 1, - 1, - JavaOnlyMap.of( - "type", - "spring", - "stiffness", - 230.2d, - "damping", - 22d, - "mass", - 1d, - "initialVelocity", - 0d, - "toValue", - 1d, - "restSpeedThreshold", - 0.001d, - "restDisplacementThreshold", - 0.001d, - "overshootClamping", - false, - "iterations", - 5 - ), - animationCallback); + 1, + 1, + JavaOnlyMap.of( + "type", + "spring", + "stiffness", + 230.2d, + "damping", + 22d, + "mass", + 1d, + "initialVelocity", + 0d, + "toValue", + 1d, + "restSpeedThreshold", + 0.001d, + "restDisplacementThreshold", + 0.001d, + "overshootClamping", + false, + "iterations", + 5), + animationCallback); - ArgumentCaptor stylesCaptor = - ArgumentCaptor.forClass(ReadableMap.class); + ArgumentCaptor stylesCaptor = ArgumentCaptor.forClass(ReadableMap.class); reset(mUIManagerMock); mNativeAnimatedNodesManager.runUpdates(nextFrameTime()); @@ -410,30 +393,30 @@ public class NativeAnimatedNodeTraversalTest { reset(mUIManagerMock); mNativeAnimatedNodesManager.runUpdates(nextFrameTime()); verify(mUIManagerMock, atMost(1)) - .synchronouslyUpdateViewOnUIThread(eq(1000), stylesCaptor.capture()); + .synchronouslyUpdateViewOnUIThread(eq(1000), stylesCaptor.capture()); double currentValue = stylesCaptor.getValue().getDouble("opacity"); if (currentValue > 1d) { wasGreaterThanOne = true; } // Test to see if it reset after coming to rest - if (didComeToRest && - currentValue == 0d && - Math.abs(Math.abs(currentValue - previousValue) - 1d) < 0.001d) { + if (didComeToRest + && currentValue == 0d + && Math.abs(Math.abs(currentValue - previousValue) - 1d) < 0.001d) { numberOfResets++; } // verify that an animation step is relatively small, unless it has come to rest and reset if (!didComeToRest) assertThat(Math.abs(currentValue - previousValue)).isLessThan(0.12d); - - // record that the animation did come to rest when it rests on toValue - didComeToRest = Math.abs(currentValue - 1d) < 0.001d && - Math.abs(currentValue - previousValue) < 0.001d; + // record that the animation did come to rest when it rests on toValue + didComeToRest = + Math.abs(currentValue - 1d) < 0.001d && Math.abs(currentValue - previousValue) < 0.001d; previousValue = currentValue; } // verify that we've reach the final value at the end of animation assertThat(previousValue).isEqualTo(1d); - // verify that value has reached some maximum value that is greater than the final value (bounce) + // verify that value has reached some maximum value that is greater than the final value + // (bounce) assertThat(wasGreaterThanOne); // verify that value reset 4 times after finishing a full animation assertThat(numberOfResets).isEqualTo(4); @@ -448,24 +431,17 @@ public class NativeAnimatedNodeTraversalTest { Callback animationCallback = mock(Callback.class); mNativeAnimatedNodesManager.startAnimatingNode( - 1, - 1, - JavaOnlyMap.of( - "type", - "decay", - "velocity", - 0.5d, - "deceleration", - 0.998d), - animationCallback); + 1, + 1, + JavaOnlyMap.of("type", "decay", "velocity", 0.5d, "deceleration", 0.998d), + animationCallback); - ArgumentCaptor stylesCaptor = - ArgumentCaptor.forClass(ReadableMap.class); + ArgumentCaptor stylesCaptor = ArgumentCaptor.forClass(ReadableMap.class); reset(mUIManagerMock); mNativeAnimatedNodesManager.runUpdates(nextFrameTime()); verify(mUIManagerMock, atMost(1)) - .synchronouslyUpdateViewOnUIThread(eq(1000), stylesCaptor.capture()); + .synchronouslyUpdateViewOnUIThread(eq(1000), stylesCaptor.capture()); double previousValue = stylesCaptor.getValue().getDouble("opacity"); double previousDiff = Double.POSITIVE_INFINITY; /* run 3 secs of animation */ @@ -473,7 +449,7 @@ public class NativeAnimatedNodeTraversalTest { reset(mUIManagerMock); mNativeAnimatedNodesManager.runUpdates(nextFrameTime()); verify(mUIManagerMock, atMost(1)) - .synchronouslyUpdateViewOnUIThread(eq(1000), stylesCaptor.capture()); + .synchronouslyUpdateViewOnUIThread(eq(1000), stylesCaptor.capture()); double currentValue = stylesCaptor.getValue().getDouble("opacity"); double currentDiff = currentValue - previousValue; // verify monotonicity @@ -505,26 +481,17 @@ public class NativeAnimatedNodeTraversalTest { Callback animationCallback = mock(Callback.class); mNativeAnimatedNodesManager.startAnimatingNode( - 1, - 1, - JavaOnlyMap.of( - "type", - "decay", - "velocity", - 0.5d, - "deceleration", - 0.998d, - "iterations", - 5), - animationCallback); + 1, + 1, + JavaOnlyMap.of("type", "decay", "velocity", 0.5d, "deceleration", 0.998d, "iterations", 5), + animationCallback); - ArgumentCaptor stylesCaptor = - ArgumentCaptor.forClass(ReadableMap.class); + ArgumentCaptor stylesCaptor = ArgumentCaptor.forClass(ReadableMap.class); reset(mUIManagerMock); mNativeAnimatedNodesManager.runUpdates(nextFrameTime()); verify(mUIManagerMock, atMost(1)) - .synchronouslyUpdateViewOnUIThread(eq(1000), stylesCaptor.capture()); + .synchronouslyUpdateViewOnUIThread(eq(1000), stylesCaptor.capture()); double previousValue = stylesCaptor.getValue().getDouble("opacity"); double previousDiff = Double.POSITIVE_INFINITY; double initialValue = stylesCaptor.getValue().getDouble("opacity"); @@ -535,7 +502,7 @@ public class NativeAnimatedNodeTraversalTest { reset(mUIManagerMock); mNativeAnimatedNodesManager.runUpdates(nextFrameTime()); verify(mUIManagerMock, atMost(1)) - .synchronouslyUpdateViewOnUIThread(eq(1000), stylesCaptor.capture()); + .synchronouslyUpdateViewOnUIThread(eq(1000), stylesCaptor.capture()); double currentValue = stylesCaptor.getValue().getDouble("opacity"); double currentDiff = currentValue - previousValue; // Test to see if it reset after coming to rest (i.e. dropped back to ) @@ -545,7 +512,8 @@ public class NativeAnimatedNodeTraversalTest { // verify monotonicity, unless it has come to rest and reset // greater *or equal* because the animation stops during these 3 seconds - if (!didComeToRest) assertThat(currentValue).as("on frame " + i).isGreaterThanOrEqualTo(previousValue); + if (!didComeToRest) + assertThat(currentValue).as("on frame " + i).isGreaterThanOrEqualTo(previousValue); // Test if animation has come to rest using the 0.1 threshold from DecayAnimation.java didComeToRest = Math.abs(currentDiff) < 0.1d; @@ -567,10 +535,7 @@ public class NativeAnimatedNodeTraversalTest { JavaOnlyArray frames = JavaOnlyArray.of(0d, 1d); Callback animationCallback = mock(Callback.class); mNativeAnimatedNodesManager.startAnimatingNode( - 1, - 1, - JavaOnlyMap.of("type", "frames", "frames", frames, "toValue", 1d), - animationCallback); + 1, 1, JavaOnlyMap.of("type", "frames", "frames", frames, "toValue", 1d), animationCallback); ArgumentCaptor callbackResponseCaptor = ArgumentCaptor.forClass(ReadableMap.class); @@ -591,34 +556,25 @@ public class NativeAnimatedNodeTraversalTest { } /** - * Creates a following graph of nodes: - * Value(1, firstValue) ----> Add(3) ---> Style(4) ---> Props(5) ---> View(viewTag) - * | - * Value(2, secondValue) --+ + * Creates a following graph of nodes: Value(1, firstValue) ----> Add(3) ---> Style(4) ---> + * Props(5) ---> View(viewTag) | Value(2, secondValue) --+ * - * Add(3) node maps to a "translateX" attribute of the Style(4) node. + *

Add(3) node maps to a "translateX" attribute of the Style(4) node. */ private void createAnimatedGraphWithAdditionNode( - int viewTag, - double firstValue, - double secondValue) { + int viewTag, double firstValue, double secondValue) { mNativeAnimatedNodesManager.createAnimatedNode( - 1, - JavaOnlyMap.of("type", "value", "value", firstValue, "offset", 0d)); + 1, JavaOnlyMap.of("type", "value", "value", firstValue, "offset", 0d)); mNativeAnimatedNodesManager.createAnimatedNode( - 2, - JavaOnlyMap.of("type", "value", "value", secondValue, "offset", 0d)); + 2, JavaOnlyMap.of("type", "value", "value", secondValue, "offset", 0d)); mNativeAnimatedNodesManager.createAnimatedNode( - 3, - JavaOnlyMap.of("type", "addition", "input", JavaOnlyArray.of(1, 2))); + 3, JavaOnlyMap.of("type", "addition", "input", JavaOnlyArray.of(1, 2))); mNativeAnimatedNodesManager.createAnimatedNode( - 4, - JavaOnlyMap.of("type", "style", "style", JavaOnlyMap.of("translateX", 3))); + 4, JavaOnlyMap.of("type", "style", "style", JavaOnlyMap.of("translateX", 3))); mNativeAnimatedNodesManager.createAnimatedNode( - 5, - JavaOnlyMap.of("type", "props", "props", JavaOnlyMap.of("style", 4))); + 5, JavaOnlyMap.of("type", "props", "props", JavaOnlyMap.of("style", 4))); mNativeAnimatedNodesManager.connectAnimatedNodes(1, 3); mNativeAnimatedNodesManager.connectAnimatedNodes(2, 3); mNativeAnimatedNodesManager.connectAnimatedNodes(3, 4); @@ -633,19 +589,18 @@ public class NativeAnimatedNodeTraversalTest { Callback animationCallback = mock(Callback.class); JavaOnlyArray frames = JavaOnlyArray.of(0d, 1d); mNativeAnimatedNodesManager.startAnimatingNode( - 1, - 1, - JavaOnlyMap.of("type", "frames", "frames", frames, "toValue", 101d), - animationCallback); + 1, + 1, + JavaOnlyMap.of("type", "frames", "frames", frames, "toValue", 101d), + animationCallback); mNativeAnimatedNodesManager.startAnimatingNode( - 2, - 2, - JavaOnlyMap.of("type", "frames", "frames", frames, "toValue", 1010d), - animationCallback); + 2, + 2, + JavaOnlyMap.of("type", "frames", "frames", frames, "toValue", 1010d), + animationCallback); - ArgumentCaptor stylesCaptor = - ArgumentCaptor.forClass(ReadableMap.class); + ArgumentCaptor stylesCaptor = ArgumentCaptor.forClass(ReadableMap.class); reset(mUIManagerMock); mNativeAnimatedNodesManager.runUpdates(nextFrameTime()); @@ -654,8 +609,7 @@ public class NativeAnimatedNodeTraversalTest { reset(mUIManagerMock); mNativeAnimatedNodesManager.runUpdates(nextFrameTime()); - verify(mUIManagerMock) - .synchronouslyUpdateViewOnUIThread(eq(50), stylesCaptor.capture()); + verify(mUIManagerMock).synchronouslyUpdateViewOnUIThread(eq(50), stylesCaptor.capture()); assertThat(stylesCaptor.getValue().getDouble("translateX")).isEqualTo(1111d); reset(mUIManagerMock); @@ -667,8 +621,8 @@ public class NativeAnimatedNodeTraversalTest { * Verifies that {@link NativeAnimatedNodesManager#runUpdates} updates the view correctly in case * when one of the addition input nodes has started animating while the other one has not. * - * We expect that the output of the addition node will take the starting value of the second input - * node even though the node hasn't been connected to an active animation driver. + *

We expect that the output of the addition node will take the starting value of the second + * input node even though the node hasn't been connected to an active animation driver. */ @Test public void testViewReceiveUpdatesIfOneOfAnimationHasntStarted() { @@ -678,13 +632,12 @@ public class NativeAnimatedNodeTraversalTest { Callback animationCallback = mock(Callback.class); JavaOnlyArray frames = JavaOnlyArray.of(0d, 1d); mNativeAnimatedNodesManager.startAnimatingNode( - 1, - 1, - JavaOnlyMap.of("type", "frames", "frames", frames, "toValue", 101d), - animationCallback); + 1, + 1, + JavaOnlyMap.of("type", "frames", "frames", frames, "toValue", 101d), + animationCallback); - ArgumentCaptor stylesCaptor = - ArgumentCaptor.forClass(ReadableMap.class); + ArgumentCaptor stylesCaptor = ArgumentCaptor.forClass(ReadableMap.class); reset(mUIManagerMock); mNativeAnimatedNodesManager.runUpdates(nextFrameTime()); @@ -693,8 +646,7 @@ public class NativeAnimatedNodeTraversalTest { reset(mUIManagerMock); mNativeAnimatedNodesManager.runUpdates(nextFrameTime()); - verify(mUIManagerMock) - .synchronouslyUpdateViewOnUIThread(eq(50), stylesCaptor.capture()); + verify(mUIManagerMock).synchronouslyUpdateViewOnUIThread(eq(50), stylesCaptor.capture()); assertThat(stylesCaptor.getValue().getDouble("translateX")).isEqualTo(1101d); reset(mUIManagerMock); @@ -706,7 +658,7 @@ public class NativeAnimatedNodeTraversalTest { * Verifies that {@link NativeAnimatedNodesManager#runUpdates} updates the view correctly in case * when one of the addition input nodes animation finishes before the other. * - * We expect that the output of the addition node after one of the animation has finished will + *

We expect that the output of the addition node after one of the animation has finished will * take the last value of the animated node and the view will receive updates up until the second * animation is over. */ @@ -719,21 +671,20 @@ public class NativeAnimatedNodeTraversalTest { // Start animating for the first addition input node, will have 2 frames only JavaOnlyArray firstFrames = JavaOnlyArray.of(0d, 1d); mNativeAnimatedNodesManager.startAnimatingNode( - 1, - 1, - JavaOnlyMap.of("type", "frames", "frames", firstFrames, "toValue", 200d), - animationCallback); + 1, + 1, + JavaOnlyMap.of("type", "frames", "frames", firstFrames, "toValue", 200d), + animationCallback); // Start animating for the first addition input node, will have 6 frames JavaOnlyArray secondFrames = JavaOnlyArray.of(0d, 0.2d, 0.4d, 0.6d, 0.8d, 1d); mNativeAnimatedNodesManager.startAnimatingNode( - 2, - 2, - JavaOnlyMap.of("type", "frames", "frames", secondFrames, "toValue", 1010d), - animationCallback); + 2, + 2, + JavaOnlyMap.of("type", "frames", "frames", secondFrames, "toValue", 1010d), + animationCallback); - ArgumentCaptor stylesCaptor = - ArgumentCaptor.forClass(ReadableMap.class); + ArgumentCaptor stylesCaptor = ArgumentCaptor.forClass(ReadableMap.class); reset(mUIManagerMock); mNativeAnimatedNodesManager.runUpdates(nextFrameTime()); @@ -743,10 +694,9 @@ public class NativeAnimatedNodeTraversalTest { for (int i = 1; i < secondFrames.size(); i++) { reset(mUIManagerMock); mNativeAnimatedNodesManager.runUpdates(nextFrameTime()); - verify(mUIManagerMock) - .synchronouslyUpdateViewOnUIThread(eq(50), stylesCaptor.capture()); + verify(mUIManagerMock).synchronouslyUpdateViewOnUIThread(eq(50), stylesCaptor.capture()); assertThat(stylesCaptor.getValue().getDouble("translateX")) - .isEqualTo(1200d + secondFrames.getDouble(i) * 10d); + .isEqualTo(1200d + secondFrames.getDouble(i) * 10d); } reset(mUIManagerMock); @@ -757,22 +707,17 @@ public class NativeAnimatedNodeTraversalTest { @Test public void testMultiplicationNode() { mNativeAnimatedNodesManager.createAnimatedNode( - 1, - JavaOnlyMap.of("type", "value", "value", 1d, "offset", 0d)); + 1, JavaOnlyMap.of("type", "value", "value", 1d, "offset", 0d)); mNativeAnimatedNodesManager.createAnimatedNode( - 2, - JavaOnlyMap.of("type", "value", "value", 5d, "offset", 0d)); + 2, JavaOnlyMap.of("type", "value", "value", 5d, "offset", 0d)); mNativeAnimatedNodesManager.createAnimatedNode( - 3, - JavaOnlyMap.of("type", "multiplication", "input", JavaOnlyArray.of(1, 2))); + 3, JavaOnlyMap.of("type", "multiplication", "input", JavaOnlyArray.of(1, 2))); mNativeAnimatedNodesManager.createAnimatedNode( - 4, - JavaOnlyMap.of("type", "style", "style", JavaOnlyMap.of("translateX", 3))); + 4, JavaOnlyMap.of("type", "style", "style", JavaOnlyMap.of("translateX", 3))); mNativeAnimatedNodesManager.createAnimatedNode( - 5, - JavaOnlyMap.of("type", "props", "props", JavaOnlyMap.of("style", 4))); + 5, JavaOnlyMap.of("type", "props", "props", JavaOnlyMap.of("style", 4))); mNativeAnimatedNodesManager.connectAnimatedNodes(1, 3); mNativeAnimatedNodesManager.connectAnimatedNodes(2, 3); mNativeAnimatedNodesManager.connectAnimatedNodes(3, 4); @@ -782,19 +727,15 @@ public class NativeAnimatedNodeTraversalTest { Callback animationCallback = mock(Callback.class); JavaOnlyArray frames = JavaOnlyArray.of(0d, 1d); mNativeAnimatedNodesManager.startAnimatingNode( - 1, - 1, - JavaOnlyMap.of("type", "frames", "frames", frames, "toValue", 2d), - animationCallback); + 1, 1, JavaOnlyMap.of("type", "frames", "frames", frames, "toValue", 2d), animationCallback); mNativeAnimatedNodesManager.startAnimatingNode( - 2, - 2, - JavaOnlyMap.of("type", "frames", "frames", frames, "toValue", 10d), - animationCallback); + 2, + 2, + JavaOnlyMap.of("type", "frames", "frames", frames, "toValue", 10d), + animationCallback); - ArgumentCaptor stylesCaptor = - ArgumentCaptor.forClass(ReadableMap.class); + ArgumentCaptor stylesCaptor = ArgumentCaptor.forClass(ReadableMap.class); reset(mUIManagerMock); mNativeAnimatedNodesManager.runUpdates(nextFrameTime()); @@ -823,10 +764,10 @@ public class NativeAnimatedNodeTraversalTest { JavaOnlyArray frames = JavaOnlyArray.of(0d, 0.2d, 0.4d, 0.6d, 0.8d, 1.0d); Callback animationCallback = mock(Callback.class); mNativeAnimatedNodesManager.startAnimatingNode( - 404, - 1, - JavaOnlyMap.of("type", "frames", "frames", frames, "toValue", 1d), - animationCallback); + 404, + 1, + JavaOnlyMap.of("type", "frames", "frames", frames, "toValue", 1d), + animationCallback); ArgumentCaptor callbackResponseCaptor = ArgumentCaptor.forClass(ReadableMap.class); @@ -835,7 +776,7 @@ public class NativeAnimatedNodeTraversalTest { mNativeAnimatedNodesManager.runUpdates(nextFrameTime()); mNativeAnimatedNodesManager.runUpdates(nextFrameTime()); verify(mUIManagerMock, times(2)) - .synchronouslyUpdateViewOnUIThread(anyInt(), any(ReadableMap.class)); + .synchronouslyUpdateViewOnUIThread(anyInt(), any(ReadableMap.class)); verifyNoMoreInteractions(animationCallback); reset(animationCallback); @@ -863,29 +804,26 @@ public class NativeAnimatedNodeTraversalTest { @Test public void testInterpolationNode() { mNativeAnimatedNodesManager.createAnimatedNode( - 1, - JavaOnlyMap.of("type", "value", "value", 10d, "offset", 0d)); + 1, JavaOnlyMap.of("type", "value", "value", 10d, "offset", 0d)); mNativeAnimatedNodesManager.createAnimatedNode( - 2, - JavaOnlyMap.of( - "type", - "interpolation", - "inputRange", - JavaOnlyArray.of(10d, 20d), - "outputRange", - JavaOnlyArray.of(0d, 1d), - "extrapolateLeft", - "extend", - "extrapolateRight", - "extend")); + 2, + JavaOnlyMap.of( + "type", + "interpolation", + "inputRange", + JavaOnlyArray.of(10d, 20d), + "outputRange", + JavaOnlyArray.of(0d, 1d), + "extrapolateLeft", + "extend", + "extrapolateRight", + "extend")); mNativeAnimatedNodesManager.createAnimatedNode( - 3, - JavaOnlyMap.of("type", "style", "style", JavaOnlyMap.of("opacity", 2))); + 3, JavaOnlyMap.of("type", "style", "style", JavaOnlyMap.of("opacity", 2))); mNativeAnimatedNodesManager.createAnimatedNode( - 4, - JavaOnlyMap.of("type", "props", "props", JavaOnlyMap.of("style", 3))); + 4, JavaOnlyMap.of("type", "props", "props", JavaOnlyMap.of("style", 3))); mNativeAnimatedNodesManager.connectAnimatedNodes(1, 2); mNativeAnimatedNodesManager.connectAnimatedNodes(2, 3); mNativeAnimatedNodesManager.connectAnimatedNodes(3, 4); @@ -894,21 +832,18 @@ public class NativeAnimatedNodeTraversalTest { Callback animationCallback = mock(Callback.class); JavaOnlyArray frames = JavaOnlyArray.of(0d, 0.2d, 0.4d, 0.6d, 0.8d, 1d); mNativeAnimatedNodesManager.startAnimatingNode( - 1, - 1, - JavaOnlyMap.of("type", "frames", "frames", frames, "toValue", 20d), - animationCallback); + 1, + 1, + JavaOnlyMap.of("type", "frames", "frames", frames, "toValue", 20d), + animationCallback); - ArgumentCaptor stylesCaptor = - ArgumentCaptor.forClass(ReadableMap.class); + ArgumentCaptor stylesCaptor = ArgumentCaptor.forClass(ReadableMap.class); for (int i = 0; i < frames.size(); i++) { reset(mUIManagerMock); mNativeAnimatedNodesManager.runUpdates(nextFrameTime()); - verify(mUIManagerMock) - .synchronouslyUpdateViewOnUIThread(eq(50), stylesCaptor.capture()); - assertThat(stylesCaptor.getValue().getDouble("opacity")) - .isEqualTo(frames.getDouble(i)); + verify(mUIManagerMock).synchronouslyUpdateViewOnUIThread(eq(50), stylesCaptor.capture()); + assertThat(stylesCaptor.getValue().getDouble("opacity")).isEqualTo(frames.getDouble(i)); } reset(mUIManagerMock); @@ -925,8 +860,8 @@ public class NativeAnimatedNodeTraversalTest { @Override public void dispatch(RCTEventEmitter rctEventEmitter) { - rctEventEmitter.receiveEvent(tag, "topScroll", JavaOnlyMap.of( - "contentOffset", JavaOnlyMap.of("y", value))); + rctEventEmitter.receiveEvent( + tag, "topScroll", JavaOnlyMap.of("contentOffset", JavaOnlyMap.of("y", value))); } }; } @@ -937,14 +872,15 @@ public class NativeAnimatedNodeTraversalTest { createSimpleAnimatedViewWithOpacity(viewTag, 0d); - mNativeAnimatedNodesManager.addAnimatedEventToView(viewTag, "topScroll", JavaOnlyMap.of( - "animatedValueTag", 1, - "nativeEventPath", JavaOnlyArray.of("contentOffset", "y"))); + mNativeAnimatedNodesManager.addAnimatedEventToView( + viewTag, + "topScroll", + JavaOnlyMap.of( + "animatedValueTag", 1, "nativeEventPath", JavaOnlyArray.of("contentOffset", "y"))); mNativeAnimatedNodesManager.onEventDispatch(createScrollEvent(viewTag, 10)); - ArgumentCaptor stylesCaptor = - ArgumentCaptor.forClass(ReadableMap.class); + ArgumentCaptor stylesCaptor = ArgumentCaptor.forClass(ReadableMap.class); reset(mUIManagerMock); mNativeAnimatedNodesManager.runUpdates(nextFrameTime()); @@ -958,18 +894,21 @@ public class NativeAnimatedNodeTraversalTest { createSimpleAnimatedViewWithOpacity(viewTag, 0d); - mNativeAnimatedNodesManager.addAnimatedEventToView(viewTag, "otherEvent", JavaOnlyMap.of( - "animatedValueTag", 1, - "nativeEventPath", JavaOnlyArray.of("contentOffset", "y"))); + mNativeAnimatedNodesManager.addAnimatedEventToView( + viewTag, + "otherEvent", + JavaOnlyMap.of( + "animatedValueTag", 1, "nativeEventPath", JavaOnlyArray.of("contentOffset", "y"))); - mNativeAnimatedNodesManager.addAnimatedEventToView(999, "topScroll", JavaOnlyMap.of( - "animatedValueTag", 1, - "nativeEventPath", JavaOnlyArray.of("contentOffset", "y"))); + mNativeAnimatedNodesManager.addAnimatedEventToView( + 999, + "topScroll", + JavaOnlyMap.of( + "animatedValueTag", 1, "nativeEventPath", JavaOnlyArray.of("contentOffset", "y"))); mNativeAnimatedNodesManager.onEventDispatch(createScrollEvent(viewTag, 10)); - ArgumentCaptor stylesCaptor = - ArgumentCaptor.forClass(ReadableMap.class); + ArgumentCaptor stylesCaptor = ArgumentCaptor.forClass(ReadableMap.class); reset(mUIManagerMock); mNativeAnimatedNodesManager.runUpdates(nextFrameTime()); @@ -981,26 +920,29 @@ public class NativeAnimatedNodeTraversalTest { public void testNativeAnimatedEventCustomMapping() { int viewTag = 1000; - PowerMockito.when(mUIManagerMock.getConstants()).thenAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - return MapBuilder.of("customDirectEventTypes", MapBuilder.of( - "topScroll", MapBuilder.of("registrationName", "onScroll") - )); - } - }); + PowerMockito.when(mUIManagerMock.getConstants()) + .thenAnswer( + new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + return MapBuilder.of( + "customDirectEventTypes", + MapBuilder.of("topScroll", MapBuilder.of("registrationName", "onScroll"))); + } + }); mNativeAnimatedNodesManager = new NativeAnimatedNodesManager(mUIManagerMock); createSimpleAnimatedViewWithOpacity(viewTag, 0d); - mNativeAnimatedNodesManager.addAnimatedEventToView(viewTag, "onScroll", JavaOnlyMap.of( - "animatedValueTag", 1, - "nativeEventPath", JavaOnlyArray.of("contentOffset", "y"))); + mNativeAnimatedNodesManager.addAnimatedEventToView( + viewTag, + "onScroll", + JavaOnlyMap.of( + "animatedValueTag", 1, "nativeEventPath", JavaOnlyArray.of("contentOffset", "y"))); mNativeAnimatedNodesManager.onEventDispatch(createScrollEvent(viewTag, 10)); - ArgumentCaptor stylesCaptor = - ArgumentCaptor.forClass(ReadableMap.class); + ArgumentCaptor stylesCaptor = ArgumentCaptor.forClass(ReadableMap.class); reset(mUIManagerMock); mNativeAnimatedNodesManager.runUpdates(nextFrameTime()); @@ -1013,14 +955,11 @@ public class NativeAnimatedNodeTraversalTest { int viewTag = 1000; int propsNodeTag = 3; mNativeAnimatedNodesManager.createAnimatedNode( - 1, - JavaOnlyMap.of("type", "value", "value", 1d, "offset", 0d)); + 1, JavaOnlyMap.of("type", "value", "value", 1d, "offset", 0d)); mNativeAnimatedNodesManager.createAnimatedNode( - 2, - JavaOnlyMap.of("type", "style", "style", JavaOnlyMap.of("opacity", 1))); + 2, JavaOnlyMap.of("type", "style", "style", JavaOnlyMap.of("opacity", 1))); mNativeAnimatedNodesManager.createAnimatedNode( - propsNodeTag, - JavaOnlyMap.of("type", "props", "props", JavaOnlyMap.of("style", 2))); + propsNodeTag, JavaOnlyMap.of("type", "props", "props", JavaOnlyMap.of("style", 2))); mNativeAnimatedNodesManager.connectAnimatedNodes(1, 2); mNativeAnimatedNodesManager.connectAnimatedNodes(2, propsNodeTag); mNativeAnimatedNodesManager.connectAnimatedNodeToView(propsNodeTag, viewTag); @@ -1028,13 +967,9 @@ public class NativeAnimatedNodeTraversalTest { JavaOnlyArray frames = JavaOnlyArray.of(0d, 0.5d, 1d); Callback animationCallback = mock(Callback.class); mNativeAnimatedNodesManager.startAnimatingNode( - 1, - 1, - JavaOnlyMap.of("type", "frames", "frames", frames, "toValue", 0d), - animationCallback); + 1, 1, JavaOnlyMap.of("type", "frames", "frames", frames, "toValue", 0d), animationCallback); - ArgumentCaptor stylesCaptor = - ArgumentCaptor.forClass(ReadableMap.class); + ArgumentCaptor stylesCaptor = ArgumentCaptor.forClass(ReadableMap.class); for (int i = 0; i < frames.size(); i++) { reset(mUIManagerMock); @@ -1050,34 +985,37 @@ public class NativeAnimatedNodeTraversalTest { assertThat(stylesCaptor.getValue().isNull("opacity")); } - /** - * Creates a following graph of nodes: - * Value(3, initialValue) ----> Style(4) ---> Props(5) ---> View(viewTag) + * Creates a following graph of nodes: Value(3, initialValue) ----> Style(4) ---> Props(5) ---> + * View(viewTag) * - * Value(3) is set to track Value(1) via Tracking(2) node with the provided animation config + *

Value(3) is set to track Value(1) via Tracking(2) node with the provided animation config */ private void createAnimatedGraphWithTrackingNode( - int viewTag, - double initialValue, - JavaOnlyMap animationConfig) { + int viewTag, double initialValue, JavaOnlyMap animationConfig) { mNativeAnimatedNodesManager.createAnimatedNode( - 1, - JavaOnlyMap.of("type", "value", "value", initialValue, "offset", 0d)); + 1, JavaOnlyMap.of("type", "value", "value", initialValue, "offset", 0d)); mNativeAnimatedNodesManager.createAnimatedNode( + 3, JavaOnlyMap.of("type", "value", "value", initialValue, "offset", 0d)); + + mNativeAnimatedNodesManager.createAnimatedNode( + 2, + JavaOnlyMap.of( + "type", + "tracking", + "animationId", + 70, + "value", 3, - JavaOnlyMap.of("type", "value", "value", initialValue, "offset", 0d)); + "toValue", + 1, + "animationConfig", + animationConfig)); mNativeAnimatedNodesManager.createAnimatedNode( - 2, - JavaOnlyMap.of("type", "tracking", "animationId", 70, "value", 3, "toValue", 1, "animationConfig", animationConfig)); - + 4, JavaOnlyMap.of("type", "style", "style", JavaOnlyMap.of("translateX", 3))); mNativeAnimatedNodesManager.createAnimatedNode( - 4, - JavaOnlyMap.of("type", "style", "style", JavaOnlyMap.of("translateX", 3))); - mNativeAnimatedNodesManager.createAnimatedNode( - 5, - JavaOnlyMap.of("type", "props", "props", JavaOnlyMap.of("style", 4))); + 5, JavaOnlyMap.of("type", "props", "props", JavaOnlyMap.of("style", 4))); mNativeAnimatedNodesManager.connectAnimatedNodes(1, 2); mNativeAnimatedNodesManager.connectAnimatedNodes(3, 4); mNativeAnimatedNodesManager.connectAnimatedNodes(4, 5); @@ -1096,8 +1034,7 @@ public class NativeAnimatedNodeTraversalTest { createAnimatedGraphWithTrackingNode(1000, 0d, animationConfig); - ArgumentCaptor stylesCaptor = - ArgumentCaptor.forClass(ReadableMap.class); + ArgumentCaptor stylesCaptor = ArgumentCaptor.forClass(ReadableMap.class); reset(mUIManagerMock); mNativeAnimatedNodesManager.runUpdates(nextFrameTime()); @@ -1111,10 +1048,9 @@ public class NativeAnimatedNodeTraversalTest { for (int i = 0; i < frames.size(); i++) { reset(mUIManagerMock); mNativeAnimatedNodesManager.runUpdates(nextFrameTime()); - verify(mUIManagerMock) - .synchronouslyUpdateViewOnUIThread(eq(1000), stylesCaptor.capture()); + verify(mUIManagerMock).synchronouslyUpdateViewOnUIThread(eq(1000), stylesCaptor.capture()); assertThat(stylesCaptor.getValue().getDouble("translateX")) - .isEqualTo(frames.getDouble(i) * 100d); + .isEqualTo(frames.getDouble(i) * 100d); } // update "toValue" to 0 but run only two frames from the animation, @@ -1125,15 +1061,14 @@ public class NativeAnimatedNodeTraversalTest { for (int i = 0; i < 2; i++) { reset(mUIManagerMock); mNativeAnimatedNodesManager.runUpdates(nextFrameTime()); - verify(mUIManagerMock) - .synchronouslyUpdateViewOnUIThread(eq(1000), stylesCaptor.capture()); + verify(mUIManagerMock).synchronouslyUpdateViewOnUIThread(eq(1000), stylesCaptor.capture()); assertThat(stylesCaptor.getValue().getDouble("translateX")) - .isEqualTo(100d * (1d - frames.getDouble(i))); + .isEqualTo(100d * (1d - frames.getDouble(i))); } // at this point we expect tracking value to be at 75 assertThat(((ValueAnimatedNode) mNativeAnimatedNodesManager.getNodeById(3)).getValue()) - .isEqualTo(75d); + .isEqualTo(75d); // we update "toValue" again to 100 and expect the animation to restart from the current place mNativeAnimatedNodesManager.setAnimatedNodeValue(1, 100d); @@ -1142,10 +1077,9 @@ public class NativeAnimatedNodeTraversalTest { for (int i = 0; i < frames.size(); i++) { reset(mUIManagerMock); mNativeAnimatedNodesManager.runUpdates(nextFrameTime()); - verify(mUIManagerMock) - .synchronouslyUpdateViewOnUIThread(eq(1000), stylesCaptor.capture()); + verify(mUIManagerMock).synchronouslyUpdateViewOnUIThread(eq(1000), stylesCaptor.capture()); assertThat(stylesCaptor.getValue().getDouble("translateX")) - .isEqualTo(50d + 50d * frames.getDouble(i)); + .isEqualTo(50d + 50d * frames.getDouble(i)); } } @@ -1171,7 +1105,7 @@ public class NativeAnimatedNodeTraversalTest { mNativeAnimatedNodesManager.runUpdates(nextFrameTime()); } verify(mUIManagerMock, times(frames.size())) - .synchronouslyUpdateViewOnUIThread(eq(1000), any(ReadableMap.class)); + .synchronouslyUpdateViewOnUIThread(eq(1000), any(ReadableMap.class)); // the animation has completed, we expect no updates to be done reset(mUIManagerMock); @@ -1179,7 +1113,6 @@ public class NativeAnimatedNodeTraversalTest { mNativeAnimatedNodesManager.runUpdates(nextFrameTime()); verifyNoMoreInteractions(mUIManagerMock); - // we update end value and expect the animation to restart mNativeAnimatedNodesManager.setAnimatedNodeValue(1, 200d); mNativeAnimatedNodesManager.runUpdates(nextFrameTime()); // make sure animation starts @@ -1190,7 +1123,7 @@ public class NativeAnimatedNodeTraversalTest { mNativeAnimatedNodesManager.runUpdates(nextFrameTime()); } verify(mUIManagerMock, times(frames.size())) - .synchronouslyUpdateViewOnUIThread(eq(1000), any(ReadableMap.class)); + .synchronouslyUpdateViewOnUIThread(eq(1000), any(ReadableMap.class)); // the animation has completed, we expect no updates to be done reset(mUIManagerMock); @@ -1208,7 +1141,8 @@ public class NativeAnimatedNodeTraversalTest { public void testSpringTrackingRetainsSpeed() { // this spring config correspomds to tension 20 and friction 0.5 which makes the spring settle // very slowly - JavaOnlyMap springConfig = JavaOnlyMap.of( + JavaOnlyMap springConfig = + JavaOnlyMap.of( "type", "spring", "restSpeedThreshold", @@ -1235,10 +1169,12 @@ public class NativeAnimatedNodeTraversalTest { // we run several steps of animation until the value starts bouncing, has negative speed and // passes the final point (that is 1) while going backwards boolean isBoucingBack = false; - double previousValue = ((ValueAnimatedNode) mNativeAnimatedNodesManager.getNodeById(3)).getValue(); + double previousValue = + ((ValueAnimatedNode) mNativeAnimatedNodesManager.getNodeById(3)).getValue(); for (int maxFrames = 500; maxFrames > 0; maxFrames--) { mNativeAnimatedNodesManager.runUpdates(nextFrameTime()); - double currentValue = ((ValueAnimatedNode) mNativeAnimatedNodesManager.getNodeById(3)).getValue(); + double currentValue = + ((ValueAnimatedNode) mNativeAnimatedNodesManager.getNodeById(3)).getValue(); if (previousValue >= 1d && currentValue < 1d) { isBoucingBack = true; break; @@ -1257,7 +1193,8 @@ public class NativeAnimatedNodeTraversalTest { // we run 8 seconds of animation for (int i = 0; i < 8 * 60; i++) { mNativeAnimatedNodesManager.runUpdates(nextFrameTime()); - double currentValue = ((ValueAnimatedNode) mNativeAnimatedNodesManager.getNodeById(3)).getValue(); + double currentValue = + ((ValueAnimatedNode) mNativeAnimatedNodesManager.getNodeById(3)).getValue(); if (!hasTurnedForward) { if (currentValue <= previousValue) { bounceBackInitialFrames++; diff --git a/ReactAndroid/src/test/java/com/facebook/react/bridge/BaseJavaModuleTest.java b/ReactAndroid/src/test/java/com/facebook/react/bridge/BaseJavaModuleTest.java index a5b61034179..83a1cb3bc24 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/bridge/BaseJavaModuleTest.java +++ b/ReactAndroid/src/test/java/com/facebook/react/bridge/BaseJavaModuleTest.java @@ -1,19 +1,17 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; -import javax.inject.Provider; +import com.facebook.soloader.SoLoader; import java.util.List; - import org.junit.Before; import org.junit.Rule; -import org.junit.runner.RunWith; import org.junit.Test; +import org.junit.runner.RunWith; import org.mockito.Mockito; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; @@ -21,18 +19,13 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.rule.PowerMockRule; import org.robolectric.RobolectricTestRunner; -import com.facebook.soloader.SoLoader; - -/** - * Tests for {@link BaseJavaModule} and {@link JavaModuleWrapper} - */ +/** Tests for {@link BaseJavaModule} and {@link JavaModuleWrapper} */ @PrepareForTest({ReadableNativeArray.class, SoLoader.class}) @PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "androidx.*", "android.*"}) @RunWith(RobolectricTestRunner.class) public class BaseJavaModuleTest { - @Rule - public PowerMockRule rule = new PowerMockRule(); + @Rule public PowerMockRule rule = new PowerMockRule(); private List mMethods; private JavaModuleWrapper mWrapper; @@ -49,7 +42,7 @@ public class BaseJavaModuleTest { private int findMethod(String mname, List methods) { int posn = -1; - for (int i = 0; i< methods.size(); i++) { + for (int i = 0; i < methods.size(); i++) { JavaModuleWrapper.MethodDescriptor md = methods.get(i); if (md.name == mname) { posn = i; @@ -61,7 +54,7 @@ public class BaseJavaModuleTest { @Test(expected = NativeArgumentsParseException.class) public void testCallMethodWithoutEnoughArgs() throws Exception { - int methodId = findMethod("regularMethod",mMethods); + int methodId = findMethod("regularMethod", mMethods); Mockito.stub(mArguments.size()).toReturn(1); mWrapper.invoke(methodId, mArguments); } diff --git a/ReactAndroid/src/test/java/com/facebook/react/bridge/FallbackJSBundleLoaderTest.java b/ReactAndroid/src/test/java/com/facebook/react/bridge/FallbackJSBundleLoaderTest.java index 1fa1e4aa455..32df7bf6f8a 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/bridge/FallbackJSBundleLoaderTest.java +++ b/ReactAndroid/src/test/java/com/facebook/react/bridge/FallbackJSBundleLoaderTest.java @@ -1,34 +1,30 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; -import java.util.ArrayList; -import java.util.Arrays; - -import org.junit.Before; -import org.junit.Test; - -import com.facebook.common.logging.FLog; -import com.facebook.common.logging.FakeLoggingDelegate; -import com.facebook.common.logging.LoggingDelegate; - import static org.fest.assertions.api.Assertions.assertThat; import static org.fest.assertions.api.Assertions.fail; - import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import com.facebook.common.logging.FLog; +import com.facebook.common.logging.FakeLoggingDelegate; +import java.util.ArrayList; +import java.util.Arrays; +import org.junit.Before; +import org.junit.Test; + public class FallbackJSBundleLoaderTest { private static final String UNRECOVERABLE; + static { String prefix = FallbackJSBundleLoader.RECOVERABLE; char first = prefix.charAt(0); @@ -46,36 +42,31 @@ public class FallbackJSBundleLoaderTest { @Test public void firstLoaderSucceeds() { - JSBundleLoader delegates[] = new JSBundleLoader[] { - successfulLoader("url1"), - successfulLoader("url2") - }; + JSBundleLoader delegates[] = + new JSBundleLoader[] {successfulLoader("url1"), successfulLoader("url2")}; FallbackJSBundleLoader fallbackLoader = - new FallbackJSBundleLoader(new ArrayList<>(Arrays.asList(delegates))); + new FallbackJSBundleLoader(new ArrayList<>(Arrays.asList(delegates))); assertThat(fallbackLoader.loadScript(null)).isEqualTo("url1"); verify(delegates[0], times(1)).loadScript(null); verify(delegates[1], never()).loadScript(null); - assertThat(mLoggingDelegate.logContains( - FakeLoggingDelegate.WTF, - FallbackJSBundleLoader.TAG, - null)) - .isFalse(); + assertThat( + mLoggingDelegate.logContains(FakeLoggingDelegate.WTF, FallbackJSBundleLoader.TAG, null)) + .isFalse(); } @Test public void fallingBackSuccessfully() { - JSBundleLoader delegates[] = new JSBundleLoader[] { - recoverableLoader("url1", "error1"), - successfulLoader("url2"), - successfulLoader("url3") - }; + JSBundleLoader delegates[] = + new JSBundleLoader[] { + recoverableLoader("url1", "error1"), successfulLoader("url2"), successfulLoader("url3") + }; FallbackJSBundleLoader fallbackLoader = - new FallbackJSBundleLoader(new ArrayList<>(Arrays.asList(delegates))); + new FallbackJSBundleLoader(new ArrayList<>(Arrays.asList(delegates))); assertThat(fallbackLoader.loadScript(null)).isEqualTo("url2"); @@ -83,22 +74,21 @@ public class FallbackJSBundleLoaderTest { verify(delegates[1], times(1)).loadScript(null); verify(delegates[2], never()).loadScript(null); - assertThat(mLoggingDelegate.logContains( - FakeLoggingDelegate.WTF, - FallbackJSBundleLoader.TAG, - recoverableMsg("error1"))) - .isTrue(); + assertThat( + mLoggingDelegate.logContains( + FakeLoggingDelegate.WTF, FallbackJSBundleLoader.TAG, recoverableMsg("error1"))) + .isTrue(); } @Test public void fallingbackUnsuccessfully() { - JSBundleLoader delegates[] = new JSBundleLoader[] { - recoverableLoader("url1", "error1"), - recoverableLoader("url2", "error2") - }; + JSBundleLoader delegates[] = + new JSBundleLoader[] { + recoverableLoader("url1", "error1"), recoverableLoader("url2", "error2") + }; FallbackJSBundleLoader fallbackLoader = - new FallbackJSBundleLoader(new ArrayList<>(Arrays.asList(delegates))); + new FallbackJSBundleLoader(new ArrayList<>(Arrays.asList(delegates))); try { fallbackLoader.loadScript(null); @@ -113,36 +103,30 @@ public class FallbackJSBundleLoaderTest { cause = cause.getCause(); } - assertThat(msgs).containsExactly( - recoverableMsg("error1"), - recoverableMsg("error2")); + assertThat(msgs).containsExactly(recoverableMsg("error1"), recoverableMsg("error2")); } verify(delegates[0], times(1)).loadScript(null); verify(delegates[1], times(1)).loadScript(null); - assertThat(mLoggingDelegate.logContains( - FakeLoggingDelegate.WTF, - FallbackJSBundleLoader.TAG, - recoverableMsg("error1"))) - .isTrue(); + assertThat( + mLoggingDelegate.logContains( + FakeLoggingDelegate.WTF, FallbackJSBundleLoader.TAG, recoverableMsg("error1"))) + .isTrue(); - assertThat(mLoggingDelegate.logContains( - FakeLoggingDelegate.WTF, - FallbackJSBundleLoader.TAG, - recoverableMsg("error2"))) - .isTrue(); + assertThat( + mLoggingDelegate.logContains( + FakeLoggingDelegate.WTF, FallbackJSBundleLoader.TAG, recoverableMsg("error2"))) + .isTrue(); } @Test public void unrecoverable() { - JSBundleLoader delegates[] = new JSBundleLoader[] { - fatalLoader("url1", "error1"), - recoverableLoader("url2", "error2") - }; + JSBundleLoader delegates[] = + new JSBundleLoader[] {fatalLoader("url1", "error1"), recoverableLoader("url2", "error2")}; FallbackJSBundleLoader fallbackLoader = - new FallbackJSBundleLoader(new ArrayList(Arrays.asList(delegates))); + new FallbackJSBundleLoader(new ArrayList(Arrays.asList(delegates))); try { fallbackLoader.loadScript(null); @@ -154,11 +138,9 @@ public class FallbackJSBundleLoaderTest { verify(delegates[0], times(1)).loadScript(null); verify(delegates[1], never()).loadScript(null); - assertThat(mLoggingDelegate.logContains( - FakeLoggingDelegate.WTF, - FallbackJSBundleLoader.TAG, - null)) - .isFalse(); + assertThat( + mLoggingDelegate.logContains(FakeLoggingDelegate.WTF, FallbackJSBundleLoader.TAG, null)) + .isFalse(); } private static JSBundleLoader successfulLoader(String url) { @@ -175,7 +157,7 @@ public class FallbackJSBundleLoaderTest { private static JSBundleLoader recoverableLoader(String url, String errMsg) { JSBundleLoader loader = mock(JSBundleLoader.class); when(loader.loadScript(null)) - .thenThrow(new RuntimeException(FallbackJSBundleLoader.RECOVERABLE + errMsg)); + .thenThrow(new RuntimeException(FallbackJSBundleLoader.RECOVERABLE + errMsg)); return loader; } @@ -186,8 +168,7 @@ public class FallbackJSBundleLoaderTest { private static JSBundleLoader fatalLoader(String url, String errMsg) { JSBundleLoader loader = mock(JSBundleLoader.class); - when(loader.loadScript(null)) - .thenThrow(new RuntimeException(UNRECOVERABLE + errMsg)); + when(loader.loadScript(null)).thenThrow(new RuntimeException(UNRECOVERABLE + errMsg)); return loader; } diff --git a/ReactAndroid/src/test/java/com/facebook/react/bridge/InstanceHandleHelper.java b/ReactAndroid/src/test/java/com/facebook/react/bridge/InstanceHandleHelper.java index 836ac568041..ed8a895cde3 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/bridge/InstanceHandleHelper.java +++ b/ReactAndroid/src/test/java/com/facebook/react/bridge/InstanceHandleHelper.java @@ -1,13 +1,11 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; - import java.util.Random; public class InstanceHandleHelper { diff --git a/ReactAndroid/src/test/java/com/facebook/react/bridge/JavaOnlyArrayTest.java b/ReactAndroid/src/test/java/com/facebook/react/bridge/JavaOnlyArrayTest.java index 571b96900c1..b799046e49e 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/bridge/JavaOnlyArrayTest.java +++ b/ReactAndroid/src/test/java/com/facebook/react/bridge/JavaOnlyArrayTest.java @@ -1,42 +1,33 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; -import org.junit.Test; - import static org.fest.assertions.api.Assertions.assertThat; -/** - * Tests for {@link JavaOnlyArray} - */ +import org.junit.Test; + +/** Tests for {@link JavaOnlyArray} */ public class JavaOnlyArrayTest { @Test public void testGetType() throws Exception { - JavaOnlyArray values = JavaOnlyArray.of( - 1, - 2f, - 3., - "4", - false, - JavaOnlyArray.of(), - JavaOnlyMap.of(), - null); - ReadableType[] expectedTypes = new ReadableType[] { - ReadableType.Number, - ReadableType.Number, - ReadableType.Number, - ReadableType.String, - ReadableType.Boolean, - ReadableType.Array, - ReadableType.Map, - ReadableType.Null - }; + JavaOnlyArray values = + JavaOnlyArray.of(1, 2f, 3., "4", false, JavaOnlyArray.of(), JavaOnlyMap.of(), null); + ReadableType[] expectedTypes = + new ReadableType[] { + ReadableType.Number, + ReadableType.Number, + ReadableType.Number, + ReadableType.String, + ReadableType.Boolean, + ReadableType.Array, + ReadableType.Map, + ReadableType.Null + }; for (int i = 0; i < values.size(); i++) { assertThat(values.getType(i)).isEqualTo(expectedTypes[i]); diff --git a/ReactAndroid/src/test/java/com/facebook/react/bridge/JsonWriterTest.java b/ReactAndroid/src/test/java/com/facebook/react/bridge/JsonWriterTest.java index 262c187b7e4..ea031b3c28d 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/bridge/JsonWriterTest.java +++ b/ReactAndroid/src/test/java/com/facebook/react/bridge/JsonWriterTest.java @@ -1,19 +1,17 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; +import static org.fest.assertions.api.Assertions.assertThat; + import java.io.IOException; import java.io.StringWriter; - import org.junit.Test; -import static org.fest.assertions.api.Assertions.assertThat; - public class JsonWriterTest { private final StringWriter mStringWriter; private final JsonWriter mWriter; diff --git a/ReactAndroid/src/test/java/com/facebook/react/bridge/ReactTestHelper.java b/ReactAndroid/src/test/java/com/facebook/react/bridge/ReactTestHelper.java index 7722823038d..51b145edd28 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/bridge/ReactTestHelper.java +++ b/ReactAndroid/src/test/java/com/facebook/react/bridge/ReactTestHelper.java @@ -1,56 +1,51 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.bridge; -import com.facebook.react.bridge.queue.ReactQueueConfiguration; -import com.facebook.react.bridge.queue.ReactQueueConfigurationImpl; -import com.facebook.react.bridge.queue.ReactQueueConfigurationSpec; -import com.facebook.react.bridge.queue.MessageQueueThreadSpec; -import com.facebook.react.bridge.queue.QueueThreadExceptionHandler; -import com.facebook.react.uimanager.UIManagerModule; - -import org.robolectric.RuntimeEnvironment; - import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -/** - * Utility for creating pre-configured instances of core react components for tests. - */ +import com.facebook.react.bridge.queue.MessageQueueThreadSpec; +import com.facebook.react.bridge.queue.QueueThreadExceptionHandler; +import com.facebook.react.bridge.queue.ReactQueueConfiguration; +import com.facebook.react.bridge.queue.ReactQueueConfigurationImpl; +import com.facebook.react.bridge.queue.ReactQueueConfigurationSpec; +import com.facebook.react.uimanager.UIManagerModule; +import org.robolectric.RuntimeEnvironment; + +/** Utility for creating pre-configured instances of core react components for tests. */ public class ReactTestHelper { /** - * @return a ReactApplicationContext that has a CatalystInstance mock returned by - * {@link #createMockCatalystInstance} + * @return a ReactApplicationContext that has a CatalystInstance mock returned by {@link + * #createMockCatalystInstance} */ public static ReactApplicationContext createCatalystContextForTest() { - ReactApplicationContext context = - new ReactApplicationContext(RuntimeEnvironment.application); + ReactApplicationContext context = new ReactApplicationContext(RuntimeEnvironment.application); context.initializeWithInstance(createMockCatalystInstance()); return context; } - /** - * @return a CatalystInstance mock that has a default working ReactQueueConfiguration. - */ + /** @return a CatalystInstance mock that has a default working ReactQueueConfiguration. */ public static CatalystInstance createMockCatalystInstance() { - ReactQueueConfigurationSpec spec = ReactQueueConfigurationSpec.builder() - .setJSQueueThreadSpec(MessageQueueThreadSpec.mainThreadSpec()) - .setNativeModulesQueueThreadSpec(MessageQueueThreadSpec.mainThreadSpec()) - .build(); - ReactQueueConfiguration ReactQueueConfiguration = ReactQueueConfigurationImpl.create( - spec, - new QueueThreadExceptionHandler() { - @Override - public void handleException(Exception e) { - throw new RuntimeException(e); - } - }); + ReactQueueConfigurationSpec spec = + ReactQueueConfigurationSpec.builder() + .setJSQueueThreadSpec(MessageQueueThreadSpec.mainThreadSpec()) + .setNativeModulesQueueThreadSpec(MessageQueueThreadSpec.mainThreadSpec()) + .build(); + ReactQueueConfiguration ReactQueueConfiguration = + ReactQueueConfigurationImpl.create( + spec, + new QueueThreadExceptionHandler() { + @Override + public void handleException(Exception e) { + throw new RuntimeException(e); + } + }); CatalystInstance reactInstance = mock(CatalystInstance.class); when(reactInstance.getReactQueueConfiguration()).thenReturn(ReactQueueConfiguration); diff --git a/ReactAndroid/src/test/java/com/facebook/react/devsupport/BundleDeltaClientTest.java b/ReactAndroid/src/test/java/com/facebook/react/devsupport/BundleDeltaClientTest.java index ef36e6a0b8c..0706a7fad84 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/devsupport/BundleDeltaClientTest.java +++ b/ReactAndroid/src/test/java/com/facebook/react/devsupport/BundleDeltaClientTest.java @@ -9,19 +9,18 @@ package com.facebook.react.devsupport; import static org.fest.assertions.api.Assertions.assertThat; import com.facebook.react.common.StandardCharsets; -import com.facebook.react.devsupport.BundleDeltaClient; -import org.junit.Test; -import org.junit.Before; -import org.junit.runner.RunWith; -import org.robolectric.RobolectricTestRunner; -import okio.BufferedSource; -import org.junit.Rule; -import org.junit.rules.TemporaryFolder; -import okio.Okio; import java.io.ByteArrayInputStream; -import java.nio.file.Files; import java.io.File; import java.io.IOException; +import java.nio.file.Files; +import okio.BufferedSource; +import okio.Okio; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricTestRunner; @RunWith(RobolectricTestRunner.class) public class BundleDeltaClientTest { @@ -72,12 +71,7 @@ public class BundleDeltaClientTest { + "\"deleted\": [1]" + "}"), file); - assertThat(contentOf(file)) - .isEqualTo( - "pre\n" - + "0.1\n" - + "2\n" - + "post\n"); + assertThat(contentOf(file)).isEqualTo("pre\n" + "0.1\n" + "2\n" + "post\n"); } @Test @@ -101,34 +95,34 @@ public class BundleDeltaClientTest { + "console.log('That is all folks!');\n"); } - @Test - public void testSortsModulesByIdInPatchedBundle() throws IOException { - File file = mFolder.newFile(); - mClient.processDelta( - bufferedSource( - "{" - + "\"pre\": \"console.log('Hello World!');\"," - + "\"post\": \"console.log('That is all folks!');\"," - + "\"modules\": [[3, \"3\"], [0, \"0\"], [1, \"1\"]]" - + "}"), - file); - file = mFolder.newFile(); - mClient.processDelta( - bufferedSource( - "{" - + "\"added\": [[2, \"2\"]]," - + "\"modified\": [[0, \"0.1\"]]," - + "\"deleted\": [1]" - + "}"), - file); - assertThat(contentOf(file)) - .isEqualTo( - "console.log('Hello World!');\n" - + "0.1\n" - + "2\n" - + "3\n" - + "console.log('That is all folks!');\n"); - } + @Test + public void testSortsModulesByIdInPatchedBundle() throws IOException { + File file = mFolder.newFile(); + mClient.processDelta( + bufferedSource( + "{" + + "\"pre\": \"console.log('Hello World!');\"," + + "\"post\": \"console.log('That is all folks!');\"," + + "\"modules\": [[3, \"3\"], [0, \"0\"], [1, \"1\"]]" + + "}"), + file); + file = mFolder.newFile(); + mClient.processDelta( + bufferedSource( + "{" + + "\"added\": [[2, \"2\"]]," + + "\"modified\": [[0, \"0.1\"]]," + + "\"deleted\": [1]" + + "}"), + file); + assertThat(contentOf(file)) + .isEqualTo( + "console.log('Hello World!');\n" + + "0.1\n" + + "2\n" + + "3\n" + + "console.log('That is all folks!');\n"); + } private static BufferedSource bufferedSource(String string) { return Okio.buffer( diff --git a/ReactAndroid/src/test/java/com/facebook/react/devsupport/JSDebuggerWebSocketClientTest.java b/ReactAndroid/src/test/java/com/facebook/react/devsupport/JSDebuggerWebSocketClientTest.java index 77f4c852b64..ee5a6bf0a16 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/devsupport/JSDebuggerWebSocketClientTest.java +++ b/ReactAndroid/src/test/java/com/facebook/react/devsupport/JSDebuggerWebSocketClientTest.java @@ -1,14 +1,16 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.devsupport; -import com.facebook.react.common.JavascriptException; +import static org.mockito.Mockito.*; +import com.facebook.react.common.JavascriptException; +import java.util.HashMap; +import okio.ByteString; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; @@ -18,35 +20,28 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.rule.PowerMockRule; import org.robolectric.RobolectricTestRunner; -import java.util.HashMap; - -import okio.ByteString; - -import static org.mockito.Mockito.*; - -@PrepareForTest({ JSDebuggerWebSocketClient.class }) +@PrepareForTest({JSDebuggerWebSocketClient.class}) @RunWith(RobolectricTestRunner.class) @PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "androidx.*", "android.*"}) public class JSDebuggerWebSocketClientTest { - @Rule - public PowerMockRule rule = new PowerMockRule(); + @Rule public PowerMockRule rule = new PowerMockRule(); @Test public void test_prepareJSRuntime_ShouldSendCorrectMessage() throws Exception { final JSDebuggerWebSocketClient.JSDebuggerCallback cb = - PowerMockito.mock(JSDebuggerWebSocketClient.JSDebuggerCallback.class); + PowerMockito.mock(JSDebuggerWebSocketClient.JSDebuggerCallback.class); JSDebuggerWebSocketClient client = PowerMockito.spy(new JSDebuggerWebSocketClient()); client.prepareJSRuntime(cb); - PowerMockito.verifyPrivate(client).invoke("sendMessage", 0, - "{\"id\":0,\"method\":\"prepareJSRuntime\"}"); + PowerMockito.verifyPrivate(client) + .invoke("sendMessage", 0, "{\"id\":0,\"method\":\"prepareJSRuntime\"}"); } @Test public void test_loadApplicationScript_ShouldSendCorrectMessage() throws Exception { final JSDebuggerWebSocketClient.JSDebuggerCallback cb = - PowerMockito.mock(JSDebuggerWebSocketClient.JSDebuggerCallback.class); + PowerMockito.mock(JSDebuggerWebSocketClient.JSDebuggerCallback.class); JSDebuggerWebSocketClient client = PowerMockito.spy(new JSDebuggerWebSocketClient()); HashMap injectedObjects = new HashMap<>(); @@ -54,21 +49,24 @@ public class JSDebuggerWebSocketClientTest { injectedObjects.put("key2", "value2"); client.loadApplicationScript("http://localhost:8080/index.js", injectedObjects, cb); - PowerMockito.verifyPrivate(client).invoke("sendMessage", 0, - "{\"id\":0,\"method\":\"executeApplicationScript\",\"url\":\"http://localhost:8080/index.js\"" + - ",\"inject\":{\"key1\":\"value1\",\"key2\":\"value2\"}}"); + PowerMockito.verifyPrivate(client) + .invoke( + "sendMessage", + 0, + "{\"id\":0,\"method\":\"executeApplicationScript\",\"url\":\"http://localhost:8080/index.js\"" + + ",\"inject\":{\"key1\":\"value1\",\"key2\":\"value2\"}}"); } @Test public void test_executeJSCall_ShouldSendCorrectMessage() throws Exception { final JSDebuggerWebSocketClient.JSDebuggerCallback cb = - PowerMockito.mock(JSDebuggerWebSocketClient.JSDebuggerCallback.class); + PowerMockito.mock(JSDebuggerWebSocketClient.JSDebuggerCallback.class); JSDebuggerWebSocketClient client = PowerMockito.spy(new JSDebuggerWebSocketClient()); client.executeJSCall("foo", "[1,2,3]", cb); - PowerMockito.verifyPrivate(client).invoke("sendMessage", 0, - "{\"id\":0,\"method\":\"foo\",\"arguments\":[1,2,3]}"); + PowerMockito.verifyPrivate(client) + .invoke("sendMessage", 0, "{\"id\":0,\"method\":\"foo\",\"arguments\":[1,2,3]}"); } @Test @@ -76,7 +74,8 @@ public class JSDebuggerWebSocketClientTest { JSDebuggerWebSocketClient client = PowerMockito.spy(new JSDebuggerWebSocketClient()); client.onMessage(null, ByteString.encodeUtf8("{\"replyID\":0, \"result\":\"OK\"}")); - PowerMockito.verifyPrivate(client, never()).invoke("triggerRequestSuccess", anyInt(), anyString()); + PowerMockito.verifyPrivate(client, never()) + .invoke("triggerRequestSuccess", anyInt(), anyString()); PowerMockito.verifyPrivate(client, never()).invoke("triggerRequestFailure", anyInt(), any()); } @@ -85,7 +84,8 @@ public class JSDebuggerWebSocketClientTest { JSDebuggerWebSocketClient client = PowerMockito.spy(new JSDebuggerWebSocketClient()); client.onMessage(null, "{\"result\":\"OK\"}"); - PowerMockito.verifyPrivate(client, never()).invoke("triggerRequestSuccess", anyInt(), anyString()); + PowerMockito.verifyPrivate(client, never()) + .invoke("triggerRequestSuccess", anyInt(), anyString()); PowerMockito.verifyPrivate(client, never()).invoke("triggerRequestFailure", anyInt(), any()); } @@ -94,7 +94,8 @@ public class JSDebuggerWebSocketClientTest { JSDebuggerWebSocketClient client = PowerMockito.spy(new JSDebuggerWebSocketClient()); client.onMessage(null, "{\"replyID\":null, \"result\":\"OK\"}"); - PowerMockito.verifyPrivate(client, never()).invoke("triggerRequestSuccess", anyInt(), anyString()); + PowerMockito.verifyPrivate(client, never()) + .invoke("triggerRequestSuccess", anyInt(), anyString()); PowerMockito.verifyPrivate(client, never()).invoke("triggerRequestFailure", anyInt(), any()); } diff --git a/ReactAndroid/src/test/java/com/facebook/react/devsupport/MultipartStreamReaderTest.java b/ReactAndroid/src/test/java/com/facebook/react/devsupport/MultipartStreamReaderTest.java index 311819523fe..9d30511d883 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/devsupport/MultipartStreamReaderTest.java +++ b/ReactAndroid/src/test/java/com/facebook/react/devsupport/MultipartStreamReaderTest.java @@ -1,23 +1,20 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.devsupport; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.robolectric.RobolectricTestRunner; +import static org.fest.assertions.api.Assertions.assertThat; import java.io.IOException; import java.util.Map; - import okio.Buffer; import okio.ByteString; - -import static org.fest.assertions.api.Assertions.assertThat; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricTestRunner; @RunWith(RobolectricTestRunner.class) public class MultipartStreamReaderTest { @@ -26,14 +23,14 @@ public class MultipartStreamReaderTest { private int mCount = 0; @Override - public void onChunkComplete(Map headers, Buffer body, boolean done) throws IOException { + public void onChunkComplete(Map headers, Buffer body, boolean done) + throws IOException { mCount++; } @Override - public void onChunkProgress(Map headers, long loaded, long total) throws IOException { - - } + public void onChunkProgress(Map headers, long loaded, long total) + throws IOException {} public int getCallCount() { return mCount; @@ -42,30 +39,33 @@ public class MultipartStreamReaderTest { @Test public void testSimpleCase() throws IOException { - ByteString response = ByteString.encodeUtf8( - "preable, should be ignored\r\n" + - "--sample_boundary\r\n" + - "Content-Type: application/json; charset=utf-8\r\n" + - "Content-Length: 2\r\n\r\n" + - "{}\r\n" + - "--sample_boundary--\r\n" + - "epilogue, should be ignored"); + ByteString response = + ByteString.encodeUtf8( + "preable, should be ignored\r\n" + + "--sample_boundary\r\n" + + "Content-Type: application/json; charset=utf-8\r\n" + + "Content-Length: 2\r\n\r\n" + + "{}\r\n" + + "--sample_boundary--\r\n" + + "epilogue, should be ignored"); Buffer source = new Buffer(); source.write(response); MultipartStreamReader reader = new MultipartStreamReader(source, "sample_boundary"); - CallCountTrackingChunkCallback callback = new CallCountTrackingChunkCallback() { - @Override - public void onChunkComplete(Map headers, Buffer body, boolean done) throws IOException { - super.onChunkComplete(headers, body, done); + CallCountTrackingChunkCallback callback = + new CallCountTrackingChunkCallback() { + @Override + public void onChunkComplete(Map headers, Buffer body, boolean done) + throws IOException { + super.onChunkComplete(headers, body, done); - assertThat(done).isTrue(); - assertThat(headers.get("Content-Type")).isEqualTo("application/json; charset=utf-8"); - assertThat(body.readUtf8()).isEqualTo("{}"); - } - }; + assertThat(done).isTrue(); + assertThat(headers.get("Content-Type")).isEqualTo("application/json; charset=utf-8"); + assertThat(body.readUtf8()).isEqualTo("{}"); + } + }; boolean success = reader.readAllParts(callback); assertThat(callback.getCallCount()).isEqualTo(1); @@ -74,31 +74,34 @@ public class MultipartStreamReaderTest { @Test public void testMultipleParts() throws IOException { - ByteString response = ByteString.encodeUtf8( - "preable, should be ignored\r\n" + - "--sample_boundary\r\n" + - "1\r\n" + - "--sample_boundary\r\n" + - "2\r\n" + - "--sample_boundary\r\n" + - "3\r\n" + - "--sample_boundary--\r\n" + - "epilogue, should be ignored"); + ByteString response = + ByteString.encodeUtf8( + "preable, should be ignored\r\n" + + "--sample_boundary\r\n" + + "1\r\n" + + "--sample_boundary\r\n" + + "2\r\n" + + "--sample_boundary\r\n" + + "3\r\n" + + "--sample_boundary--\r\n" + + "epilogue, should be ignored"); Buffer source = new Buffer(); source.write(response); MultipartStreamReader reader = new MultipartStreamReader(source, "sample_boundary"); - CallCountTrackingChunkCallback callback = new CallCountTrackingChunkCallback() { - @Override - public void onChunkComplete(Map headers, Buffer body, boolean done) throws IOException { - super.onChunkComplete(headers, body, done); + CallCountTrackingChunkCallback callback = + new CallCountTrackingChunkCallback() { + @Override + public void onChunkComplete(Map headers, Buffer body, boolean done) + throws IOException { + super.onChunkComplete(headers, body, done); - assertThat(done).isEqualTo(getCallCount() == 3); - assertThat(body.readUtf8()).isEqualTo(String.valueOf(getCallCount())); - } - }; + assertThat(done).isEqualTo(getCallCount() == 3); + assertThat(body.readUtf8()).isEqualTo(String.valueOf(getCallCount())); + } + }; boolean success = reader.readAllParts(callback); assertThat(callback.getCallCount()).isEqualTo(3); @@ -123,14 +126,15 @@ public class MultipartStreamReaderTest { @Test public void testNoCloseDelimiter() throws IOException { - ByteString response = ByteString.encodeUtf8( - "preable, should be ignored\r\n" + - "--sample_boundary\r\n" + - "Content-Type: application/json; charset=utf-8\r\n" + - "Content-Length: 2\r\n\r\n" + - "{}\r\n" + - "--sample_boundary\r\n" + - "incomplete message..."); + ByteString response = + ByteString.encodeUtf8( + "preable, should be ignored\r\n" + + "--sample_boundary\r\n" + + "Content-Type: application/json; charset=utf-8\r\n" + + "Content-Length: 2\r\n\r\n" + + "{}\r\n" + + "--sample_boundary\r\n" + + "incomplete message..."); Buffer source = new Buffer(); source.write(response); diff --git a/ReactAndroid/src/test/java/com/facebook/react/devsupport/StackTraceHelperTest.java b/ReactAndroid/src/test/java/com/facebook/react/devsupport/StackTraceHelperTest.java index 9fc112b2879..09d240b647e 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/devsupport/StackTraceHelperTest.java +++ b/ReactAndroid/src/test/java/com/facebook/react/devsupport/StackTraceHelperTest.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.devsupport; import static org.fest.assertions.api.Assertions.assertThat; @@ -19,8 +18,8 @@ public class StackTraceHelperTest { @Test public void testParseAlternateFormatStackFrameWithMethod() { - final StackFrame frame = StackTraceHelper.convertJsStackTrace( - "at func1 (/path/to/file.js:2:18)")[0]; + final StackFrame frame = + StackTraceHelper.convertJsStackTrace("at func1 (/path/to/file.js:2:18)")[0]; assertThat(frame.getMethod()).isEqualTo("func1"); assertThat(frame.getFileName()).isEqualTo("file.js"); assertThat(frame.getLine()).isEqualTo(2); @@ -29,8 +28,7 @@ public class StackTraceHelperTest { @Test public void testParseStackFrameWithMethod() { - final StackFrame frame = StackTraceHelper.convertJsStackTrace( - "render@Test.bundle:1:2000")[0]; + final StackFrame frame = StackTraceHelper.convertJsStackTrace("render@Test.bundle:1:2000")[0]; assertThat(frame.getMethod()).isEqualTo("render"); assertThat(frame.getFileName()).isEqualTo("Test.bundle"); assertThat(frame.getLine()).isEqualTo(1); @@ -39,8 +37,7 @@ public class StackTraceHelperTest { @Test public void testParseStackFrameWithoutMethod() { - final StackFrame frame = StackTraceHelper.convertJsStackTrace( - "Test.bundle:1:2000")[0]; + final StackFrame frame = StackTraceHelper.convertJsStackTrace("Test.bundle:1:2000")[0]; assertThat(frame.getMethod()).isEqualTo("(unknown)"); assertThat(frame.getFileName()).isEqualTo("Test.bundle"); assertThat(frame.getLine()).isEqualTo(1); diff --git a/ReactAndroid/src/test/java/com/facebook/react/modules/blob/BlobModuleTest.java b/ReactAndroid/src/test/java/com/facebook/react/modules/blob/BlobModuleTest.java index 582209827df..147c2dbd6bc 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/modules/blob/BlobModuleTest.java +++ b/ReactAndroid/src/test/java/com/facebook/react/modules/blob/BlobModuleTest.java @@ -1,19 +1,25 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.blob; -import android.net.Uri; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import android.net.Uri; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.JavaOnlyArray; import com.facebook.react.bridge.JavaOnlyMap; import com.facebook.react.bridge.ReactTestHelper; - +import java.nio.ByteBuffer; +import java.nio.charset.Charset; +import java.util.Arrays; +import java.util.Random; +import java.util.UUID; import org.junit.After; import org.junit.Before; import org.junit.Rule; @@ -29,16 +35,6 @@ import org.powermock.modules.junit4.rule.PowerMockRule; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; -import java.nio.ByteBuffer; -import java.nio.charset.Charset; -import java.util.Arrays; -import java.util.Random; -import java.util.UUID; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - @PrepareForTest({Arguments.class}) @RunWith(RobolectricTestRunner.class) @PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "androidx.*", "android.*"}) @@ -49,18 +45,19 @@ public class BlobModuleTest { private String mBlobId; private BlobModule mBlobModule; - @Rule - public PowerMockRule rule = new PowerMockRule(); + @Rule public PowerMockRule rule = new PowerMockRule(); @Before public void prepareModules() throws Exception { PowerMockito.mockStatic(Arguments.class); - Mockito.when(Arguments.createMap()).thenAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - return new JavaOnlyMap(); - } - }); + Mockito.when(Arguments.createMap()) + .thenAnswer( + new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + return new JavaOnlyMap(); + } + }); mBytes = new byte[120]; new Random().nextBytes(mBytes); @@ -83,11 +80,12 @@ public class BlobModuleTest { @Test public void testResolveUri() { - Uri uri = new Uri.Builder() - .appendPath(mBlobId) - .appendQueryParameter("offset", "0") - .appendQueryParameter("size", String.valueOf(mBytes.length)) - .build(); + Uri uri = + new Uri.Builder() + .appendPath(mBlobId) + .appendQueryParameter("offset", "0") + .appendQueryParameter("size", String.valueOf(mBytes.length)) + .build(); assertArrayEquals(mBytes, mBlobModule.resolve(uri)); } diff --git a/ReactAndroid/src/test/java/com/facebook/react/modules/camera/ImageStoreManagerTest.java b/ReactAndroid/src/test/java/com/facebook/react/modules/camera/ImageStoreManagerTest.java index 455f728ebd4..14dd987a72f 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/modules/camera/ImageStoreManagerTest.java +++ b/ReactAndroid/src/test/java/com/facebook/react/modules/camera/ImageStoreManagerTest.java @@ -1,30 +1,27 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ package com.facebook.react.modules.camera; -import android.util.Base64; -import android.util.Base64InputStream; - -import com.facebook.react.bridge.ReactApplicationContext; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.robolectric.RobolectricTestRunner; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.Random; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.mockito.Mockito.mock; +import android.util.Base64; +import android.util.Base64InputStream; +import com.facebook.react.bridge.ReactApplicationContext; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Random; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.robolectric.RobolectricTestRunner; + @RunWith(RobolectricTestRunner.class) @PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "androidx.*", "android.*"}) public class ImageStoreManagerTest { @@ -57,9 +54,7 @@ public class ImageStoreManagerTest { assertFalse(invokeConversion(inputStream).contains("\n")); } - /** - * Just to test if using the ByteArrayInputStream isn't missing something - */ + /** Just to test if using the ByteArrayInputStream isn't missing something */ @Test public void itDoesNotAddLineBreaks_whenBase64InputStream() throws IOException { byte[] exampleString = "dGVzdA==".getBytes(); diff --git a/ReactAndroid/src/test/java/com/facebook/react/modules/clipboard/ClipboardModuleTest.java b/ReactAndroid/src/test/java/com/facebook/react/modules/clipboard/ClipboardModuleTest.java index 677f8fc3647..a8bf0d4d7b6 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/modules/clipboard/ClipboardModuleTest.java +++ b/ReactAndroid/src/test/java/com/facebook/react/modules/clipboard/ClipboardModuleTest.java @@ -1,30 +1,24 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.clipboard; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + import android.annotation.SuppressLint; import android.content.Context; import android.text.ClipboardManager; - -import com.facebook.react.bridge.ReactTestHelper; -import com.facebook.react.modules.clipboard.ClipboardModule; - import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.assertFalse; - @SuppressLint({"ClipboardManager", "DeprecatedClass"}) @RunWith(RobolectricTestRunner.class) @PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "androidx.*", "android.*"}) @@ -39,7 +33,8 @@ public class ClipboardModuleTest { public void setUp() { mClipboardModule = new ClipboardModule(RuntimeEnvironment.application); mClipboardManager = - (ClipboardManager) RuntimeEnvironment.application.getSystemService(Context.CLIPBOARD_SERVICE); + (ClipboardManager) + RuntimeEnvironment.application.getSystemService(Context.CLIPBOARD_SERVICE); } @Test diff --git a/ReactAndroid/src/test/java/com/facebook/react/modules/dialog/DialogModuleTest.java b/ReactAndroid/src/test/java/com/facebook/react/modules/dialog/DialogModuleTest.java index 7a9fe4c5e6b..cb3caa5e6d3 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/modules/dialog/DialogModuleTest.java +++ b/ReactAndroid/src/test/java/com/facebook/react/modules/dialog/DialogModuleTest.java @@ -1,20 +1,21 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.dialog; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; + import android.app.AlertDialog; import android.content.DialogInterface; - - +import androidx.fragment.app.FragmentActivity; import com.facebook.react.bridge.Callback; -import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.JavaOnlyMap; - +import com.facebook.react.bridge.ReactApplicationContext; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -25,12 +26,6 @@ import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import org.robolectric.util.ActivityController; -import androidx.fragment.app.FragmentActivity; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; - @RunWith(RobolectricTestRunner.class) @PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "androidx.*", "android.*"}) public class DialogModuleTest { @@ -39,7 +34,7 @@ public class DialogModuleTest { private FragmentActivity mActivity; private DialogModule mDialogModule; - final static class SimpleCallback implements Callback { + static final class SimpleCallback implements Callback { private Object[] mArgs; private int mCalls; @@ -61,11 +56,7 @@ public class DialogModuleTest { @Before public void setUp() throws Exception { mActivityController = Robolectric.buildActivity(FragmentActivity.class); - mActivity = mActivityController - .create() - .start() - .resume() - .get(); + mActivity = mActivityController.create().start().resume().get(); final ReactApplicationContext context = PowerMockito.mock(ReactApplicationContext.class); PowerMockito.when(context.hasActiveCatalystInstance()).thenReturn(true); @@ -167,7 +158,7 @@ public class DialogModuleTest { } private AlertFragment getFragment() { - return (AlertFragment) mActivity.getSupportFragmentManager() - .findFragmentByTag(DialogModule.FRAGMENT_TAG); + return (AlertFragment) + mActivity.getSupportFragmentManager().findFragmentByTag(DialogModule.FRAGMENT_TAG); } } diff --git a/ReactAndroid/src/test/java/com/facebook/react/modules/network/HeaderUtilTest.java b/ReactAndroid/src/test/java/com/facebook/react/modules/network/HeaderUtilTest.java index 10e52ddc547..d4169ef1004 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/modules/network/HeaderUtilTest.java +++ b/ReactAndroid/src/test/java/com/facebook/react/modules/network/HeaderUtilTest.java @@ -1,16 +1,15 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.network; -import org.junit.Test; - import static org.junit.Assert.assertEquals; +import org.junit.Test; + public class HeaderUtilTest { public static final String TABULATION_TEST = "\teyJhbGciOiJS\t"; public static final String TABULATION_STRIP_EXPECTED = "eyJhbGciOiJS"; @@ -24,7 +23,6 @@ public class HeaderUtilTest { @Test public void nameStripKeepsLetters() { assertEquals(ALPHABET_TEST, HeaderUtil.stripHeaderName(ALPHABET_TEST)); - } @Test @@ -35,7 +33,6 @@ public class HeaderUtilTest { @Test public void nameStripKeepsNumbers() { assertEquals(NUMBERS_TEST, HeaderUtil.stripHeaderName(NUMBERS_TEST)); - } @Test @@ -72,5 +69,4 @@ public class HeaderUtilTest { public void nameStripRemovesExtraSymbols() { assertEquals(BANNED_TEST_EXPECTED, HeaderUtil.stripHeaderName(NAME_BANNED_SYMBOLS_TEST)); } - } diff --git a/ReactAndroid/src/test/java/com/facebook/react/modules/network/NetworkingModuleTest.java b/ReactAndroid/src/test/java/com/facebook/react/modules/network/NetworkingModuleTest.java index f22c56f72dc..00fd7f56e05 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/modules/network/NetworkingModuleTest.java +++ b/ReactAndroid/src/test/java/com/facebook/react/modules/network/NetworkingModuleTest.java @@ -1,15 +1,18 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.network; -import java.io.InputStream; -import java.util.Arrays; -import java.util.List; +import static org.fest.assertions.api.Assertions.assertThat; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.JavaOnlyArray; @@ -21,7 +24,9 @@ import com.facebook.react.bridge.WritableMap; import com.facebook.react.common.StandardCharsets; import com.facebook.react.common.network.OkHttpCallUtil; import com.facebook.react.modules.core.DeviceEventManagerModule.RCTDeviceEventEmitter; - +import java.io.InputStream; +import java.util.Arrays; +import java.util.List; import okhttp3.Call; import okhttp3.Headers; import okhttp3.MediaType; @@ -43,62 +48,54 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.rule.PowerMockRule; import org.robolectric.RobolectricTestRunner; -import static org.fest.assertions.api.Assertions.assertThat; -import static org.mockito.Mockito.any; -import static org.mockito.Mockito.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -/** - * Tests for {@link NetworkingModule}. - */ +/** Tests for {@link NetworkingModule}. */ @PrepareForTest({ - Arguments.class, - Call.class, - RequestBodyUtil.class, - ProgressRequestBody.class, - ProgressListener.class, - MultipartBody.class, - MultipartBody.Builder.class, - NetworkingModule.class, - OkHttpClient.class, - OkHttpClient.Builder.class, - OkHttpCallUtil.class}) + Arguments.class, + Call.class, + RequestBodyUtil.class, + ProgressRequestBody.class, + ProgressListener.class, + MultipartBody.class, + MultipartBody.Builder.class, + NetworkingModule.class, + OkHttpClient.class, + OkHttpClient.Builder.class, + OkHttpCallUtil.class +}) @RunWith(RobolectricTestRunner.class) @PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "androidx.*", "android.*"}) public class NetworkingModuleTest { - @Rule - public PowerMockRule rule = new PowerMockRule(); + @Rule public PowerMockRule rule = new PowerMockRule(); @Test public void testGetWithoutHeaders() throws Exception { OkHttpClient httpClient = mock(OkHttpClient.class); - when(httpClient.newCall(any(Request.class))).thenAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - Call callMock = mock(Call.class); - return callMock; - } - }); + when(httpClient.newCall(any(Request.class))) + .thenAnswer( + new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + Call callMock = mock(Call.class); + return callMock; + } + }); OkHttpClient.Builder clientBuilder = mock(OkHttpClient.Builder.class); when(clientBuilder.build()).thenReturn(httpClient); when(httpClient.newBuilder()).thenReturn(clientBuilder); NetworkingModule networkingModule = - new NetworkingModule(mock(ReactApplicationContext.class), "", httpClient); + new NetworkingModule(mock(ReactApplicationContext.class), "", httpClient); networkingModule.sendRequest( - "GET", - "http://somedomain/foo", - /* requestId */ 0, - /* headers */ JavaOnlyArray.of(), - /* body */ null, - /* responseType */ "text", - /* useIncrementalUpdates*/ true, - /* timeout */ 0, - /* withCredentials */ false); + "GET", + "http://somedomain/foo", + /* requestId */ 0, + /* headers */ JavaOnlyArray.of(), + /* body */ null, + /* responseType */ "text", + /* useIncrementalUpdates*/ true, + /* timeout */ 0, + /* withCredentials */ false); ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(Request.class); verify(httpClient).newCall(argumentCaptor.capture()); @@ -125,15 +122,15 @@ public class NetworkingModuleTest { mockEvents(); networkingModule.sendRequest( - "GET", - "http://somedoman/foo", - /* requestId */ 0, - /* headers */ JavaOnlyArray.from(invalidHeaders), - /* body */ null, - /* responseType */ "text", - /* useIncrementalUpdates*/ true, - /* timeout */ 0, - /* withCredentials */ false); + "GET", + "http://somedoman/foo", + /* requestId */ 0, + /* headers */ JavaOnlyArray.from(invalidHeaders), + /* body */ null, + /* responseType */ "text", + /* useIncrementalUpdates*/ true, + /* timeout */ 0, + /* withCredentials */ false); verifyErrorEmit(emitter, 0); } @@ -156,15 +153,15 @@ public class NetworkingModuleTest { mockEvents(); networkingModule.sendRequest( - "POST", - "http://somedomain/bar", - 0, - JavaOnlyArray.of(), - body, - /* responseType */ "text", - /* useIncrementalUpdates*/ true, - /* timeout */ 0, - /* withCredentials */ false); + "POST", + "http://somedomain/bar", + 0, + JavaOnlyArray.of(), + body, + /* responseType */ "text", + /* useIncrementalUpdates*/ true, + /* timeout */ 0, + /* withCredentials */ false); verifyErrorEmit(emitter, 0); } @@ -184,15 +181,15 @@ public class NetworkingModuleTest { mockEvents(); networkingModule.sendRequest( - "GET", - "aaa", - /* requestId */ 0, - /* headers */ JavaOnlyArray.of(), - /* body */ null, - /* responseType */ "text", - /* useIncrementalUpdates*/ true, - /* timeout */ 0, - /* withCredentials */ false); + "GET", + "aaa", + /* requestId */ 0, + /* headers */ JavaOnlyArray.of(), + /* body */ null, + /* responseType */ "text", + /* useIncrementalUpdates*/ true, + /* timeout */ 0, + /* withCredentials */ false); verifyErrorEmit(emitter, 0); } @@ -208,21 +205,23 @@ public class NetworkingModuleTest { private static void mockEvents() { PowerMockito.mockStatic(Arguments.class); - Mockito.when(Arguments.createArray()).thenAnswer( - new Answer() { - @Override - public WritableArray answer(InvocationOnMock invocation) throws Throwable { - return new JavaOnlyArray(); - } - }); + Mockito.when(Arguments.createArray()) + .thenAnswer( + new Answer() { + @Override + public WritableArray answer(InvocationOnMock invocation) throws Throwable { + return new JavaOnlyArray(); + } + }); - Mockito.when(Arguments.createMap()).thenAnswer( - new Answer() { - @Override - public WritableMap answer(InvocationOnMock invocation) throws Throwable { - return new JavaOnlyMap(); - } - }); + Mockito.when(Arguments.createMap()) + .thenAnswer( + new Answer() { + @Override + public WritableMap answer(InvocationOnMock invocation) throws Throwable { + return new JavaOnlyMap(); + } + }); } @Test @@ -232,13 +231,15 @@ public class NetworkingModuleTest { when(context.getJSModule(any(Class.class))).thenReturn(emitter); OkHttpClient httpClient = mock(OkHttpClient.class); - when(httpClient.newCall(any(Request.class))).thenAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - Call callMock = mock(Call.class); - return callMock; - } - }); + when(httpClient.newCall(any(Request.class))) + .thenAnswer( + new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + Call callMock = mock(Call.class); + return callMock; + } + }); OkHttpClient.Builder clientBuilder = mock(OkHttpClient.Builder.class); when(clientBuilder.build()).thenReturn(httpClient); when(httpClient.newBuilder()).thenReturn(clientBuilder); @@ -250,15 +251,15 @@ public class NetworkingModuleTest { mockEvents(); networkingModule.sendRequest( - "POST", - "http://somedomain/bar", - 0, - JavaOnlyArray.of(JavaOnlyArray.of("Content-Type", "text/plain")), - body, - /* responseType */ "text", - /* useIncrementalUpdates*/ true, - /* timeout */ 0, - /* withCredentials */ false); + "POST", + "http://somedomain/bar", + 0, + JavaOnlyArray.of(JavaOnlyArray.of("Content-Type", "text/plain")), + body, + /* responseType */ "text", + /* useIncrementalUpdates*/ true, + /* timeout */ 0, + /* withCredentials */ false); ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(Request.class); verify(httpClient).newCall(argumentCaptor.capture()); @@ -275,33 +276,36 @@ public class NetworkingModuleTest { @Test public void testHeaders() throws Exception { OkHttpClient httpClient = mock(OkHttpClient.class); - when(httpClient.newCall(any(Request.class))).thenAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - Call callMock = mock(Call.class); - return callMock; - } - }); + when(httpClient.newCall(any(Request.class))) + .thenAnswer( + new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + Call callMock = mock(Call.class); + return callMock; + } + }); OkHttpClient.Builder clientBuilder = mock(OkHttpClient.Builder.class); when(clientBuilder.build()).thenReturn(httpClient); when(httpClient.newBuilder()).thenReturn(clientBuilder); NetworkingModule networkingModule = - new NetworkingModule(mock(ReactApplicationContext.class), "", httpClient); + new NetworkingModule(mock(ReactApplicationContext.class), "", httpClient); - List headers = Arrays.asList( - JavaOnlyArray.of("Accept", "text/plain"), - JavaOnlyArray.of("User-Agent", "React test agent/1.0")); + List headers = + Arrays.asList( + JavaOnlyArray.of("Accept", "text/plain"), + JavaOnlyArray.of("User-Agent", "React test agent/1.0")); networkingModule.sendRequest( - "GET", - "http://someurl/baz", - 0, - JavaOnlyArray.from(headers), - null, - /* responseType */ "text", - /* useIncrementalUpdates*/ true, - /* timeout */ 0, - /* withCredentials */ false); + "GET", + "http://someurl/baz", + 0, + JavaOnlyArray.from(headers), + null, + /* responseType */ "text", + /* useIncrementalUpdates*/ true, + /* timeout */ 0, + /* withCredentials */ false); ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(Request.class); verify(httpClient).newCall(argumentCaptor.capture()); Headers requestHeaders = argumentCaptor.getValue().headers(); @@ -313,38 +317,41 @@ public class NetworkingModuleTest { @Test public void testPostJsonContentTypeHeader() throws Exception { OkHttpClient httpClient = mock(OkHttpClient.class); - when(httpClient.newCall(any(Request.class))).thenAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - Call callMock = mock(Call.class); - return callMock; - } - }); + when(httpClient.newCall(any(Request.class))) + .thenAnswer( + new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + Call callMock = mock(Call.class); + return callMock; + } + }); OkHttpClient.Builder clientBuilder = mock(OkHttpClient.Builder.class); when(clientBuilder.build()).thenReturn(httpClient); when(httpClient.newBuilder()).thenReturn(clientBuilder); NetworkingModule networkingModule = - new NetworkingModule(mock(ReactApplicationContext.class), "", httpClient); + new NetworkingModule(mock(ReactApplicationContext.class), "", httpClient); JavaOnlyMap body = new JavaOnlyMap(); body.putString("string", "{ \"key\": \"value\" }"); networkingModule.sendRequest( - "POST", - "http://somedomain/bar", - 0, - JavaOnlyArray.of(JavaOnlyArray.of("Content-Type", "application/json")), - body, - /* responseType */ "text", - /* useIncrementalUpdates*/ true, - /* timeout */ 0, - /* withCredentials */ false); + "POST", + "http://somedomain/bar", + 0, + JavaOnlyArray.of(JavaOnlyArray.of("Content-Type", "application/json")), + body, + /* responseType */ "text", + /* useIncrementalUpdates*/ true, + /* timeout */ 0, + /* withCredentials */ false); ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(Request.class); verify(httpClient).newCall(argumentCaptor.capture()); // Verify okhttp does not append "charset=utf-8" - assertThat(argumentCaptor.getValue().body().contentType().toString()).isEqualTo("application/json"); + assertThat(argumentCaptor.getValue().body().contentType().toString()) + .isEqualTo("application/json"); } @Test @@ -354,13 +361,15 @@ public class NetworkingModuleTest { when(context.getJSModule(any(Class.class))).thenReturn(emitter); OkHttpClient httpClient = mock(OkHttpClient.class); - when(httpClient.newCall(any(Request.class))).thenAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - Call callMock = mock(Call.class); - return callMock; - } - }); + when(httpClient.newCall(any(Request.class))) + .thenAnswer( + new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + Call callMock = mock(Call.class); + return callMock; + } + }); OkHttpClient.Builder clientBuilder = mock(OkHttpClient.Builder.class); when(clientBuilder.build()).thenReturn(httpClient); when(httpClient.newBuilder()).thenReturn(clientBuilder); @@ -372,15 +381,15 @@ public class NetworkingModuleTest { mockEvents(); networkingModule.sendRequest( - "POST", - "http://somedomain/bar", - 0, - JavaOnlyArray.of(JavaOnlyArray.of("Content-Type", "text/plain; charset=utf-16")), - body, - /* responseType */ "text", - /* useIncrementalUpdates*/ true, - /* timeout */ 0, - /* withCredentials */ false); + "POST", + "http://somedomain/bar", + 0, + JavaOnlyArray.of(JavaOnlyArray.of("Content-Type", "text/plain; charset=utf-16")), + body, + /* responseType */ "text", + /* useIncrementalUpdates*/ true, + /* timeout */ 0, + /* withCredentials */ false); ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(Request.class); verify(httpClient).newCall(argumentCaptor.capture()); @@ -397,13 +406,15 @@ public class NetworkingModuleTest { when(context.getJSModule(any(Class.class))).thenReturn(emitter); OkHttpClient httpClient = mock(OkHttpClient.class); - when(httpClient.newCall(any(Request.class))).thenAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - Call callMock = mock(Call.class); - return callMock; - } - }); + when(httpClient.newCall(any(Request.class))) + .thenAnswer( + new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + Call callMock = mock(Call.class); + return callMock; + } + }); OkHttpClient.Builder clientBuilder = mock(OkHttpClient.Builder.class); when(clientBuilder.build()).thenReturn(httpClient); when(httpClient.newBuilder()).thenReturn(clientBuilder); @@ -415,15 +426,15 @@ public class NetworkingModuleTest { mockEvents(); networkingModule.sendRequest( - "POST", - "http://somedomain/bar", - 0, - JavaOnlyArray.of(JavaOnlyArray.of("Content-Type", "invalid")), - body, - /* responseType */ "text", - /* useIncrementalUpdates*/ true, - /* timeout */ 0, - /* withCredentials */ false); + "POST", + "http://somedomain/bar", + 0, + JavaOnlyArray.of(JavaOnlyArray.of("Content-Type", "invalid")), + body, + /* responseType */ "text", + /* useIncrementalUpdates*/ true, + /* timeout */ 0, + /* withCredentials */ false); ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(Request.class); verify(httpClient).newCall(argumentCaptor.capture()); @@ -451,46 +462,45 @@ public class NetworkingModuleTest { bodyPart.putString("string", "value"); bodyPart.putArray( "headers", - JavaOnlyArray.from( - Arrays.asList( - JavaOnlyArray.of("content-disposition", "name")))); + JavaOnlyArray.from(Arrays.asList(JavaOnlyArray.of("content-disposition", "name")))); formData.pushMap(bodyPart); body.putArray("formData", formData); OkHttpClient httpClient = mock(OkHttpClient.class); - when(httpClient.newCall(any(Request.class))).thenAnswer( - new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - Call callMock = mock(Call.class); - return callMock; - } - }); + when(httpClient.newCall(any(Request.class))) + .thenAnswer( + new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + Call callMock = mock(Call.class); + return callMock; + } + }); OkHttpClient.Builder clientBuilder = mock(OkHttpClient.Builder.class); when(clientBuilder.build()).thenReturn(httpClient); when(httpClient.newBuilder()).thenReturn(clientBuilder); NetworkingModule networkingModule = - new NetworkingModule(mock(ReactApplicationContext.class), "", httpClient); + new NetworkingModule(mock(ReactApplicationContext.class), "", httpClient); networkingModule.sendRequest( - "POST", - "http://someurl/uploadFoo", - 0, - new JavaOnlyArray(), - body, - /* responseType */ "text", - /* useIncrementalUpdates*/ true, - /* timeout */ 0, - /* withCredentials */ false); + "POST", + "http://someurl/uploadFoo", + 0, + new JavaOnlyArray(), + body, + /* responseType */ "text", + /* useIncrementalUpdates*/ true, + /* timeout */ 0, + /* withCredentials */ false); // verify url, method, headers ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(Request.class); verify(httpClient).newCall(argumentCaptor.capture()); assertThat(argumentCaptor.getValue().url().toString()).isEqualTo("http://someurl/uploadFoo"); assertThat(argumentCaptor.getValue().method()).isEqualTo("POST"); - assertThat(argumentCaptor.getValue().body().contentType().type()). - isEqualTo(MultipartBody.FORM.type()); - assertThat(argumentCaptor.getValue().body().contentType().subtype()). - isEqualTo(MultipartBody.FORM.subtype()); + assertThat(argumentCaptor.getValue().body().contentType().type()) + .isEqualTo(MultipartBody.FORM.type()); + assertThat(argumentCaptor.getValue().body().contentType().subtype()) + .isEqualTo(MultipartBody.FORM.subtype()); Headers requestHeaders = argumentCaptor.getValue().headers(); assertThat(requestHeaders.size()).isEqualTo(1); } @@ -505,7 +515,8 @@ public class NetworkingModuleTest { when(RequestBodyUtil.createProgressRequest(any(RequestBody.class), any(ProgressListener.class))) .thenCallRealMethod(); - List headers = Arrays.asList( + List headers = + Arrays.asList( JavaOnlyArray.of("Accept", "text/plain"), JavaOnlyArray.of("User-Agent", "React test agent/1.0"), JavaOnlyArray.of("content-type", "multipart/form-data")); @@ -516,46 +527,45 @@ public class NetworkingModuleTest { bodyPart.putString("string", "value"); bodyPart.putArray( "headers", - JavaOnlyArray.from( - Arrays.asList( - JavaOnlyArray.of("content-disposition", "name")))); + JavaOnlyArray.from(Arrays.asList(JavaOnlyArray.of("content-disposition", "name")))); formData.pushMap(bodyPart); body.putArray("formData", formData); OkHttpClient httpClient = mock(OkHttpClient.class); - when(httpClient.newCall(any(Request.class))).thenAnswer( - new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - Call callMock = mock(Call.class); - return callMock; - } - }); + when(httpClient.newCall(any(Request.class))) + .thenAnswer( + new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + Call callMock = mock(Call.class); + return callMock; + } + }); OkHttpClient.Builder clientBuilder = mock(OkHttpClient.Builder.class); when(clientBuilder.build()).thenReturn(httpClient); when(httpClient.newBuilder()).thenReturn(clientBuilder); NetworkingModule networkingModule = - new NetworkingModule(mock(ReactApplicationContext.class), "", httpClient); + new NetworkingModule(mock(ReactApplicationContext.class), "", httpClient); networkingModule.sendRequest( - "POST", - "http://someurl/uploadFoo", - 0, - JavaOnlyArray.from(headers), - body, - /* responseType */ "text", - /* useIncrementalUpdates*/ true, - /* timeout */ 0, - /* withCredentials */ false); + "POST", + "http://someurl/uploadFoo", + 0, + JavaOnlyArray.from(headers), + body, + /* responseType */ "text", + /* useIncrementalUpdates*/ true, + /* timeout */ 0, + /* withCredentials */ false); // verify url, method, headers ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(Request.class); verify(httpClient).newCall(argumentCaptor.capture()); assertThat(argumentCaptor.getValue().url().toString()).isEqualTo("http://someurl/uploadFoo"); assertThat(argumentCaptor.getValue().method()).isEqualTo("POST"); - assertThat(argumentCaptor.getValue().body().contentType().type()). - isEqualTo(MultipartBody.FORM.type()); - assertThat(argumentCaptor.getValue().body().contentType().subtype()). - isEqualTo(MultipartBody.FORM.subtype()); + assertThat(argumentCaptor.getValue().body().contentType().type()) + .isEqualTo(MultipartBody.FORM.type()); + assertThat(argumentCaptor.getValue().body().contentType().subtype()) + .isEqualTo(MultipartBody.FORM.subtype()); Headers requestHeaders = argumentCaptor.getValue().headers(); assertThat(requestHeaders.size()).isEqualTo(3); assertThat(requestHeaders.get("Accept")).isEqualTo("text/plain"); @@ -575,31 +585,36 @@ public class NetworkingModuleTest { when(inputStream.available()).thenReturn("imageUri".length()); final MultipartBody.Builder multipartBuilder = mock(MultipartBody.Builder.class); - PowerMockito.whenNew(MultipartBody.Builder.class).withNoArguments().thenReturn(multipartBuilder); - when(multipartBuilder.setType(any(MediaType.class))).thenAnswer( - new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - return multipartBuilder; - } - }); - when(multipartBuilder.addPart(any(Headers.class), any(RequestBody.class))).thenAnswer( - new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - return multipartBuilder; - } - }); - when(multipartBuilder.build()).thenAnswer( - new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - return mock(MultipartBody.class); - } - }); + PowerMockito.whenNew(MultipartBody.Builder.class) + .withNoArguments() + .thenReturn(multipartBuilder); + when(multipartBuilder.setType(any(MediaType.class))) + .thenAnswer( + new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + return multipartBuilder; + } + }); + when(multipartBuilder.addPart(any(Headers.class), any(RequestBody.class))) + .thenAnswer( + new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + return multipartBuilder; + } + }); + when(multipartBuilder.build()) + .thenAnswer( + new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + return mock(MultipartBody.class); + } + }); - List headers = Arrays.asList( - JavaOnlyArray.of("content-type", "multipart/form-data")); + List headers = + Arrays.asList(JavaOnlyArray.of("content-type", "multipart/form-data")); JavaOnlyMap body = new JavaOnlyMap(); JavaOnlyArray formData = new JavaOnlyArray(); @@ -609,9 +624,7 @@ public class NetworkingModuleTest { bodyPart.putString("string", "locale"); bodyPart.putArray( "headers", - JavaOnlyArray.from( - Arrays.asList( - JavaOnlyArray.of("content-disposition", "user")))); + JavaOnlyArray.from(Arrays.asList(JavaOnlyArray.of("content-disposition", "user")))); formData.pushMap(bodyPart); JavaOnlyMap imageBodyPart = new JavaOnlyMap(); @@ -625,30 +638,31 @@ public class NetworkingModuleTest { formData.pushMap(imageBodyPart); OkHttpClient httpClient = mock(OkHttpClient.class); - when(httpClient.newCall(any(Request.class))).thenAnswer( - new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - Call callMock = mock(Call.class); - return callMock; - } - }); + when(httpClient.newCall(any(Request.class))) + .thenAnswer( + new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + Call callMock = mock(Call.class); + return callMock; + } + }); OkHttpClient.Builder clientBuilder = mock(OkHttpClient.Builder.class); when(clientBuilder.build()).thenReturn(httpClient); when(httpClient.newBuilder()).thenReturn(clientBuilder); NetworkingModule networkingModule = - new NetworkingModule(mock(ReactApplicationContext.class), "", httpClient); + new NetworkingModule(mock(ReactApplicationContext.class), "", httpClient); networkingModule.sendRequest( - "POST", - "http://someurl/uploadFoo", - 0, - JavaOnlyArray.from(headers), - body, - /* responseType */ "text", - /* useIncrementalUpdates*/ true, - /* timeout */ 0, - /* withCredentials */ false); + "POST", + "http://someurl/uploadFoo", + 0, + JavaOnlyArray.from(headers), + body, + /* responseType */ "text", + /* useIncrementalUpdates*/ true, + /* timeout */ 0, + /* withCredentials */ false); // verify RequestBodyPart for image PowerMockito.verifyStatic(times(1)); @@ -661,8 +675,8 @@ public class NetworkingModuleTest { verify(multipartBuilder).setType(MultipartBody.FORM); ArgumentCaptor headersArgumentCaptor = ArgumentCaptor.forClass(Headers.class); ArgumentCaptor bodyArgumentCaptor = ArgumentCaptor.forClass(RequestBody.class); - verify(multipartBuilder, times(2)). - addPart(headersArgumentCaptor.capture(), bodyArgumentCaptor.capture()); + verify(multipartBuilder, times(2)) + .addPart(headersArgumentCaptor.capture(), bodyArgumentCaptor.capture()); List bodyHeaders = headersArgumentCaptor.getAllValues(); assertThat(bodyHeaders.size()).isEqualTo(2); @@ -688,31 +702,33 @@ public class NetworkingModuleTest { } when(httpClient.cookieJar()).thenReturn(mock(CookieJarContainer.class)); - when(httpClient.newCall(any(Request.class))).thenAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - Request request = (Request) invocation.getArguments()[0]; - return calls[(Integer) request.tag() - 1]; - } - }); + when(httpClient.newCall(any(Request.class))) + .thenAnswer( + new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + Request request = (Request) invocation.getArguments()[0]; + return calls[(Integer) request.tag() - 1]; + } + }); OkHttpClient.Builder clientBuilder = mock(OkHttpClient.Builder.class); when(clientBuilder.build()).thenReturn(httpClient); when(httpClient.newBuilder()).thenReturn(clientBuilder); NetworkingModule networkingModule = - new NetworkingModule(mock(ReactApplicationContext.class), "", httpClient); + new NetworkingModule(mock(ReactApplicationContext.class), "", httpClient); networkingModule.initialize(); for (int idx = 0; idx < requests; idx++) { networkingModule.sendRequest( - "GET", - "http://somedomain/foo", - idx + 1, - JavaOnlyArray.of(), - null, - /* responseType */ "text", - /* useIncrementalUpdates*/ true, - /* timeout */ 0, - /* withCredentials */ false); + "GET", + "http://somedomain/foo", + idx + 1, + JavaOnlyArray.of(), + null, + /* responseType */ "text", + /* useIncrementalUpdates*/ true, + /* timeout */ 0, + /* withCredentials */ false); } verify(httpClient, times(3)).newCall(any(Request.class)); @@ -739,30 +755,32 @@ public class NetworkingModuleTest { } when(httpClient.cookieJar()).thenReturn(mock(CookieJarContainer.class)); - when(httpClient.newCall(any(Request.class))).thenAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - Request request = (Request) invocation.getArguments()[0]; - return calls[(Integer) request.tag() - 1]; - } - }); + when(httpClient.newCall(any(Request.class))) + .thenAnswer( + new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + Request request = (Request) invocation.getArguments()[0]; + return calls[(Integer) request.tag() - 1]; + } + }); OkHttpClient.Builder clientBuilder = mock(OkHttpClient.Builder.class); when(clientBuilder.build()).thenReturn(httpClient); when(httpClient.newBuilder()).thenReturn(clientBuilder); NetworkingModule networkingModule = - new NetworkingModule(mock(ReactApplicationContext.class), "", httpClient); + new NetworkingModule(mock(ReactApplicationContext.class), "", httpClient); for (int idx = 0; idx < requests; idx++) { networkingModule.sendRequest( - "GET", - "http://somedomain/foo", - idx + 1, - JavaOnlyArray.of(), - null, - /* responseType */ "text", - /* useIncrementalUpdates*/ true, - /* timeout */ 0, - /* withCredentials */ false); + "GET", + "http://somedomain/foo", + idx + 1, + JavaOnlyArray.of(), + null, + /* responseType */ "text", + /* useIncrementalUpdates*/ true, + /* timeout */ 0, + /* withCredentials */ false); } verify(httpClient, times(3)).newCall(any(Request.class)); diff --git a/ReactAndroid/src/test/java/com/facebook/react/modules/network/ProgressiveStringDecoderTest.java b/ReactAndroid/src/test/java/com/facebook/react/modules/network/ProgressiveStringDecoderTest.java index 9b387cd60ec..399c1958f7e 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/modules/network/ProgressiveStringDecoderTest.java +++ b/ReactAndroid/src/test/java/com/facebook/react/modules/network/ProgressiveStringDecoderTest.java @@ -1,74 +1,75 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ package com.facebook.react.modules.network; import com.facebook.react.common.StandardCharsets; - +import java.nio.charset.Charset; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; -import java.nio.charset.Charset; - - @RunWith(RobolectricTestRunner.class) public class ProgressiveStringDecoderTest { - private static String TEST_DATA_1_BYTE = "Lorem ipsum dolor sit amet, ea ius viris laoreet gloriatur, ea enim illud mel. Ea eligendi erroribus inciderint sea, id nemore sensibus contentiones qui. Eos et nulla abhorreant, noluisse adipiscing reprehendunt an sit. Harum iriure meliore ne nec, clita semper voluptaria at sea. Ius civibus vituperata reprehendunt ut.\n" + - "\n" + - "Sed nisl postea maiorum ex, mea eros verterem ea. Ne usu brute debitis appareat. Ad quem reprimique dissentias duo. Sit an labitur eleifend, illud zril audiam nam ex, epicuri luptatum ne usu. Lorem mundi utinam vix ea.\n" + - "\n" + - "Te eam nominati qualisque. Ut praesent consetetur pro. Soleat vivendum vim ea. Altera dolores eam in. Eum at praesent complectitur. Nec ea inani definitiones, tantas vivendum mei an, mea an ubique omnium latine. Has mundi ocurreret ei, nam ea iuvaret gloriatur.\n" + - "\n" + - "Ad omnes malorum vim, no latine facilisi mel, dicant salutandi conclusionemque ei est. Nam cu partem alterum minimum. Et quo iriure deleniti accommodare, ad impetus perfecto liberavisse pri. Instructior necessitatibus ut mel, ex cum sumo atqui comprehensam, ei nullam oporteat sed. Ius meliore placerat cu.\n" + - "\n" + - "Eum in ferri nobis, eam eu verear facilisis referrentur. Veniam epicuri referrentur at nam. Vel congue diceret fabulas te, ei fabellas temporibus mei. Nemore corrumpit quo ex, et vis soluta reprehendunt. Et eos eripuit atomorum.\n" + - "\n" + - "Eum no novum tantas decore. Indoctum definiebas intellegam ut vel. Cu per ipsum graeco, in nam dico dolore, usu id ludus consulatu. Vis an clita commune, cu quot quaeque cum. In eos semper aperiri. Ne mea probo inermis, no vis audiam volutpat.\n" + - "\n" + - "Cu quaeque scaevola vis. Civibus commune scriptorem vim an, vim ea vocent petentium consequuntur, meis propriae invidunt eam ex. Pro et ponderum recusabo sapientem. Vel legere possim ornatus ne, saepe commodo scaevola an quo. An scaevola repudiandae sed. Eam ei veri nemore.\n" + - "\n" + - "Ullum deleniti cum at. An has soleat docendi, epicuri erroribus inciderint pro ea. Noluisse invidunt splendide quo in, eam odio invenire ea. Eu hinc definiebas scripserit duo, has cu equidem ponderum expetenda, eum vulputate intellegat id. Pri eu natum semper pertinax, ei vel inani aliquip habemus, sit an facer dicam. Et graeci abhorreant contentiones duo, et summo partiendo conclusionemque per.\n" + - "\n" + - "Sed ei etiam iudico abhorreant. Pri an regione fastidii, clita discere eu nec. Torquatos percipitur inciderint eos in, id per prompta blandit. Sit et epicuri deleniti. Per labores corpora no.\n" + - "\n" + - "Quodsi melius facilis pri ei, has adhuc recusabo reprimique ut. Laoreet definitionem cum cu, amet nonumes ut vis, qui ut sonet ancillae. Vim no doctus efficiantur, ancillae indoctum ex sea, vel eu fabulas volumus argumentum. Ex eum aeque commune placerat, nam choro tamquam luptatum et. Ne sea vero idque liberavisse"; + private static String TEST_DATA_1_BYTE = + "Lorem ipsum dolor sit amet, ea ius viris laoreet gloriatur, ea enim illud mel. Ea eligendi erroribus inciderint sea, id nemore sensibus contentiones qui. Eos et nulla abhorreant, noluisse adipiscing reprehendunt an sit. Harum iriure meliore ne nec, clita semper voluptaria at sea. Ius civibus vituperata reprehendunt ut.\n" + + "\n" + + "Sed nisl postea maiorum ex, mea eros verterem ea. Ne usu brute debitis appareat. Ad quem reprimique dissentias duo. Sit an labitur eleifend, illud zril audiam nam ex, epicuri luptatum ne usu. Lorem mundi utinam vix ea.\n" + + "\n" + + "Te eam nominati qualisque. Ut praesent consetetur pro. Soleat vivendum vim ea. Altera dolores eam in. Eum at praesent complectitur. Nec ea inani definitiones, tantas vivendum mei an, mea an ubique omnium latine. Has mundi ocurreret ei, nam ea iuvaret gloriatur.\n" + + "\n" + + "Ad omnes malorum vim, no latine facilisi mel, dicant salutandi conclusionemque ei est. Nam cu partem alterum minimum. Et quo iriure deleniti accommodare, ad impetus perfecto liberavisse pri. Instructior necessitatibus ut mel, ex cum sumo atqui comprehensam, ei nullam oporteat sed. Ius meliore placerat cu.\n" + + "\n" + + "Eum in ferri nobis, eam eu verear facilisis referrentur. Veniam epicuri referrentur at nam. Vel congue diceret fabulas te, ei fabellas temporibus mei. Nemore corrumpit quo ex, et vis soluta reprehendunt. Et eos eripuit atomorum.\n" + + "\n" + + "Eum no novum tantas decore. Indoctum definiebas intellegam ut vel. Cu per ipsum graeco, in nam dico dolore, usu id ludus consulatu. Vis an clita commune, cu quot quaeque cum. In eos semper aperiri. Ne mea probo inermis, no vis audiam volutpat.\n" + + "\n" + + "Cu quaeque scaevola vis. Civibus commune scriptorem vim an, vim ea vocent petentium consequuntur, meis propriae invidunt eam ex. Pro et ponderum recusabo sapientem. Vel legere possim ornatus ne, saepe commodo scaevola an quo. An scaevola repudiandae sed. Eam ei veri nemore.\n" + + "\n" + + "Ullum deleniti cum at. An has soleat docendi, epicuri erroribus inciderint pro ea. Noluisse invidunt splendide quo in, eam odio invenire ea. Eu hinc definiebas scripserit duo, has cu equidem ponderum expetenda, eum vulputate intellegat id. Pri eu natum semper pertinax, ei vel inani aliquip habemus, sit an facer dicam. Et graeci abhorreant contentiones duo, et summo partiendo conclusionemque per.\n" + + "\n" + + "Sed ei etiam iudico abhorreant. Pri an regione fastidii, clita discere eu nec. Torquatos percipitur inciderint eos in, id per prompta blandit. Sit et epicuri deleniti. Per labores corpora no.\n" + + "\n" + + "Quodsi melius facilis pri ei, has adhuc recusabo reprimique ut. Laoreet definitionem cum cu, amet nonumes ut vis, qui ut sonet ancillae. Vim no doctus efficiantur, ancillae indoctum ex sea, vel eu fabulas volumus argumentum. Ex eum aeque commune placerat, nam choro tamquam luptatum et. Ne sea vero idque liberavisse"; - private static String TEST_DATA_2_BYTES = "Лорем ипсум долор сит амет, доминг дисцере ад вих, велит игнота ратионибус мел цу. Не вирис малорум яуаеяуе хас, еу либрис доцтус хис. Моллис садипсцинг ан цум, семпер молестие репрехендунт усу те. Цасе аетерно оффендит ан еос. При ан толлит опортере оцурререт, ан яуот мутат трацтатос вих.\n" + - "\n" + - "Нец фалли харум ратионибус еа. Магна адмодум ат нам, яуи еа рецусабо мандамус, аццусам цонсеяуунтур цу хис. Импедит цотидиеяуе улламцорпер еа мел, усу ет долорес аргументум. Веро торяуатос ех нам, цибо либерависсе ест еи. Вис долор омниум сплендиде ад, велит рецусабо цонсететур иус цу.\n" + - "\n" + - "Еи дуо меис атоморум сигниферумяуе, аугуе аццусам мел ет. Ут ностро легендос хонестатис пер, ут яуас мовет сеа. Меа цу продессет аппеллантур. Вис еа яуод оффендит, дебет видерер ет нам.\n" + - "\n" + - "Еам еа дебитис иудицабит, не хас иллуд цивибус. Усу ет алии уллум утамур. Поссит цонституто те яуи, хас ет лаудем аудире, нам еи епицури салутанди. Лудус делицатиссими цум еу, либер адиписцинг еи нец. Ид ерипуит лобортис антиопам хис, санцтус елигенди неглегентур сед ут, вел сентентиае инструцтиор еи. Ан про унум яуалисяуе.\n" + - "\n" + - "Ат еррор алтера сит, пер еу яуот номинави. Пертинах репудиаре цум еу. Еа фуиссет антиопам вим, пробатус реферрентур ут иус. Еум ад модус утрояуе диспутандо.\n" + - "\n" + - "Ехерци бландит ут меа. Солет импедит сед ад. Дуо порро тимеам аудире не, алии ерант номинави цу нец, сит ферри веритус адиписци те. Те меи синт адверсариум, ад феугаит инвидунт луцилиус сед, дицунт нумяуам нам те. Еум дицант елеифенд цонсецтетуер ет, суммо вереар епицуреи не про. Не лудус сцрипта опортере вим, еи дуо идяуе алияуам сигниферумяуе. Цум еу лабитур инвенире, про ессе губергрен темпорибус еи, ад хис минимум пертинах.\n" + - "\n" + - "Дуо ад вери евертитур интеллегат, демоцритум еффициенди дуо ет. Нец но доценди демоцритум сцрипторем, витуперата цонституам нецесситатибус ут вим. Яуи виде санцтус мандамус ан, нонумес принципес вел ат, ех дуо инани нулла. Петентиум маиестатис еам ин, те ерант дебитис еурипидис вис. Но вел антиопам цотидиеяуе еффициантур, сеа еи нибх нонумы инцидеринт.\n" + - "\n" + - "Одио омнес но яуо, популо ноструд иус ад. Инани хонестатис но вис. Хис еу лудус партем персиус, пурто малис витуперата при ан, еи елаборарет ассуеверит вим. Цу бруте утинам тинцидунт вих, цум ад дицтас лобортис лаборамус. Нец хабемус рецусабо ат, ех фацилис денияуе ест. При те велит алияуам аццусамус, юсто утамур антиопам но нам.\n" + - "\n" + - "Про не еррем иудицо мелиоре, еи цибо ерудити санцтус хас. Яуод еяуидем еу вис, вих яуидам легимус ад, ид сеа солум легере мандамус. Аеяуе детрахит ех иус, суас вертерем еум цу. Еи вим алиа ехерци пхаедрум, хас не лаборес цоррумпит. Ат граеци сцрипта вим.\n" + - "\n" + - "Иус ат менандри персеяуерис. Про модус дицта еу, ин граеци доценди фиерент при, еи хас аугуе мандамус дефинитионем. Ет путент интерпретарис сит, перицула сентентиае ат ест. При ут сумо видит волуптатибус, нобис деленити еа."; - private static String TEST_DATA_3_BYTES = "案のづよド捕毎エオ文疑ろめた今宮レ秋像とが供持属ょー真場中ホサヒ不箱らご著質ーぼンろ保6年読さ系蔵べるル緩参フシセタ鮮県フずッ歳民ナセ楽飲匹恒桜ぱ。要電ネソメ嘉負向ス援中ぜく界党フネ属平ぎ象越容レ書95争効99争効7翌テ売約わこよッ紙点発事9入そさ補綱のラず他亭匠ぞ。\n" + - "\n" + - "天レ供内ソ愛7読でぽせ回書ほごしな浅月企設潟せぐり裂個ホヌヤ局題制エ柏央ざぽ。外くにさ下格か終所あ硬当ワ着少選とけリへ康件終にぎ季規らおず給測トユテ考毎サトス事版にーご文8忙チ深暮タヲムラ度6応しぞぎぐ装速て続際ぞ発准揮包孤てい。制はたちき合南む乙甲ゅさと捕4球任条こでン頭広セスモウ月夜エス面陽ヨネ力京ウリ紙聞ト印2火映ラ基頭スフ点愛伎協ねド。\n" + - "\n" + - "属と共代みむもず以監すい者新ス田政家ヱス使校音刑トホ則上ゅぐ一未ヌ意40芸標んは学必強ゅ帝歯没牧具もか。58新イシレ正米ニユ負皇っぐせの必容キソタコ公3容ーつぶべ年然検ざ整賞ニチ注興ぐ放約えあ野夜磨やゃフよ。柳ソシアテ申1科ル舗紀深むぜ競供とび室全ハネ測高エラク権暮ヲクオト館暮ヌ黒杯クリぴぽ火竹ねる種4帰替やあい北問クルゃン登壌粉つどべ。"; + private static String TEST_DATA_2_BYTES = + "Лорем ипсум долор сит амет, доминг дисцере ад вих, велит игнота ратионибус мел цу. Не вирис малорум яуаеяуе хас, еу либрис доцтус хис. Моллис садипсцинг ан цум, семпер молестие репрехендунт усу те. Цасе аетерно оффендит ан еос. При ан толлит опортере оцурререт, ан яуот мутат трацтатос вих.\n" + + "\n" + + "Нец фалли харум ратионибус еа. Магна адмодум ат нам, яуи еа рецусабо мандамус, аццусам цонсеяуунтур цу хис. Импедит цотидиеяуе улламцорпер еа мел, усу ет долорес аргументум. Веро торяуатос ех нам, цибо либерависсе ест еи. Вис долор омниум сплендиде ад, велит рецусабо цонсететур иус цу.\n" + + "\n" + + "Еи дуо меис атоморум сигниферумяуе, аугуе аццусам мел ет. Ут ностро легендос хонестатис пер, ут яуас мовет сеа. Меа цу продессет аппеллантур. Вис еа яуод оффендит, дебет видерер ет нам.\n" + + "\n" + + "Еам еа дебитис иудицабит, не хас иллуд цивибус. Усу ет алии уллум утамур. Поссит цонституто те яуи, хас ет лаудем аудире, нам еи епицури салутанди. Лудус делицатиссими цум еу, либер адиписцинг еи нец. Ид ерипуит лобортис антиопам хис, санцтус елигенди неглегентур сед ут, вел сентентиае инструцтиор еи. Ан про унум яуалисяуе.\n" + + "\n" + + "Ат еррор алтера сит, пер еу яуот номинави. Пертинах репудиаре цум еу. Еа фуиссет антиопам вим, пробатус реферрентур ут иус. Еум ад модус утрояуе диспутандо.\n" + + "\n" + + "Ехерци бландит ут меа. Солет импедит сед ад. Дуо порро тимеам аудире не, алии ерант номинави цу нец, сит ферри веритус адиписци те. Те меи синт адверсариум, ад феугаит инвидунт луцилиус сед, дицунт нумяуам нам те. Еум дицант елеифенд цонсецтетуер ет, суммо вереар епицуреи не про. Не лудус сцрипта опортере вим, еи дуо идяуе алияуам сигниферумяуе. Цум еу лабитур инвенире, про ессе губергрен темпорибус еи, ад хис минимум пертинах.\n" + + "\n" + + "Дуо ад вери евертитур интеллегат, демоцритум еффициенди дуо ет. Нец но доценди демоцритум сцрипторем, витуперата цонституам нецесситатибус ут вим. Яуи виде санцтус мандамус ан, нонумес принципес вел ат, ех дуо инани нулла. Петентиум маиестатис еам ин, те ерант дебитис еурипидис вис. Но вел антиопам цотидиеяуе еффициантур, сеа еи нибх нонумы инцидеринт.\n" + + "\n" + + "Одио омнес но яуо, популо ноструд иус ад. Инани хонестатис но вис. Хис еу лудус партем персиус, пурто малис витуперата при ан, еи елаборарет ассуеверит вим. Цу бруте утинам тинцидунт вих, цум ад дицтас лобортис лаборамус. Нец хабемус рецусабо ат, ех фацилис денияуе ест. При те велит алияуам аццусамус, юсто утамур антиопам но нам.\n" + + "\n" + + "Про не еррем иудицо мелиоре, еи цибо ерудити санцтус хас. Яуод еяуидем еу вис, вих яуидам легимус ад, ид сеа солум легере мандамус. Аеяуе детрахит ех иус, суас вертерем еум цу. Еи вим алиа ехерци пхаедрум, хас не лаборес цоррумпит. Ат граеци сцрипта вим.\n" + + "\n" + + "Иус ат менандри персеяуерис. Про модус дицта еу, ин граеци доценди фиерент при, еи хас аугуе мандамус дефинитионем. Ет путент интерпретарис сит, перицула сентентиае ат ест. При ут сумо видит волуптатибус, нобис деленити еа."; + private static String TEST_DATA_3_BYTES = + "案のづよド捕毎エオ文疑ろめた今宮レ秋像とが供持属ょー真場中ホサヒ不箱らご著質ーぼンろ保6年読さ系蔵べるル緩参フシセタ鮮県フずッ歳民ナセ楽飲匹恒桜ぱ。要電ネソメ嘉負向ス援中ぜく界党フネ属平ぎ象越容レ書95争効99争効7翌テ売約わこよッ紙点発事9入そさ補綱のラず他亭匠ぞ。\n" + + "\n" + + "天レ供内ソ愛7読でぽせ回書ほごしな浅月企設潟せぐり裂個ホヌヤ局題制エ柏央ざぽ。外くにさ下格か終所あ硬当ワ着少選とけリへ康件終にぎ季規らおず給測トユテ考毎サトス事版にーご文8忙チ深暮タヲムラ度6応しぞぎぐ装速て続際ぞ発准揮包孤てい。制はたちき合南む乙甲ゅさと捕4球任条こでン頭広セスモウ月夜エス面陽ヨネ力京ウリ紙聞ト印2火映ラ基頭スフ点愛伎協ねド。\n" + + "\n" + + "属と共代みむもず以監すい者新ス田政家ヱス使校音刑トホ則上ゅぐ一未ヌ意40芸標んは学必強ゅ帝歯没牧具もか。58新イシレ正米ニユ負皇っぐせの必容キソタコ公3容ーつぶべ年然検ざ整賞ニチ注興ぐ放約えあ野夜磨やゃフよ。柳ソシアテ申1科ル舗紀深むぜ競供とび室全ハネ測高エラク権暮ヲクオト館暮ヌ黒杯クリぴぽ火竹ねる種4帰替やあい北問クルゃン登壌粉つどべ。"; - private static final String TEST_DATA_4_BYTES ="\uD800\uDE55\uD800\uDE55\uD800\uDE55 \uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE55" + - "\uD800\uDE55\uD800\uDE55\uD800\uDE55 \uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80" + - "\uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80" + - "\uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80" + - "\uD800\uDE80\uD800\uDE80\uD800\uDE80"; + private static final String TEST_DATA_4_BYTES = + "\uD800\uDE55\uD800\uDE55\uD800\uDE55 \uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE55" + + "\uD800\uDE55\uD800\uDE55\uD800\uDE55 \uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80" + + "\uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80" + + "\uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE55\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80\uD800\uDE80" + + "\uD800\uDE80\uD800\uDE80\uD800\uDE80"; @Test public void testUTF8SingleByteSymbols() { @@ -91,23 +92,23 @@ public class ProgressiveStringDecoderTest { } @Test - public void testUTF16LEStandard() throws Exception { + public void testUTF16LEStandard() throws Exception { chunkString(TEST_DATA_3_BYTES, StandardCharsets.UTF_16LE, 47); } @Test - public void testUTF16LESurrogates() throws Exception { + public void testUTF16LESurrogates() throws Exception { // 4 bytes UTF-8 symbols are encoded as two 2 byte surrogate symbols in UTF-16 chunkString(TEST_DATA_4_BYTES, StandardCharsets.UTF_16LE, 47); } @Test - public void testUTF16BEStandard() throws Exception { + public void testUTF16BEStandard() throws Exception { chunkString(TEST_DATA_3_BYTES, StandardCharsets.UTF_16BE, 47); } @Test - public void testUTF16BESurrogates() throws Exception { + public void testUTF16BESurrogates() throws Exception { // 4 bytes UTF-8 symbols are encoded as two 2 byte surrogate symbols in UTF-16 chunkString(TEST_DATA_4_BYTES, StandardCharsets.UTF_16BE, 47); } @@ -119,15 +120,15 @@ public class ProgressiveStringDecoderTest { } private void chunkString(String originalString, Charset charset, int chunkSize) { - byte data [] = originalString.getBytes(charset); + byte data[] = originalString.getBytes(charset); StringBuilder builder = new StringBuilder(); ProgressiveStringDecoder collector = new ProgressiveStringDecoder(charset); byte[] buffer = new byte[chunkSize]; - for (int i = 0; i < data.length; i+= chunkSize) { + for (int i = 0; i < data.length; i += chunkSize) { int bytesRead = Math.min(chunkSize, data.length - i); - System.arraycopy(data, i, buffer, 0, bytesRead ); - builder.append(collector.decodeNext(buffer, bytesRead )); + System.arraycopy(data, i, buffer, 0, bytesRead); + builder.append(collector.decodeNext(buffer, bytesRead)); } String actualString = builder.toString(); diff --git a/ReactAndroid/src/test/java/com/facebook/react/modules/network/ReactCookieJarContainerTest.java b/ReactAndroid/src/test/java/com/facebook/react/modules/network/ReactCookieJarContainerTest.java index 7c8f84d7249..55978ea3950 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/modules/network/ReactCookieJarContainerTest.java +++ b/ReactAndroid/src/test/java/com/facebook/react/modules/network/ReactCookieJarContainerTest.java @@ -1,40 +1,31 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.network; -import com.facebook.react.modules.network.ReactCookieJarContainer; +import static org.fest.assertions.api.Assertions.assertThat; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; import okhttp3.Cookie; import okhttp3.CookieJar; import okhttp3.HttpUrl; -import java.util.List; -import java.util.ArrayList; - import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.robolectric.RobolectricTestRunner; -import static org.fest.assertions.api.Assertions.assertThat; -import static org.mockito.Mockito.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -/** - * Tests for {@link NetworkingModule}. - */ -@PrepareForTest({ - ReactCookieJarContainer.class -}) +/** Tests for {@link NetworkingModule}. */ +@PrepareForTest({ReactCookieJarContainer.class}) @RunWith(RobolectricTestRunner.class) @PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "androidx.*", "android.*"}) - public class ReactCookieJarContainerTest { @Test @@ -57,12 +48,7 @@ public class ReactCookieJarContainerTest { CookieJar cookieJar = mock(CookieJar.class); jarContainer.setCookieJar(cookieJar); List cookies = new ArrayList<>(); - cookies.add(new Cookie.Builder() - .name("valid") - .value("valid value") - .domain("domain") - .build() - ); + cookies.add(new Cookie.Builder().name("valid").value("valid value").domain("domain").build()); when(cookieJar.loadForRequest(any(HttpUrl.class))).thenReturn(cookies); assertThat(jarContainer.loadForRequest(any(HttpUrl.class)).size()).isEqualTo(1); } @@ -73,12 +59,7 @@ public class ReactCookieJarContainerTest { CookieJar cookieJar = mock(CookieJar.class); jarContainer.setCookieJar(cookieJar); List cookies = new ArrayList<>(); - cookies.add(new Cookie.Builder() - .name("valid") - .value("înválíd välūė") - .domain("domain") - .build() - ); + cookies.add(new Cookie.Builder().name("valid").value("înválíd välūė").domain("domain").build()); when(cookieJar.loadForRequest(any(HttpUrl.class))).thenReturn(cookies); assertThat(jarContainer.loadForRequest(any(HttpUrl.class)).size()).isEqualTo(0); } diff --git a/ReactAndroid/src/test/java/com/facebook/react/modules/share/ShareModuleTest.java b/ReactAndroid/src/test/java/com/facebook/react/modules/share/ShareModuleTest.java index 63b48e89fca..2870847d31b 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/modules/share/ShareModuleTest.java +++ b/ReactAndroid/src/test/java/com/facebook/react/modules/share/ShareModuleTest.java @@ -1,21 +1,23 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.share; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + import android.app.Activity; import android.content.Intent; - import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.JavaOnlyMap; import com.facebook.react.bridge.Promise; import com.facebook.react.bridge.ReactTestHelper; import com.facebook.react.bridge.WritableMap; - +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import org.junit.After; import org.junit.Before; import org.junit.Rule; @@ -33,12 +35,6 @@ import org.robolectric.RuntimeEnvironment; import org.robolectric.internal.ShadowExtractor; import org.robolectric.shadows.ShadowApplication; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - @PrepareForTest({Arguments.class}) @RunWith(RobolectricTestRunner.class) @PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "androidx.*", "android.*"}) @@ -47,20 +43,19 @@ public class ShareModuleTest { private Activity mActivity; private ShareModule mShareModule; - @Rule - public PowerMockRule rule = new PowerMockRule(); + @Rule public PowerMockRule rule = new PowerMockRule(); @Before public void prepareModules() throws Exception { PowerMockito.mockStatic(Arguments.class); - Mockito - .when(Arguments.createMap()) - .thenAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - return new JavaOnlyMap(); - } - }); + Mockito.when(Arguments.createMap()) + .thenAnswer( + new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + return new JavaOnlyMap(); + } + }); mShareModule = new ShareModule(ReactTestHelper.createCatalystContextForTest()); } @@ -86,33 +81,17 @@ public class ShareModuleTest { mShareModule.share(content, dialogTitle, promise); final Intent chooserIntent = - ((ShadowApplication) ShadowExtractor.extract(RuntimeEnvironment.application)).getNextStartedActivity(); + ((ShadowApplication) ShadowExtractor.extract(RuntimeEnvironment.application)) + .getNextStartedActivity(); assertNotNull("Dialog was not displayed", chooserIntent); assertEquals(Intent.ACTION_CHOOSER, chooserIntent.getAction()); - assertEquals( - dialogTitle, - chooserIntent - .getExtras() - .get(Intent.EXTRA_TITLE) - ); + assertEquals(dialogTitle, chooserIntent.getExtras().get(Intent.EXTRA_TITLE)); - final Intent contentIntent = (Intent) chooserIntent - .getExtras() - .get(Intent.EXTRA_INTENT); + final Intent contentIntent = (Intent) chooserIntent.getExtras().get(Intent.EXTRA_INTENT); assertNotNull("Intent was not built correctly", contentIntent); assertEquals(Intent.ACTION_SEND, contentIntent.getAction()); - assertEquals( - title, - contentIntent - .getExtras() - .get(Intent.EXTRA_SUBJECT) - ); - assertEquals( - message, - contentIntent - .getExtras() - .get(Intent.EXTRA_TEXT) - ); + assertEquals(title, contentIntent.getExtras().get(Intent.EXTRA_SUBJECT)); + assertEquals(message, contentIntent.getExtras().get(Intent.EXTRA_TEXT)); assertEquals(1, promise.getResolved()); } @@ -129,7 +108,7 @@ public class ShareModuleTest { assertEquals(ShareModule.ERROR_INVALID_CONTENT, promise.getErrorCode()); } - final static class SimplePromise implements Promise { + static final class SimplePromise implements Promise { private static final String ERROR_DEFAULT_CODE = "EUNSPECIFIED"; private static final String ERROR_DEFAULT_MESSAGE = "Error not specified."; @@ -167,42 +146,42 @@ public class ShareModuleTest { @Override public void reject(String code, String message) { - reject(code, message, /*Throwable*/null, /*WritableMap*/null); + reject(code, message, /*Throwable*/ null, /*WritableMap*/ null); } @Override public void reject(String code, Throwable throwable) { - reject(code, /*Message*/null, throwable, /*WritableMap*/null); + reject(code, /*Message*/ null, throwable, /*WritableMap*/ null); } @Override public void reject(String code, String message, Throwable throwable) { - reject(code, message, throwable, /*WritableMap*/null); + reject(code, message, throwable, /*WritableMap*/ null); } @Override public void reject(Throwable throwable) { - reject(/*Code*/null, /*Message*/null, throwable, /*WritableMap*/null); + reject(/*Code*/ null, /*Message*/ null, throwable, /*WritableMap*/ null); } @Override public void reject(Throwable throwable, WritableMap userInfo) { - reject(/*Code*/null, /*Message*/null, throwable, userInfo); + reject(/*Code*/ null, /*Message*/ null, throwable, userInfo); } @Override public void reject(String code, @Nonnull WritableMap userInfo) { - reject(code, /*Message*/null, /*Throwable*/null, userInfo); + reject(code, /*Message*/ null, /*Throwable*/ null, userInfo); } @Override public void reject(String code, Throwable throwable, WritableMap userInfo) { - reject(code, /*Message*/null, throwable, userInfo); + reject(code, /*Message*/ null, throwable, userInfo); } @Override public void reject(String code, String message, @Nonnull WritableMap userInfo) { - reject(code, message, /*Throwable*/null, userInfo); + reject(code, message, /*Throwable*/ null, userInfo); } @Override @@ -210,8 +189,7 @@ public class ShareModuleTest { String code, String message, @Nullable Throwable throwable, - @Nullable WritableMap userInfo - ) { + @Nullable WritableMap userInfo) { mRejected++; if (code == null) { @@ -232,7 +210,7 @@ public class ShareModuleTest { @Override @Deprecated public void reject(String message) { - reject(/*Code*/null, message, /*Throwable*/null, /*WritableMap*/null); + reject(/*Code*/ null, message, /*Throwable*/ null, /*WritableMap*/ null); } } } diff --git a/ReactAndroid/src/test/java/com/facebook/react/modules/storage/AsyncStorageModuleTest.java b/ReactAndroid/src/test/java/com/facebook/react/modules/storage/AsyncStorageModuleTest.java index cb9683b65e1..d64fce1c6b7 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/modules/storage/AsyncStorageModuleTest.java +++ b/ReactAndroid/src/test/java/com/facebook/react/modules/storage/AsyncStorageModuleTest.java @@ -1,32 +1,22 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.storage; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.Executor; - -import android.app.Activity; -import android.content.Context; -import android.content.ContextWrapper; -import android.os.AsyncTask; +import static org.fest.assertions.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.Callback; -import com.facebook.react.bridge.GuardedAsyncTask; -import com.facebook.react.bridge.ReactApplicationContext; -import com.facebook.react.bridge.ReactTestHelper; import com.facebook.react.bridge.JavaOnlyArray; import com.facebook.react.bridge.JavaOnlyMap; -import com.facebook.react.modules.storage.AsyncStorageModule; -import com.facebook.react.modules.storage.ReactDatabaseSupplier; - +import com.facebook.react.bridge.ReactTestHelper; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; import org.json.JSONArray; import org.json.JSONObject; import org.junit.After; @@ -34,26 +24,20 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.mockito.verification.VerificationMode; import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.rule.PowerMockRule; -import org.robolectric.RuntimeEnvironment; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; +import org.robolectric.RuntimeEnvironment; import org.robolectric.util.concurrent.RoboExecutorService; -import static org.mockito.Mockito.mock; -import static org.fest.assertions.api.Assertions.assertThat; - -/** - * Tests for {@link AsyncStorageModule}. - */ +/** Tests for {@link com.facebook.react.modules.storage.AsyncStorageModule}. */ @PrepareForTest({Arguments.class}) @PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "androidx.*", "android.*", "org.json.*"}) @RunWith(RobolectricTestRunner.class) @@ -62,33 +46,33 @@ public class AsyncStorageModuleTest { private AsyncStorageModule mStorage; private JavaOnlyArray mEmptyArray; - @Rule - public PowerMockRule rule = new PowerMockRule(); + @Rule public PowerMockRule rule = new PowerMockRule(); @Before public void prepareModules() { PowerMockito.mockStatic(Arguments.class); - Mockito.when(Arguments.createArray()).thenAnswer( - new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - return new JavaOnlyArray(); - } - }); + Mockito.when(Arguments.createArray()) + .thenAnswer( + new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + return new JavaOnlyArray(); + } + }); - Mockito.when(Arguments.createMap()).thenAnswer( - new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - return new JavaOnlyMap(); - } - }); + Mockito.when(Arguments.createMap()) + .thenAnswer( + new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + return new JavaOnlyMap(); + } + }); // don't use Robolectric before initializing mocks - mStorage = new AsyncStorageModule( - ReactTestHelper.createCatalystContextForTest(), - new RoboExecutorService() - ); + mStorage = + new AsyncStorageModule( + ReactTestHelper.createCatalystContextForTest(), new RoboExecutorService()); mEmptyArray = new JavaOnlyArray(); } @@ -276,7 +260,8 @@ public class AsyncStorageModuleTest { keys.pushString("key" + i); } mStorage.multiGet( - keys, new Callback() { + keys, + new Callback() { @Override public void invoke(Object... args) { assertThat(args.length).isEqualTo(2); diff --git a/ReactAndroid/src/test/java/com/facebook/react/modules/timing/TimingModuleTest.java b/ReactAndroid/src/test/java/com/facebook/react/modules/timing/TimingModuleTest.java index ef4c60fa0ea..94d92baeb0f 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/modules/timing/TimingModuleTest.java +++ b/ReactAndroid/src/test/java/com/facebook/react/modules/timing/TimingModuleTest.java @@ -1,23 +1,23 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.modules.timing; +import static org.mockito.Mockito.*; + import com.facebook.react.bridge.Arguments; -import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.CatalystInstance; import com.facebook.react.bridge.JavaOnlyArray; -import com.facebook.react.devsupport.interfaces.DevSupportManager; +import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.common.SystemClock; +import com.facebook.react.devsupport.interfaces.DevSupportManager; import com.facebook.react.modules.core.ChoreographerCompat; import com.facebook.react.modules.core.JSTimers; import com.facebook.react.modules.core.ReactChoreographer; import com.facebook.react.modules.core.Timing; - import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -25,16 +25,12 @@ import org.junit.runner.RunWith; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.rule.PowerMockRule; import org.robolectric.RobolectricTestRunner; -import static org.mockito.Mockito.*; - -/** - * Tests for {@link Timing}. - */ +/** Tests for {@link Timing}. */ // DISABLED, BROKEN https://circleci.com/gh/facebook/react-native/12068 // t=13905097 @PrepareForTest({Arguments.class, SystemClock.class, ReactChoreographer.class}) @@ -51,19 +47,19 @@ public class TimingModuleTest { private long mCurrentTimeNs; private JSTimers mJSTimersMock; - @Rule - public PowerMockRule rule = new PowerMockRule(); + @Rule public PowerMockRule rule = new PowerMockRule(); @Before public void prepareModules() { PowerMockito.mockStatic(Arguments.class); - when(Arguments.createArray()).thenAnswer( - new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - return new JavaOnlyArray(); - } - }); + when(Arguments.createArray()) + .thenAnswer( + new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + return new JavaOnlyArray(); + } + }); PowerMockito.mockStatic(SystemClock.class); when(SystemClock.uptimeMillis()).thenReturn(mCurrentTimeNs / 1000000); @@ -83,35 +79,40 @@ public class TimingModuleTest { mIdlePostFrameCallbackHandler = new PostFrameIdleCallbackHandler(); doAnswer(mPostFrameCallbackHandler) - .when(mReactChoreographerMock) - .postFrameCallback( - eq(ReactChoreographer.CallbackType.TIMERS_EVENTS), - any(ChoreographerCompat.FrameCallback.class)); + .when(mReactChoreographerMock) + .postFrameCallback( + eq(ReactChoreographer.CallbackType.TIMERS_EVENTS), + any(ChoreographerCompat.FrameCallback.class)); doAnswer(mIdlePostFrameCallbackHandler) - .when(mReactChoreographerMock) - .postFrameCallback( - eq(ReactChoreographer.CallbackType.IDLE_EVENT), - any(ChoreographerCompat.FrameCallback.class)); + .when(mReactChoreographerMock) + .postFrameCallback( + eq(ReactChoreographer.CallbackType.IDLE_EVENT), + any(ChoreographerCompat.FrameCallback.class)); mTiming = new Timing(reactContext, mock(DevSupportManager.class)); mJSTimersMock = mock(JSTimers.class); when(reactContext.getJSModule(JSTimers.class)).thenReturn(mJSTimersMock); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ((Runnable) invocation.getArguments()[0]).run(); - return null; - } - }).when(reactContext).runOnJSQueueThread(any(Runnable.class)); + doAnswer( + new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + ((Runnable) invocation.getArguments()[0]).run(); + return null; + } + }) + .when(reactContext) + .runOnJSQueueThread(any(Runnable.class)); mTiming.initialize(); } private void stepChoreographerFrame() { - ChoreographerCompat.FrameCallback callback = mPostFrameCallbackHandler.getAndResetFrameCallback(); - ChoreographerCompat.FrameCallback idleCallback = mIdlePostFrameCallbackHandler.getAndResetFrameCallback(); + ChoreographerCompat.FrameCallback callback = + mPostFrameCallbackHandler.getAndResetFrameCallback(); + ChoreographerCompat.FrameCallback idleCallback = + mIdlePostFrameCallbackHandler.getAndResetFrameCallback(); mCurrentTimeNs += FRAME_TIME_NS; when(SystemClock.uptimeMillis()).thenReturn(mCurrentTimeNs / 1000000); diff --git a/ReactAndroid/src/test/java/com/facebook/react/packagerconnection/JSPackagerClientTest.java b/ReactAndroid/src/test/java/com/facebook/react/packagerconnection/JSPackagerClientTest.java index 88f18c00467..4b63297113d 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/packagerconnection/JSPackagerClientTest.java +++ b/ReactAndroid/src/test/java/com/facebook/react/packagerconnection/JSPackagerClientTest.java @@ -1,33 +1,27 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.packagerconnection; +import static org.mockito.Mockito.*; + import com.facebook.react.packagerconnection.ReconnectingWebSocket.ConnectionCallback; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; - import java.io.IOException; import java.util.HashMap; import java.util.Map; - import okio.ByteString; - -import static org.mockito.Mockito.*; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; @RunWith(RobolectricTestRunner.class) public class JSPackagerClientTest { - private static Map createRH( - String action, RequestHandler handler) { - Map m = - new HashMap(); + private static Map createRH(String action, RequestHandler handler) { + Map m = new HashMap(); m.put(action, handler); return m; } @@ -44,7 +38,8 @@ public class JSPackagerClientTest { @Test public void test_onMessage_ShouldTriggerNotification() throws IOException { RequestHandler handler = mock(RequestHandler.class); - final JSPackagerClient client = new JSPackagerClient("test_client", mSettings, createRH("methodValue", handler)); + final JSPackagerClient client = + new JSPackagerClient("test_client", mSettings, createRH("methodValue", handler)); client.onMessage("{\"version\": 2, \"method\": \"methodValue\", \"params\": \"paramsValue\"}"); verify(handler).onNotification(eq("paramsValue")); @@ -54,9 +49,11 @@ public class JSPackagerClientTest { @Test public void test_onMessage_ShouldTriggerRequest() throws IOException { RequestHandler handler = mock(RequestHandler.class); - final JSPackagerClient client = new JSPackagerClient("test_client", mSettings, createRH("methodValue", handler)); + final JSPackagerClient client = + new JSPackagerClient("test_client", mSettings, createRH("methodValue", handler)); - client.onMessage("{\"version\": 2, \"id\": \"idValue\", \"method\": \"methodValue\", \"params\": \"paramsValue\"}"); + client.onMessage( + "{\"version\": 2, \"id\": \"idValue\", \"method\": \"methodValue\", \"params\": \"paramsValue\"}"); verify(handler, never()).onNotification(any()); verify(handler).onRequest(eq("paramsValue"), any(Responder.class)); } @@ -64,7 +61,8 @@ public class JSPackagerClientTest { @Test public void test_onMessage_WithoutParams_ShouldTriggerNotification() throws IOException { RequestHandler handler = mock(RequestHandler.class); - final JSPackagerClient client = new JSPackagerClient("test_client", mSettings, createRH("methodValue", handler)); + final JSPackagerClient client = + new JSPackagerClient("test_client", mSettings, createRH("methodValue", handler)); client.onMessage("{\"version\": 2, \"method\": \"methodValue\"}"); verify(handler).onNotification(eq(null)); @@ -74,7 +72,8 @@ public class JSPackagerClientTest { @Test public void test_onMessage_WithInvalidContentType_ShouldNotTriggerCallback() throws IOException { RequestHandler handler = mock(RequestHandler.class); - final JSPackagerClient client = new JSPackagerClient("test_client", mSettings, createRH("methodValue", handler)); + final JSPackagerClient client = + new JSPackagerClient("test_client", mSettings, createRH("methodValue", handler)); client.onMessage(ByteString.encodeUtf8("{\"version\": 2, \"method\": \"methodValue\"}")); verify(handler, never()).onNotification(any()); @@ -84,7 +83,8 @@ public class JSPackagerClientTest { @Test public void test_onMessage_WithoutMethod_ShouldNotTriggerCallback() throws IOException { RequestHandler handler = mock(RequestHandler.class); - final JSPackagerClient client = new JSPackagerClient("test_client", mSettings, createRH("methodValue", handler)); + final JSPackagerClient client = + new JSPackagerClient("test_client", mSettings, createRH("methodValue", handler)); client.onMessage("{\"version\": 2}"); verify(handler, never()).onNotification(any()); @@ -94,7 +94,8 @@ public class JSPackagerClientTest { @Test public void test_onMessage_With_Null_Action_ShouldNotTriggerCallback() throws IOException { RequestHandler handler = mock(RequestHandler.class); - final JSPackagerClient client = new JSPackagerClient("test_client", mSettings, createRH("methodValue", handler)); + final JSPackagerClient client = + new JSPackagerClient("test_client", mSettings, createRH("methodValue", handler)); client.onMessage("{\"version\": 2, \"method\": null}"); verify(handler, never()).onNotification(any()); @@ -104,7 +105,8 @@ public class JSPackagerClientTest { @Test public void test_onMessage_WithInvalidMethod_ShouldNotTriggerCallback() throws IOException { RequestHandler handler = mock(RequestHandler.class); - final JSPackagerClient client = new JSPackagerClient("test_client", mSettings, createRH("methodValue", handler)); + final JSPackagerClient client = + new JSPackagerClient("test_client", mSettings, createRH("methodValue", handler)); client.onMessage(ByteString.EMPTY); verify(handler, never()).onNotification(any()); @@ -114,7 +116,8 @@ public class JSPackagerClientTest { @Test public void test_onMessage_WrongVersion_ShouldNotTriggerCallback() throws IOException { RequestHandler handler = mock(RequestHandler.class); - final JSPackagerClient client = new JSPackagerClient("test_client", mSettings, createRH("methodValue", handler)); + final JSPackagerClient client = + new JSPackagerClient("test_client", mSettings, createRH("methodValue", handler)); client.onMessage("{\"version\": 1, \"method\": \"methodValue\"}"); verify(handler, never()).onNotification(any()); @@ -126,7 +129,8 @@ public class JSPackagerClientTest { ConnectionCallback connectionHandler = mock(ConnectionCallback.class); RequestHandler handler = mock(RequestHandler.class); final JSPackagerClient client = - new JSPackagerClient("test_client", mSettings, new HashMap(), connectionHandler); + new JSPackagerClient( + "test_client", mSettings, new HashMap(), connectionHandler); client.close(); diff --git a/ReactAndroid/src/test/java/com/facebook/react/uimanager/BaseViewManagerTest.java b/ReactAndroid/src/test/java/com/facebook/react/uimanager/BaseViewManagerTest.java index db9449bf11c..ebc99eb4085 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/uimanager/BaseViewManagerTest.java +++ b/ReactAndroid/src/test/java/com/facebook/react/uimanager/BaseViewManagerTest.java @@ -1,27 +1,23 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; -import static org.mockito.Mockito.mock; +import static org.fest.assertions.api.Assertions.assertThat; -import android.content.Context; -import androidx.core.view.ViewCompat; +import com.facebook.react.R; import com.facebook.react.uimanager.ReactAccessibilityDelegate.AccessibilityRole; import com.facebook.react.views.view.ReactViewGroup; import com.facebook.react.views.view.ReactViewManager; -import com.facebook.react.R; import java.util.Locale; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; -import org.robolectric.RuntimeEnvironment; import org.robolectric.RobolectricTestRunner; -import static org.fest.assertions.api.Assertions.assertThat; +import org.robolectric.RuntimeEnvironment; @RunWith(RobolectricTestRunner.class) public class BaseViewManagerTest { diff --git a/ReactAndroid/src/test/java/com/facebook/react/uimanager/LayoutPropertyApplicatorTest.java b/ReactAndroid/src/test/java/com/facebook/react/uimanager/LayoutPropertyApplicatorTest.java index 60485e9a227..f3f59966378 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/uimanager/LayoutPropertyApplicatorTest.java +++ b/ReactAndroid/src/test/java/com/facebook/react/uimanager/LayoutPropertyApplicatorTest.java @@ -1,33 +1,11 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; -import android.util.DisplayMetrics; - -import com.facebook.yoga.YogaAlign; -import com.facebook.yoga.YogaConstants; -import com.facebook.yoga.YogaFlexDirection; -import com.facebook.yoga.YogaJustify; -import com.facebook.yoga.YogaPositionType; -import com.facebook.react.bridge.JavaOnlyMap; - -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.modules.junit4.rule.PowerMockRule; -import org.robolectric.RobolectricTestRunner; - import static junit.framework.Assert.assertEquals; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyFloat; @@ -40,13 +18,31 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.powermock.api.mockito.PowerMockito.mockStatic; +import android.util.DisplayMetrics; +import com.facebook.react.bridge.JavaOnlyMap; +import com.facebook.yoga.YogaAlign; +import com.facebook.yoga.YogaConstants; +import com.facebook.yoga.YogaFlexDirection; +import com.facebook.yoga.YogaJustify; +import com.facebook.yoga.YogaPositionType; +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.rule.PowerMockRule; +import org.robolectric.RobolectricTestRunner; + @PrepareForTest({PixelUtil.class}) @RunWith(RobolectricTestRunner.class) @PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "androidx.*", "android.*"}) public class LayoutPropertyApplicatorTest { - @Rule - public PowerMockRule rule = new PowerMockRule(); + @Rule public PowerMockRule rule = new PowerMockRule(); @Before public void setup() { @@ -67,16 +63,8 @@ public class LayoutPropertyApplicatorTest { @Test public void testDimensions() { LayoutShadowNode reactShadowNode = spy(new LayoutShadowNode()); - ReactStylesDiffMap map = spy( - buildStyles( - "width", - 10.0, - "height", - 10.0, - "left", - 10.0, - "top", - 10.0)); + ReactStylesDiffMap map = + spy(buildStyles("width", 10.0, "height", 10.0, "left", 10.0, "top", 10.0)); reactShadowNode.updateProperties(map); verify(reactShadowNode).setStyleWidth(anyFloat()); @@ -122,13 +110,7 @@ public class LayoutPropertyApplicatorTest { @Test public void testPosition() { LayoutShadowNode reactShadowNode = spy(new LayoutShadowNode()); - ReactStylesDiffMap map = spy(buildStyles( - "position", - "absolute", - "bottom", - 10.0, - "right", - 5.0)); + ReactStylesDiffMap map = spy(buildStyles("position", "absolute", "bottom", 10.0, "right", 5.0)); reactShadowNode.updateProperties(map); verify(reactShadowNode).setPosition(eq(Spacing.BOTTOM), anyFloat()); @@ -285,17 +267,18 @@ public class LayoutPropertyApplicatorTest { @Test public void testEnumerations() { LayoutShadowNode reactShadowNode = spy(new LayoutShadowNode()); - ReactStylesDiffMap map = buildStyles( - "flexDirection", - "column", - "alignSelf", - "stretch", - "alignItems", - "center", - "justifyContent", - "space_between", - "position", - "relative"); + ReactStylesDiffMap map = + buildStyles( + "flexDirection", + "column", + "alignSelf", + "stretch", + "alignItems", + "center", + "justifyContent", + "space_between", + "position", + "relative"); reactShadowNode.updateProperties(map); verify(reactShadowNode).setFlexDirection(YogaFlexDirection.COLUMN); @@ -322,33 +305,34 @@ public class LayoutPropertyApplicatorTest { DisplayMetricsHolder.setWindowDisplayMetrics(displayMetrics); LayoutShadowNode reactShadowNode = spy(new LayoutShadowNode()); - ReactStylesDiffMap map = buildStyles( - "width", - 10.0, - "height", - 10.0, - "left", - 10.0, - "top", - 10.0, - "flex", - 1.0, - "padding", - 10.0, - "marginLeft", - 10.0, - "borderTopWidth", - 10.0, - "flexDirection", - "row", - "alignSelf", - "stretch", - "alignItems", - "center", - "justifyContent", - "space_between", - "position", - "absolute"); + ReactStylesDiffMap map = + buildStyles( + "width", + 10.0, + "height", + 10.0, + "left", + 10.0, + "top", + 10.0, + "flex", + 1.0, + "padding", + 10.0, + "marginLeft", + 10.0, + "borderTopWidth", + 10.0, + "flexDirection", + "row", + "alignSelf", + "stretch", + "alignItems", + "center", + "justifyContent", + "space_between", + "position", + "absolute"); reactShadowNode.updateProperties(map); verify(reactShadowNode).setStyleWidth(10.f); @@ -365,33 +349,34 @@ public class LayoutPropertyApplicatorTest { verify(reactShadowNode).setJustifyContent(YogaJustify.SPACE_BETWEEN); verify(reactShadowNode).setPositionType(YogaPositionType.ABSOLUTE); - map = buildStyles( - "width", - null, - "height", - null, - "left", - null, - "top", - null, - "flex", - null, - "padding", - null, - "marginLeft", - null, - "borderTopWidth", - null, - "flexDirection", - null, - "alignSelf", - null, - "alignItems", - null, - "justifyContent", - null, - "position", - null); + map = + buildStyles( + "width", + null, + "height", + null, + "left", + null, + "top", + null, + "flex", + null, + "padding", + null, + "marginLeft", + null, + "borderTopWidth", + null, + "flexDirection", + null, + "alignSelf", + null, + "alignItems", + null, + "justifyContent", + null, + "position", + null); reset(reactShadowNode); reactShadowNode.updateProperties(map); @@ -413,14 +398,15 @@ public class LayoutPropertyApplicatorTest { @Test public void testSettingDefaultStyleValues() { mockStatic(PixelUtil.class); - when(PixelUtil.toPixelFromDIP(anyFloat())).thenAnswer( - new Answer() { - @Override - public Float answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - return (Float) args[0]; - } - }); + when(PixelUtil.toPixelFromDIP(anyFloat())) + .thenAnswer( + new Answer() { + @Override + public Float answer(InvocationOnMock invocation) throws Throwable { + Object[] args = invocation.getArguments(); + return (Float) args[0]; + } + }); LayoutShadowNode[] nodes = new LayoutShadowNode[7]; for (int idx = 0; idx < nodes.length; idx++) { @@ -437,13 +423,8 @@ public class LayoutPropertyApplicatorTest { mapNodes[2] = buildStyles("paddingLeft", 10.0, "paddingVertical", 5.0); mapNodes[3] = buildStyles("paddingBottom", 10.0, "paddingHorizontal", 5.0); mapNodes[4] = buildStyles("padding", null, "paddingTop", 5.0); - mapNodes[5] = buildStyles( - "paddingRight", - 10.0, - "paddingHorizontal", - null, - "paddingVertical", - 7.0); + mapNodes[5] = + buildStyles("paddingRight", 10.0, "paddingHorizontal", null, "paddingVertical", 7.0); mapNodes[6] = buildStyles("margin", 5.0); for (int idx = 0; idx < nodes.length; idx++) { diff --git a/ReactAndroid/src/test/java/com/facebook/react/uimanager/MatrixMathHelperTest.java b/ReactAndroid/src/test/java/com/facebook/react/uimanager/MatrixMathHelperTest.java index 5866ca66f8d..8f725a55126 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/uimanager/MatrixMathHelperTest.java +++ b/ReactAndroid/src/test/java/com/facebook/react/uimanager/MatrixMathHelperTest.java @@ -1,27 +1,24 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; +import static org.fest.assertions.api.Assertions.assertThat; + import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; -import static org.fest.assertions.api.Assertions.assertThat; - -/** - * Test for {@link MatrixMathHelper} - */ +/** Test for {@link MatrixMathHelper} */ @RunWith(RobolectricTestRunner.class) public class MatrixMathHelperTest { private void verifyZRotatedMatrix(double degrees, double rotX, double rotY, double rotZ) { MatrixMathHelper.MatrixDecompositionContext ctx = - new MatrixMathHelper.MatrixDecompositionContext(); + new MatrixMathHelper.MatrixDecompositionContext(); double[] matrix = createRotateZ(degreesToRadians(degrees)); MatrixMathHelper.decomposeMatrix(matrix, ctx); assertThat(ctx.rotationDegrees).containsSequence(rotX, rotY, rotZ); @@ -29,7 +26,7 @@ public class MatrixMathHelperTest { private void verifyYRotatedMatrix(double degrees, double rotX, double rotY, double rotZ) { MatrixMathHelper.MatrixDecompositionContext ctx = - new MatrixMathHelper.MatrixDecompositionContext(); + new MatrixMathHelper.MatrixDecompositionContext(); double[] matrix = createRotateY(degreesToRadians(degrees)); MatrixMathHelper.decomposeMatrix(matrix, ctx); assertThat(ctx.rotationDegrees).containsSequence(rotX, rotY, rotZ); @@ -37,15 +34,16 @@ public class MatrixMathHelperTest { private void verifyXRotatedMatrix(double degrees, double rotX, double rotY, double rotZ) { MatrixMathHelper.MatrixDecompositionContext ctx = - new MatrixMathHelper.MatrixDecompositionContext(); + new MatrixMathHelper.MatrixDecompositionContext(); double[] matrix = createRotateX(degreesToRadians(degrees)); MatrixMathHelper.decomposeMatrix(matrix, ctx); assertThat(ctx.rotationDegrees).containsSequence(rotX, rotY, rotZ); } - private void verifyRotatedMatrix(double degreesX, double degreesY, double degreesZ, double rotX, double rotY, double rotZ) { + private void verifyRotatedMatrix( + double degreesX, double degreesY, double degreesZ, double rotX, double rotY, double rotZ) { MatrixMathHelper.MatrixDecompositionContext ctx = - new MatrixMathHelper.MatrixDecompositionContext(); + new MatrixMathHelper.MatrixDecompositionContext(); double[] matrixX = createRotateX(degreesToRadians(degreesX)); double[] matrixY = createRotateY(degreesToRadians(degreesY)); double[] matrixZ = createRotateZ(degreesToRadians(degreesZ)); @@ -61,15 +59,14 @@ public class MatrixMathHelperTest { public void testDecomposing4x4MatrixToProduceAccurateZaxisAngles() { MatrixMathHelper.MatrixDecompositionContext ctx = - new MatrixMathHelper.MatrixDecompositionContext(); + new MatrixMathHelper.MatrixDecompositionContext(); MatrixMathHelper.decomposeMatrix( - new double[]{1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1}, - ctx); + new double[] {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1}, ctx); assertThat(ctx.rotationDegrees).containsSequence(0d, 0d, 0d); - double[] angles = new double[]{30, 45, 60, 75, 90, 100, 115, 120, 133, 167}; + double[] angles = new double[] {30, 45, 60, 75, 90, 100, 115, 120, 133, 167}; for (double angle : angles) { verifyZRotatedMatrix(angle, 0d, 0d, angle); verifyZRotatedMatrix(-angle, 0d, 0d, -angle); @@ -103,7 +100,7 @@ public class MatrixMathHelperTest { @Test public void testDecomposing4x4MatrixToProduceAccurateYaxisAngles() { - double[] angles = new double[]{30, 45, 60, 75, 90}; + double[] angles = new double[] {30, 45, 60, 75, 90}; for (double angle : angles) { verifyYRotatedMatrix(angle, 0d, angle, 0d); verifyYRotatedMatrix(-angle, 0d, -angle, 0d); @@ -120,7 +117,7 @@ public class MatrixMathHelperTest { @Test public void testDecomposing4x4MatrixToProduceAccurateXaxisAngles() { - double[] angles = new double[]{30, 45, 60, 75, 90, 100, 110, 120, 133, 167}; + double[] angles = new double[] {30, 45, 60, 75, 90, 100, 110, 120, 133, 167}; for (double angle : angles) { verifyXRotatedMatrix(angle, angle, 0d, 0d); verifyXRotatedMatrix(-angle, -angle, 0d, 0d); diff --git a/ReactAndroid/src/test/java/com/facebook/react/uimanager/ReactPropAnnotationSetterSpecTest.java b/ReactAndroid/src/test/java/com/facebook/react/uimanager/ReactPropAnnotationSetterSpecTest.java index d18baaaf018..31e134b9384 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/uimanager/ReactPropAnnotationSetterSpecTest.java +++ b/ReactAndroid/src/test/java/com/facebook/react/uimanager/ReactPropAnnotationSetterSpecTest.java @@ -1,35 +1,28 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; -import java.util.Date; - import android.view.View; - import com.facebook.react.uimanager.annotations.ReactProp; import com.facebook.react.uimanager.annotations.ReactPropGroup; - -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.modules.junit4.rule.PowerMockRule; +import java.util.Date; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.modules.junit4.rule.PowerMockRule; import org.robolectric.RobolectricTestRunner; -/** - * Test that verifies that spec of methods annotated with @ReactProp is correct - */ +/** Test that verifies that spec of methods annotated with @ReactProp is correct */ @RunWith(RobolectricTestRunner.class) @PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "androidx.*", "android.*"}) public class ReactPropAnnotationSetterSpecTest { - @Rule - public PowerMockRule rule = new PowerMockRule(); + @Rule public PowerMockRule rule = new PowerMockRule(); private abstract class BaseViewManager extends ViewManager { @@ -54,16 +47,14 @@ public class ReactPropAnnotationSetterSpecTest { } @Override - public void updateExtraData(View root, Object extraData) { - } + public void updateExtraData(View root, Object extraData) {} } @Test(expected = RuntimeException.class) public void testMethodWithWongNumberOfParams() { new BaseViewManager() { @ReactProp(name = "prop") - public void setterWithIncorrectNumberOfArgs(View v, boolean value, boolean otherValue) { - } + public void setterWithIncorrectNumberOfArgs(View v, boolean value, boolean otherValue) {} }.getNativeProps(); } @@ -71,8 +62,7 @@ public class ReactPropAnnotationSetterSpecTest { public void testMethodWithTooFewParams() { new BaseViewManager() { @ReactProp(name = "prop") - public void setterWithTooFewParams(View v) { - } + public void setterWithTooFewParams(View v) {} }.getNativeProps(); } @@ -80,8 +70,7 @@ public class ReactPropAnnotationSetterSpecTest { public void testUnsupportedPropValueType() { new BaseViewManager() { @ReactProp(name = "prop") - public void setterWithUnsupportedValueType(View v, Date value) { - } + public void setterWithUnsupportedValueType(View v, Date value) {} }.getNativeProps(); } @@ -89,8 +78,7 @@ public class ReactPropAnnotationSetterSpecTest { public void testSetterWIthNonViewParam() { new BaseViewManager() { @ReactProp(name = "prop") - public void setterWithNonViewParam(Object v, boolean value) { - } + public void setterWithNonViewParam(Object v, boolean value) {} }.getNativeProps(); } @@ -98,8 +86,7 @@ public class ReactPropAnnotationSetterSpecTest { public void testGroupInvalidNumberOfParams() { new BaseViewManager() { @ReactPropGroup(names = {"prop1", "prop2"}) - public void setterWIthInvalidNumberOfParams(View v, int index, float value, float other) { - } + public void setterWIthInvalidNumberOfParams(View v, int index, float value, float other) {} }.getNativeProps(); } @@ -107,8 +94,7 @@ public class ReactPropAnnotationSetterSpecTest { public void testGroupTooFewParams() { new BaseViewManager() { @ReactPropGroup(names = {"prop1", "prop2"}) - public void setterWIthTooFewParams(View v, int index) { - } + public void setterWIthTooFewParams(View v, int index) {} }.getNativeProps(); } @@ -116,8 +102,7 @@ public class ReactPropAnnotationSetterSpecTest { public void testGroupNoIndexParam() { new BaseViewManager() { @ReactPropGroup(names = {"prop1", "prop2"}) - public void setterWithoutIndexParam(View v, float value, float sth) { - } + public void setterWithoutIndexParam(View v, float value, float sth) {} }.getNativeProps(); } @@ -125,8 +110,7 @@ public class ReactPropAnnotationSetterSpecTest { public void testGroupNoViewParam() { new BaseViewManager() { @ReactPropGroup(names = {"prop1", "prop2"}) - public void setterWithoutViewParam(Object v, int index, float value) { - } + public void setterWithoutViewParam(Object v, int index, float value) {} }.getNativeProps(); } @@ -134,8 +118,7 @@ public class ReactPropAnnotationSetterSpecTest { public void testGroupUnsupportedPropType() { new BaseViewManager() { @ReactPropGroup(names = {"prop1", "prop2"}) - public void setterWithUnsupportedPropType(View v, int index, long value) { - } + public void setterWithUnsupportedPropType(View v, int index, long value) {} }.getNativeProps(); } } diff --git a/ReactAndroid/src/test/java/com/facebook/react/uimanager/ReactPropAnnotationSetterTest.java b/ReactAndroid/src/test/java/com/facebook/react/uimanager/ReactPropAnnotationSetterTest.java index d2fb9bbc76c..190007564ea 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/uimanager/ReactPropAnnotationSetterTest.java +++ b/ReactAndroid/src/test/java/com/facebook/react/uimanager/ReactPropAnnotationSetterTest.java @@ -1,36 +1,33 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; -import android.view.View; - -import com.facebook.react.bridge.JSApplicationIllegalArgumentException; -import com.facebook.react.bridge.ReadableArray; -import com.facebook.react.bridge.ReadableMap; -import com.facebook.react.bridge.JavaOnlyArray; -import com.facebook.react.bridge.JavaOnlyMap; -import com.facebook.react.uimanager.annotations.ReactProp; -import com.facebook.react.uimanager.annotations.ReactPropGroup; - -import org.junit.Before; -import org.junit.runner.RunWith; -import org.junit.Rule; -import org.junit.Test; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.modules.junit4.rule.PowerMockRule; -import org.robolectric.RobolectricTestRunner; - import static org.fest.assertions.api.Assertions.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; +import android.view.View; +import com.facebook.react.bridge.JSApplicationIllegalArgumentException; +import com.facebook.react.bridge.JavaOnlyArray; +import com.facebook.react.bridge.JavaOnlyMap; +import com.facebook.react.bridge.ReadableArray; +import com.facebook.react.bridge.ReadableMap; +import com.facebook.react.uimanager.annotations.ReactProp; +import com.facebook.react.uimanager.annotations.ReactPropGroup; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.modules.junit4.rule.PowerMockRule; +import org.robolectric.RobolectricTestRunner; + /** * Test updating view through {@link ViewManager} with {@link ReactProp} and {@link ReactPropGroup} * annotations. @@ -39,21 +36,31 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; @PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "androidx.*", "android.*"}) public class ReactPropAnnotationSetterTest { - @Rule - public PowerMockRule rule = new PowerMockRule(); + @Rule public PowerMockRule rule = new PowerMockRule(); public interface ViewManagerUpdatesReceiver { void onBooleanSetterCalled(boolean value); + void onIntSetterCalled(int value); + void onDoubleSetterCalled(double value); + void onFloatSetterCalled(float value); + void onStringSetterCalled(String value); + void onBoxedBooleanSetterCalled(Boolean value); + void onBoxedIntSetterCalled(Integer value); + void onArraySetterCalled(ReadableArray value); + void onMapSetterCalled(ReadableMap value); + void onFloatGroupPropSetterCalled(int index, float value); + void onIntGroupPropSetterCalled(int index, int value); + void onBoxedIntGroupPropSetterCalled(int index, Integer value); } @@ -157,42 +164,42 @@ public class ReactPropAnnotationSetterTest { mViewManagerUpdatesReceiver.onMapSetterCalled(value); } - @ReactPropGroup(names = { - "floatGroupPropFirst", - "floatGroupPropSecond", - }) + @ReactPropGroup( + names = { + "floatGroupPropFirst", + "floatGroupPropSecond", + }) public void setFloatGroupProp(View v, int index, float value) { mViewManagerUpdatesReceiver.onFloatGroupPropSetterCalled(index, value); } - @ReactPropGroup(names = { - "floatGroupPropWithDefaultFirst", - "floatGroupPropWithDefaultSecond", - }, defaultFloat = -100.0f) + @ReactPropGroup( + names = { + "floatGroupPropWithDefaultFirst", + "floatGroupPropWithDefaultSecond", + }, + defaultFloat = -100.0f) public void setFloatGroupPropWithDefault(View v, int index, float value) { mViewManagerUpdatesReceiver.onFloatGroupPropSetterCalled(index, value); } - @ReactPropGroup(names = { - "intGroupPropFirst", - "intGroupPropSecond" - }) + @ReactPropGroup(names = {"intGroupPropFirst", "intGroupPropSecond"}) public void setIntGroupProp(View v, int index, int value) { mViewManagerUpdatesReceiver.onIntGroupPropSetterCalled(index, value); } - @ReactPropGroup(names = { - "intGroupPropWithDefaultFirst", - "intGroupPropWithDefaultSecond" - }, defaultInt = 555) + @ReactPropGroup( + names = {"intGroupPropWithDefaultFirst", "intGroupPropWithDefaultSecond"}, + defaultInt = 555) public void setIntGroupPropWithDefault(View v, int index, int value) { mViewManagerUpdatesReceiver.onIntGroupPropSetterCalled(index, value); } - @ReactPropGroup(names = { - "boxedIntGroupPropFirst", - "boxedIntGroupPropSecond", - }) + @ReactPropGroup( + names = { + "boxedIntGroupPropFirst", + "boxedIntGroupPropSecond", + }) public void setBoxedIntGroupProp(View v, int index, Integer value) { mViewManagerUpdatesReceiver.onBoxedIntGroupPropSetterCalled(index, value); } diff --git a/ReactAndroid/src/test/java/com/facebook/react/uimanager/ReactPropConstantsTest.java b/ReactAndroid/src/test/java/com/facebook/react/uimanager/ReactPropConstantsTest.java index cfa7be3bc0b..883732bebe9 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/uimanager/ReactPropConstantsTest.java +++ b/ReactAndroid/src/test/java/com/facebook/react/uimanager/ReactPropConstantsTest.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; import static org.fest.assertions.api.Assertions.assertThat; @@ -28,15 +27,12 @@ import org.powermock.modules.junit4.rule.PowerMockRule; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; -/** - * Verifies that prop constants are generated properly based on {@code ReactProp} annotation. - */ +/** Verifies that prop constants are generated properly based on {@code ReactProp} annotation. */ @RunWith(RobolectricTestRunner.class) @PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "androidx.*", "android.*"}) public class ReactPropConstantsTest { - @Rule - public PowerMockRule rule = new PowerMockRule(); + @Rule public PowerMockRule rule = new PowerMockRule(); private class ViewManagerUnderTest extends ViewManager { @@ -68,103 +64,88 @@ public class ReactPropConstantsTest { } @ReactProp(name = "boolProp") - public void setBoolProp(View v, boolean value) { - } + public void setBoolProp(View v, boolean value) {} @ReactProp(name = "intProp") - public void setIntProp(View v, int value) { - } + public void setIntProp(View v, int value) {} @ReactProp(name = "floatProp") - public void setFloatProp(View v, float value) { - } + public void setFloatProp(View v, float value) {} @ReactProp(name = "doubleProp") - public void setDoubleProp(View v, double value) { - } + public void setDoubleProp(View v, double value) {} @ReactProp(name = "stringProp") - public void setStringProp(View v, String value) { - } + public void setStringProp(View v, String value) {} @ReactProp(name = "boxedBoolProp") - public void setBoxedBoolProp(View v, Boolean value) { - } + public void setBoxedBoolProp(View v, Boolean value) {} @ReactProp(name = "boxedIntProp") - public void setBoxedIntProp(View v, Integer value) { - } + public void setBoxedIntProp(View v, Integer value) {} @ReactProp(name = "arrayProp") - public void setArrayProp(View v, ReadableArray value) { - } + public void setArrayProp(View v, ReadableArray value) {} @ReactProp(name = "mapProp") - public void setMapProp(View v, ReadableMap value) { - } + public void setMapProp(View v, ReadableMap value) {} - @ReactPropGroup(names = { - "floatGroupPropFirst", - "floatGroupPropSecond", - }) - public void setFloatGroupProp(View v, int index, float value) { - } + @ReactPropGroup( + names = { + "floatGroupPropFirst", + "floatGroupPropSecond", + }) + public void setFloatGroupProp(View v, int index, float value) {} - @ReactPropGroup(names = { - "intGroupPropFirst", - "intGroupPropSecond" - }) - public void setIntGroupProp(View v, int index, int value) { - } + @ReactPropGroup(names = {"intGroupPropFirst", "intGroupPropSecond"}) + public void setIntGroupProp(View v, int index, int value) {} - @ReactPropGroup(names = { - "boxedIntGroupPropFirst", - "boxedIntGroupPropSecond", - }) - public void setBoxedIntGroupProp(View v, int index, Integer value) { - } + @ReactPropGroup( + names = { + "boxedIntGroupPropFirst", + "boxedIntGroupPropSecond", + }) + public void setBoxedIntGroupProp(View v, int index, Integer value) {} @ReactProp(name = "customIntProp", customType = "date") - public void customIntProp(View v, int value) { - } + public void customIntProp(View v, int value) {} - @ReactPropGroup(names = { - "customBoxedIntGroupPropFirst", - "customBoxedIntGroupPropSecond" - }, customType = "color") - public void customIntGroupProp(View v, int index, Integer value) { - } + @ReactPropGroup( + names = {"customBoxedIntGroupPropFirst", "customBoxedIntGroupPropSecond"}, + customType = "color") + public void customIntGroupProp(View v, int index, Integer value) {} } @Test public void testNativePropsIncludeCorrectTypes() { List viewManagers = Arrays.asList(new ViewManagerUnderTest()); - ReactApplicationContext reactContext = new ReactApplicationContext(RuntimeEnvironment.application); - UIManagerModule uiManagerModule = - new UIManagerModule(reactContext, viewManagers, 0); + ReactApplicationContext reactContext = + new ReactApplicationContext(RuntimeEnvironment.application); + UIManagerModule uiManagerModule = new UIManagerModule(reactContext, viewManagers, 0); Map constants = (Map) valueAtPath(uiManagerModule.getConstants(), "SomeView", "NativeProps"); - assertThat(constants).isEqualTo( - MapBuilder.builder() - .put("boolProp", "boolean") - .put("intProp", "number") - .put("doubleProp", "number") - .put("floatProp", "number") - .put("stringProp", "String") - .put("boxedBoolProp", "boolean") - .put("boxedIntProp", "number") - .put("arrayProp", "Array") - .put("mapProp", "Map") - .put("floatGroupPropFirst", "number") - .put("floatGroupPropSecond", "number") - .put("intGroupPropFirst", "number") - .put("intGroupPropSecond", "number") - .put("boxedIntGroupPropFirst", "number") - .put("boxedIntGroupPropSecond", "number") - .put("customIntProp", "date") - .put("customBoxedIntGroupPropFirst", "color") - .put("customBoxedIntGroupPropSecond", "color") - .build()); + assertThat(constants) + .isEqualTo( + MapBuilder.builder() + .put("boolProp", "boolean") + .put("intProp", "number") + .put("doubleProp", "number") + .put("floatProp", "number") + .put("stringProp", "String") + .put("boxedBoolProp", "boolean") + .put("boxedIntProp", "number") + .put("arrayProp", "Array") + .put("mapProp", "Map") + .put("floatGroupPropFirst", "number") + .put("floatGroupPropSecond", "number") + .put("intGroupPropFirst", "number") + .put("intGroupPropSecond", "number") + .put("boxedIntGroupPropFirst", "number") + .put("boxedIntGroupPropSecond", "number") + .put("customIntProp", "date") + .put("customBoxedIntGroupPropFirst", "color") + .put("customBoxedIntGroupPropSecond", "color") + .build()); } private static Object valueAtPath(Map nestedMap, String... keyPath) { diff --git a/ReactAndroid/src/test/java/com/facebook/react/uimanager/ReactPropForShadowNodeSetterTest.java b/ReactAndroid/src/test/java/com/facebook/react/uimanager/ReactPropForShadowNodeSetterTest.java index dd36766d7f3..c1a289e0b4c 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/uimanager/ReactPropForShadowNodeSetterTest.java +++ b/ReactAndroid/src/test/java/com/facebook/react/uimanager/ReactPropForShadowNodeSetterTest.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; import static org.mockito.Mockito.mock; @@ -35,21 +34,31 @@ import org.robolectric.RobolectricTestRunner; @PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "androidx.*", "android.*"}) public class ReactPropForShadowNodeSetterTest { - @Rule - public PowerMockRule rule = new PowerMockRule(); + @Rule public PowerMockRule rule = new PowerMockRule(); public interface ViewManagerUpdatesReceiver { void onBooleanSetterCalled(boolean value); + void onIntSetterCalled(int value); + void onDoubleSetterCalled(double value); + void onFloatSetterCalled(float value); + void onStringSetterCalled(String value); + void onBoxedBooleanSetterCalled(Boolean value); + void onBoxedIntSetterCalled(Integer value); + void onArraySetterCalled(ReadableArray value); + void onMapSetterCalled(ReadableMap value); + void onFloatGroupPropSetterCalled(int index, float value); + void onIntGroupPropSetterCalled(int index, int value); + void onBoxedIntGroupPropSetterCalled(int index, Integer value); } @@ -80,10 +89,11 @@ public class ReactPropForShadowNodeSetterTest { mViewManagerUpdatesReceiver.onBoxedIntSetterCalled(value); } - @ReactPropGroup(names = { - "floatGroupPropFirst", - "floatGroupPropSecond", - }) + @ReactPropGroup( + names = { + "floatGroupPropFirst", + "floatGroupPropSecond", + }) public void setFloatGroupProp(int index, float value) { mViewManagerUpdatesReceiver.onFloatGroupPropSetterCalled(index, value); } diff --git a/ReactAndroid/src/test/java/com/facebook/react/uimanager/ReactPropForShadowNodeSpecTest.java b/ReactAndroid/src/test/java/com/facebook/react/uimanager/ReactPropForShadowNodeSpecTest.java index 2ae60bf9cfc..94022c164e2 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/uimanager/ReactPropForShadowNodeSpecTest.java +++ b/ReactAndroid/src/test/java/com/facebook/react/uimanager/ReactPropForShadowNodeSpecTest.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; import android.view.View; @@ -26,8 +25,7 @@ import org.robolectric.RobolectricTestRunner; @PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "androidx.*", "android.*"}) public class ReactPropForShadowNodeSpecTest { - @Rule - public PowerMockRule rule = new PowerMockRule(); + @Rule public PowerMockRule rule = new PowerMockRule(); private static class BaseViewManager extends ViewManager { @@ -58,8 +56,7 @@ public class ReactPropForShadowNodeSpecTest { } @Override - public void updateExtraData(View root, Object extraData) { - } + public void updateExtraData(View root, Object extraData) {} } @Test(expected = RuntimeException.class) diff --git a/ReactAndroid/src/test/java/com/facebook/react/uimanager/SimpleViewPropertyTest.java b/ReactAndroid/src/test/java/com/facebook/react/uimanager/SimpleViewPropertyTest.java index c66d9bf48df..c3453052e57 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/uimanager/SimpleViewPropertyTest.java +++ b/ReactAndroid/src/test/java/com/facebook/react/uimanager/SimpleViewPropertyTest.java @@ -1,56 +1,47 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; -import java.util.Map; - -import android.graphics.drawable.ColorDrawable; -import android.view.View; - -import com.facebook.react.bridge.ReadableMap; -import com.facebook.react.touch.JSResponderHandler; -import com.facebook.react.bridge.ReactApplicationContext; -import com.facebook.react.bridge.ReactTestHelper; -import com.facebook.react.bridge.JavaOnlyMap; -import com.facebook.react.bridge.CatalystInstance; -import com.facebook.react.uimanager.annotations.ReactProp; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.robolectric.RuntimeEnvironment; -import org.robolectric.RobolectricTestRunner; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.modules.junit4.rule.PowerMockRule; - import static org.fest.assertions.api.Assertions.assertThat; import static org.fest.assertions.api.Assertions.offset; -/** - * Verify {@link View} view property being applied properly by {@link SimpleViewManager} - */ +import android.graphics.drawable.ColorDrawable; +import android.view.View; +import com.facebook.react.bridge.CatalystInstance; +import com.facebook.react.bridge.JavaOnlyMap; +import com.facebook.react.bridge.ReactApplicationContext; +import com.facebook.react.bridge.ReactTestHelper; +import com.facebook.react.bridge.ReadableMap; +import com.facebook.react.touch.JSResponderHandler; +import com.facebook.react.uimanager.annotations.ReactProp; +import java.util.Map; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.modules.junit4.rule.PowerMockRule; +import org.robolectric.RobolectricTestRunner; +import org.robolectric.RuntimeEnvironment; + +/** Verify {@link View} view property being applied properly by {@link SimpleViewManager} */ @RunWith(RobolectricTestRunner.class) @PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "androidx.*", "android.*"}) public class SimpleViewPropertyTest { - @Rule - public PowerMockRule rule = new PowerMockRule(); + @Rule public PowerMockRule rule = new PowerMockRule(); private static class ConcreteViewManager extends SimpleViewManager { @ReactProp(name = "foo") - public void setFoo(View view, boolean foo) { - } + public void setFoo(View view, boolean foo) {} @ReactProp(name = "bar") - public void setBar(View view, ReadableMap bar) { - } + public void setBar(View view, ReadableMap bar) {} @Override protected View createViewInstance(ThemedReactContext reactContext) { @@ -103,10 +94,10 @@ public class SimpleViewPropertyTest { assertThat(view.getBackground()).isEqualTo(null); mManager.updateProperties(view, buildStyles("backgroundColor", 12)); - assertThat(((ColorDrawable)view.getBackground()).getColor()).isEqualTo(12); + assertThat(((ColorDrawable) view.getBackground()).getColor()).isEqualTo(12); mManager.updateProperties(view, buildStyles("backgroundColor", null)); - assertThat(((ColorDrawable)view.getBackground()).getColor()).isEqualTo(0); + assertThat(((ColorDrawable) view.getBackground()).getColor()).isEqualTo(0); } @Test diff --git a/ReactAndroid/src/test/java/com/facebook/react/uimanager/UIManagerModuleConstantsTest.java b/ReactAndroid/src/test/java/com/facebook/react/uimanager/UIManagerModuleConstantsTest.java index ddc4ced9326..c4f91a7d4c6 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/uimanager/UIManagerModuleConstantsTest.java +++ b/ReactAndroid/src/test/java/com/facebook/react/uimanager/UIManagerModuleConstantsTest.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; import static org.fest.assertions.api.Assertions.assertThat; @@ -30,19 +29,15 @@ import org.robolectric.RuntimeEnvironment; @PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "androidx.*", "android.*"}) public class UIManagerModuleConstantsTest { - @Rule - public PowerMockRule rule = new PowerMockRule(); + @Rule public PowerMockRule rule = new PowerMockRule(); private static final String CUSTOM_BUBBLING_EVENT_TYPES = "customBubblingEventTypes"; private static final String CUSTOM_DIRECT_EVENT_TYPES = "customDirectEventTypes"; - private static final Map TWIRL_BUBBLING_EVENT_MAP = MapBuilder.of( - "phasedRegistrationNames", + private static final Map TWIRL_BUBBLING_EVENT_MAP = MapBuilder.of( - "bubbled", - "onTwirl", - "captured", - "onTwirlCaptured")); + "phasedRegistrationNames", + MapBuilder.of("bubbled", "onTwirl", "captured", "onTwirlCaptured")); private static final Map TWIRL_DIRECT_EVENT_MAP = MapBuilder.of("registrationName", "onTwirl"); private ReactApplicationContext mReactContext; @@ -55,8 +50,7 @@ public class UIManagerModuleConstantsTest { @Test public void testNoCustomConstants() { List viewManagers = Arrays.asList(mock(ViewManager.class)); - UIManagerModule uiManagerModule = - new UIManagerModule(mReactContext, viewManagers, 0); + UIManagerModule uiManagerModule = new UIManagerModule(mReactContext, viewManagers, 0); Map constants = uiManagerModule.getConstants(); assertThat(constants) .containsKey(CUSTOM_BUBBLING_EVENT_TYPES) @@ -70,8 +64,7 @@ public class UIManagerModuleConstantsTest { List viewManagers = Arrays.asList(mockViewManager); when(mockViewManager.getExportedCustomBubblingEventTypeConstants()) .thenReturn(MapBuilder.of("onTwirl", TWIRL_BUBBLING_EVENT_MAP)); - UIManagerModule uiManagerModule = - new UIManagerModule(mReactContext, viewManagers, 0); + UIManagerModule uiManagerModule = new UIManagerModule(mReactContext, viewManagers, 0); Map constants = uiManagerModule.getConstants(); assertThat((Map) constants.get(CUSTOM_BUBBLING_EVENT_TYPES)) .contains(MapEntry.entry("onTwirl", TWIRL_BUBBLING_EVENT_MAP)) @@ -84,8 +77,7 @@ public class UIManagerModuleConstantsTest { List viewManagers = Arrays.asList(mockViewManager); when(mockViewManager.getExportedCustomDirectEventTypeConstants()) .thenReturn(MapBuilder.of("onTwirl", TWIRL_DIRECT_EVENT_MAP)); - UIManagerModule uiManagerModule = - new UIManagerModule(mReactContext, viewManagers, 0); + UIManagerModule uiManagerModule = new UIManagerModule(mReactContext, viewManagers, 0); Map constants = uiManagerModule.getConstants(); assertThat((Map) constants.get(CUSTOM_DIRECT_EVENT_TYPES)) .contains(MapEntry.entry("onTwirl", TWIRL_DIRECT_EVENT_MAP)) @@ -99,8 +91,7 @@ public class UIManagerModuleConstantsTest { when(mockViewManager.getName()).thenReturn("RedPandaPhotoOfTheDayView"); when(mockViewManager.getExportedViewConstants()) .thenReturn(MapBuilder.of("PhotoSizeType", MapBuilder.of("Small", 1, "Large", 2))); - UIManagerModule uiManagerModule = - new UIManagerModule(mReactContext, viewManagers, 0); + UIManagerModule uiManagerModule = new UIManagerModule(mReactContext, viewManagers, 0); Map constants = uiManagerModule.getConstants(); assertThat(constants).containsKey("RedPandaPhotoOfTheDayView"); assertThat((Map) constants.get("RedPandaPhotoOfTheDayView")).containsKey("Constants"); @@ -113,10 +104,8 @@ public class UIManagerModuleConstantsTest { ViewManager mockViewManager = mock(ViewManager.class); List viewManagers = Arrays.asList(mockViewManager); when(mockViewManager.getName()).thenReturn("SomeView"); - when(mockViewManager.getNativeProps()) - .thenReturn(MapBuilder.of("fooProp", "number")); - UIManagerModule uiManagerModule = - new UIManagerModule(mReactContext, viewManagers, 0); + when(mockViewManager.getNativeProps()).thenReturn(MapBuilder.of("fooProp", "number")); + UIManagerModule uiManagerModule = new UIManagerModule(mReactContext, viewManagers, 0); Map constants = uiManagerModule.getConstants(); assertThat((String) valueAtPath(constants, "SomeView", "NativeProps", "fooProp")) .isEqualTo("number"); @@ -125,30 +114,33 @@ public class UIManagerModuleConstantsTest { @Test public void testMergeConstants() { ViewManager managerX = mock(ViewManager.class); - when(managerX.getExportedCustomDirectEventTypeConstants()).thenReturn(MapBuilder.of( - "onTwirl", - MapBuilder.of( - "registrationName", - "onTwirl", - "keyToOverride", - "valueX", - "mapToMerge", - MapBuilder.of("keyToOverride", "innerValueX", "anotherKey", "valueX")))); + when(managerX.getExportedCustomDirectEventTypeConstants()) + .thenReturn( + MapBuilder.of( + "onTwirl", + MapBuilder.of( + "registrationName", + "onTwirl", + "keyToOverride", + "valueX", + "mapToMerge", + MapBuilder.of("keyToOverride", "innerValueX", "anotherKey", "valueX")))); ViewManager managerY = mock(ViewManager.class); - when(managerY.getExportedCustomDirectEventTypeConstants()).thenReturn(MapBuilder.of( - "onTwirl", - MapBuilder.of( - "extraKey", - "extraValue", - "keyToOverride", - "valueY", - "mapToMerge", - MapBuilder.of("keyToOverride", "innerValueY", "extraKey", "valueY")))); + when(managerY.getExportedCustomDirectEventTypeConstants()) + .thenReturn( + MapBuilder.of( + "onTwirl", + MapBuilder.of( + "extraKey", + "extraValue", + "keyToOverride", + "valueY", + "mapToMerge", + MapBuilder.of("keyToOverride", "innerValueY", "extraKey", "valueY")))); List viewManagers = Arrays.asList(managerX, managerY); - UIManagerModule uiManagerModule = - new UIManagerModule(mReactContext, viewManagers, 0); + UIManagerModule uiManagerModule = new UIManagerModule(mReactContext, viewManagers, 0); Map constants = uiManagerModule.getConstants(); assertThat((Map) constants.get(CUSTOM_DIRECT_EVENT_TYPES)).containsKey("onTwirl"); diff --git a/ReactAndroid/src/test/java/com/facebook/react/uimanager/UIManagerModuleTest.java b/ReactAndroid/src/test/java/com/facebook/react/uimanager/UIManagerModuleTest.java index 3190c692f5a..f6c45c854a1 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/uimanager/UIManagerModuleTest.java +++ b/ReactAndroid/src/test/java/com/facebook/react/uimanager/UIManagerModuleTest.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager; import static org.fest.assertions.api.Assertions.assertThat; @@ -53,16 +52,13 @@ import org.powermock.modules.junit4.rule.PowerMockRule; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; -/** - * Tests for {@link UIManagerModule}. - */ +/** Tests for {@link UIManagerModule}. */ @PrepareForTest({Arguments.class, ReactChoreographer.class}) @RunWith(RobolectricTestRunner.class) @PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "androidx.*", "android.*"}) public class UIManagerModuleTest { - @Rule - public PowerMockRule rule = new PowerMockRule(); + @Rule public PowerMockRule rule = new PowerMockRule(); private ReactApplicationContext mReactContext; private CatalystInstance mCatalystInstanceMock; @@ -73,31 +69,38 @@ public class UIManagerModuleTest { PowerMockito.mockStatic(Arguments.class, ReactChoreographer.class); ReactChoreographer choreographerMock = mock(ReactChoreographer.class); - PowerMockito.when(Arguments.createArray()).thenAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - return new JavaOnlyArray(); - } - }); - PowerMockito.when(Arguments.createMap()).thenAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - return new JavaOnlyMap(); - } - }); + PowerMockito.when(Arguments.createArray()) + .thenAnswer( + new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + return new JavaOnlyArray(); + } + }); + PowerMockito.when(Arguments.createMap()) + .thenAnswer( + new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + return new JavaOnlyMap(); + } + }); PowerMockito.when(ReactChoreographer.getInstance()).thenReturn(choreographerMock); mPendingFrameCallbacks = new ArrayList<>(); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - mPendingFrameCallbacks - .add((ChoreographerCompat.FrameCallback) invocation.getArguments()[1]); - return null; - } - }).when(choreographerMock).postFrameCallback( - any(ReactChoreographer.CallbackType.class), - any(ChoreographerCompat.FrameCallback.class)); + doAnswer( + new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + mPendingFrameCallbacks.add( + (ChoreographerCompat.FrameCallback) invocation.getArguments()[1]); + return null; + } + }) + .when(choreographerMock) + .postFrameCallback( + any(ReactChoreographer.CallbackType.class), + any(ChoreographerCompat.FrameCallback.class)); mCatalystInstanceMock = ReactTestHelper.createMockCatalystInstance(); mReactContext = new ReactApplicationContext(RuntimeEnvironment.application); @@ -151,31 +154,15 @@ public class UIManagerModuleTest { int subViewTag = viewTag + 1; uiManager.createView( - viewTag, - ReactViewManager.REACT_CLASS, - rootTag, - JavaOnlyMap.of("collapsable", false)); + viewTag, ReactViewManager.REACT_CLASS, rootTag, JavaOnlyMap.of("collapsable", false)); uiManager.createView( - subViewTag, - ReactViewManager.REACT_CLASS, - rootTag, - JavaOnlyMap.of("collapsable", false)); + subViewTag, ReactViewManager.REACT_CLASS, rootTag, JavaOnlyMap.of("collapsable", false)); uiManager.manageChildren( - viewTag, - null, - null, - JavaOnlyArray.of(subViewTag), - JavaOnlyArray.of(0), - null); + viewTag, null, null, JavaOnlyArray.of(subViewTag), JavaOnlyArray.of(0), null); uiManager.manageChildren( - rootTag, - null, - null, - JavaOnlyArray.of(viewTag), - JavaOnlyArray.of(0), - null); + rootTag, null, null, JavaOnlyArray.of(viewTag), JavaOnlyArray.of(0), null); uiManager.onBatchComplete(); executePendingFrameCallbacks(); @@ -201,12 +188,7 @@ public class UIManagerModuleTest { View expectedViewAt3 = hierarchy.nativeRootView.getChildAt(3); uiManager.manageChildren( - hierarchy.rootView, - JavaOnlyArray.of(1, 0, 2), - JavaOnlyArray.of(0, 2, 1), - null, - null, - null); + hierarchy.rootView, JavaOnlyArray.of(1, 0, 2), JavaOnlyArray.of(0, 2, 1), null, null, null); uiManager.onBatchComplete(); executePendingFrameCallbacks(); @@ -227,21 +209,12 @@ public class UIManagerModuleTest { View expectedViewAt0 = hierarchy.nativeRootView.getChildAt(1); View expectedViewAt1 = hierarchy.nativeRootView.getChildAt(2); - uiManager.manageChildren( - hierarchy.rootView, - null, - null, - null, - null, - JavaOnlyArray.of(0, 3)); + uiManager.manageChildren(hierarchy.rootView, null, null, null, null, JavaOnlyArray.of(0, 3)); uiManager.onBatchComplete(); executePendingFrameCallbacks(); - assertChildrenAreExactly( - hierarchy.nativeRootView, - expectedViewAt0, - expectedViewAt1); + assertChildrenAreExactly(hierarchy.nativeRootView, expectedViewAt0, expectedViewAt1); } @Test @@ -265,10 +238,7 @@ public class UIManagerModuleTest { executePendingFrameCallbacks(); assertChildrenAreExactly( - hierarchy.nativeRootView, - expectedViewAt0, - expectedViewAt1, - expectedViewAt2); + hierarchy.nativeRootView, expectedViewAt0, expectedViewAt1, expectedViewAt2); } @Test(expected = IllegalViewOperationException.class) @@ -293,13 +263,7 @@ public class UIManagerModuleTest { UIManagerModule uiManager = getUIManagerModule(); TestMoveDeleteHierarchy hierarchy = createMoveDeleteHierarchy(uiManager); - uiManager.manageChildren( - hierarchy.rootView, - null, - null, - null, - null, - JavaOnlyArray.of(3, 3)); + uiManager.manageChildren(hierarchy.rootView, null, null, null, null, JavaOnlyArray.of(3, 3)); uiManager.onBatchComplete(); executePendingFrameCallbacks(); @@ -351,12 +315,7 @@ public class UIManagerModuleTest { View expectedViewAt3 = hierarchy.nativeRootView.getChildAt(3); uiManager.manageChildren( - hierarchy.rootView, - JavaOnlyArray.of(1, 2), - JavaOnlyArray.of(2, 1), - null, - null, - null); + hierarchy.rootView, JavaOnlyArray.of(1, 2), JavaOnlyArray.of(2, 1), null, null, null); uiManager.onBatchComplete(); executePendingFrameCallbacks(); @@ -379,22 +338,13 @@ public class UIManagerModuleTest { View expectedViewAt1 = hierarchy.nativeRootView.getChildAt(2); View expectedViewAt2 = hierarchy.nativeRootView.getChildAt(3); - uiManager.manageChildren( - hierarchy.rootView, - null, - null, - null, - null, - JavaOnlyArray.of(1)); + uiManager.manageChildren(hierarchy.rootView, null, null, null, null, JavaOnlyArray.of(1)); uiManager.onBatchComplete(); executePendingFrameCallbacks(); assertChildrenAreExactly( - hierarchy.nativeRootView, - expectedViewAt0, - expectedViewAt1, - expectedViewAt2); + hierarchy.nativeRootView, expectedViewAt0, expectedViewAt1, expectedViewAt2); } @Test @@ -408,16 +358,11 @@ public class UIManagerModuleTest { newViewTag, ReactViewManager.REACT_CLASS, hierarchy.rootView, - JavaOnlyMap - .of("left", 10.0, "top", 20.0, "width", 30.0, "height", 40.0, "collapsable", false)); + JavaOnlyMap.of( + "left", 10.0, "top", 20.0, "width", 30.0, "height", 40.0, "collapsable", false)); uiManager.manageChildren( - hierarchy.rootView, - null, - null, - JavaOnlyArray.of(newViewTag), - JavaOnlyArray.of(4), - null); + hierarchy.rootView, null, null, JavaOnlyArray.of(newViewTag), JavaOnlyArray.of(4), null); uiManager.onBatchComplete(); executePendingFrameCallbacks(); @@ -430,9 +375,7 @@ public class UIManagerModuleTest { assertThat(newView.getHeight()).isEqualTo(40); } - /** - * This is to make sure we execute enqueued operations in the order given by JS. - */ + /** This is to make sure we execute enqueued operations in the order given by JS. */ @Test public void testAddUpdateRemoveInSingleBatch() { UIManagerModule uiManager = getUIManagerModule(); @@ -447,25 +390,12 @@ public class UIManagerModuleTest { JavaOnlyMap.of("collapsable", false)); uiManager.manageChildren( - hierarchy.rootView, - null, - null, - JavaOnlyArray.of(newViewTag), - JavaOnlyArray.of(4), - null); + hierarchy.rootView, null, null, JavaOnlyArray.of(newViewTag), JavaOnlyArray.of(4), null); uiManager.updateView( - newViewTag, - ReactViewManager.REACT_CLASS, - JavaOnlyMap.of("backgroundColor", Color.RED)); + newViewTag, ReactViewManager.REACT_CLASS, JavaOnlyMap.of("backgroundColor", Color.RED)); - uiManager.manageChildren( - hierarchy.rootView, - null, - null, - null, - null, - JavaOnlyArray.of(4)); + uiManager.manageChildren(hierarchy.rootView, null, null, null, null, JavaOnlyArray.of(4)); uiManager.onBatchComplete(); executePendingFrameCallbacks(); @@ -536,8 +466,7 @@ public class UIManagerModuleTest { } @Override - public void run() { - } + public void run() {} } @Test @@ -610,10 +539,7 @@ public class UIManagerModuleTest { final int containerSiblingTag = containerTag + 1; uiManager.createView( - containerTag, - ReactViewManager.REACT_CLASS, - rootTag, - JavaOnlyMap.of("collapsable", false)); + containerTag, ReactViewManager.REACT_CLASS, rootTag, JavaOnlyMap.of("collapsable", false)); uiManager.createView( containerSiblingTag, ReactViewManager.REACT_CLASS, @@ -662,10 +588,7 @@ public class UIManagerModuleTest { int rawTextTag = textTag + 1; uiManager.createView( - textTag, - ReactTextViewManager.REACT_CLASS, - rootTag, - JavaOnlyMap.of("collapsable", false)); + textTag, ReactTextViewManager.REACT_CLASS, rootTag, JavaOnlyMap.of("collapsable", false)); uiManager.createView( rawTextTag, ReactRawTextManager.REACT_CLASS, @@ -673,20 +596,10 @@ public class UIManagerModuleTest { JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, text, "collapsable", false)); uiManager.manageChildren( - textTag, - null, - null, - JavaOnlyArray.of(rawTextTag), - JavaOnlyArray.of(0), - null); + textTag, null, null, JavaOnlyArray.of(rawTextTag), JavaOnlyArray.of(0), null); uiManager.manageChildren( - rootTag, - null, - null, - JavaOnlyArray.of(textTag), - JavaOnlyArray.of(0), - null); + rootTag, null, null, JavaOnlyArray.of(textTag), JavaOnlyArray.of(0), null); uiManager.onBatchComplete(); executePendingFrameCallbacks(); @@ -747,34 +660,22 @@ public class UIManagerModuleTest { private void addChild(UIManagerModule uiManager, int parentTag, int childTag, int index) { uiManager.manageChildren( - parentTag, - null, - null, - JavaOnlyArray.of(childTag), - JavaOnlyArray.of(index), - null); + parentTag, null, null, JavaOnlyArray.of(childTag), JavaOnlyArray.of(index), null); } private void assertChildrenAreExactly(ViewGroup parent, View... views) { assertThat(parent.getChildCount()).isEqualTo(views.length); for (int i = 0; i < views.length; i++) { - assertThat(parent.getChildAt(i)) - .describedAs("View at " + i) - .isEqualTo(views[i]); + assertThat(parent.getChildAt(i)).describedAs("View at " + i).isEqualTo(views[i]); } } /** - * Holder for the tags that represent that represent views in the following hierarchy: - * - View rootView - * - View view0 - * - View viewWithChildren1 - * - View childView0 - * - View childView1 - * - View view2 - * - View view3 + * Holder for the tags that represent that represent views in the following hierarchy: - View + * rootView - View view0 - View viewWithChildren1 - View childView0 - View childView1 - View view2 + * - View view3 * - * This hierarchy is used to test move/delete functionality in manageChildren. + *

This hierarchy is used to test move/delete functionality in manageChildren. */ private static class TestMoveDeleteHierarchy { @@ -809,12 +710,10 @@ public class UIManagerModuleTest { } private UIManagerModule getUIManagerModule() { - List viewManagers = Arrays.asList( - new ReactViewManager(), - new ReactTextViewManager(), - new ReactRawTextManager()); - UIManagerModule uiManagerModule = - new UIManagerModule(mReactContext, viewManagers, 0); + List viewManagers = + Arrays.asList( + new ReactViewManager(), new ReactTextViewManager(), new ReactRawTextManager()); + UIManagerModule uiManagerModule = new UIManagerModule(mReactContext, viewManagers, 0); uiManagerModule.onHostResume(); return uiManagerModule; } diff --git a/ReactAndroid/src/test/java/com/facebook/react/uimanager/layoutanimation/InterpolatorTypeTest.java b/ReactAndroid/src/test/java/com/facebook/react/uimanager/layoutanimation/InterpolatorTypeTest.java index 291d1c4facb..a5bc8bab1cb 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/uimanager/layoutanimation/InterpolatorTypeTest.java +++ b/ReactAndroid/src/test/java/com/facebook/react/uimanager/layoutanimation/InterpolatorTypeTest.java @@ -1,18 +1,17 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.uimanager.layoutanimation; -import com.facebook.react.uimanager.layoutanimation.InterpolatorType; +import static org.fest.assertions.api.Assertions.assertThat; + import java.util.Locale; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; -import static org.fest.assertions.api.Assertions.assertThat; @RunWith(RobolectricTestRunner.class) public class InterpolatorTypeTest { @@ -22,7 +21,8 @@ public class InterpolatorTypeTest { assertThat(InterpolatorType.fromString("linear")).isEqualTo(InterpolatorType.LINEAR); assertThat(InterpolatorType.fromString("easeIn")).isEqualTo(InterpolatorType.EASE_IN); assertThat(InterpolatorType.fromString("easeOut")).isEqualTo(InterpolatorType.EASE_OUT); - assertThat(InterpolatorType.fromString("easeInEaseOut")).isEqualTo(InterpolatorType.EASE_IN_EASE_OUT); + assertThat(InterpolatorType.fromString("easeInEaseOut")) + .isEqualTo(InterpolatorType.EASE_IN_EASE_OUT); assertThat(InterpolatorType.fromString("spring")).isEqualTo(InterpolatorType.SPRING); } @@ -30,13 +30,15 @@ public class InterpolatorTypeTest { public void testOtherCases() { assertThat(InterpolatorType.fromString("EASEIN")).isEqualTo(InterpolatorType.EASE_IN); assertThat(InterpolatorType.fromString("easeout")).isEqualTo(InterpolatorType.EASE_OUT); - assertThat(InterpolatorType.fromString("easeineaseout")).isEqualTo(InterpolatorType.EASE_IN_EASE_OUT); + assertThat(InterpolatorType.fromString("easeineaseout")) + .isEqualTo(InterpolatorType.EASE_IN_EASE_OUT); } @Test public void testLocales() { Locale.setDefault(Locale.forLanguageTag("tr-TR")); - assertThat(InterpolatorType.fromString("easeInEaseOut")).isEqualTo(InterpolatorType.EASE_IN_EASE_OUT); + assertThat(InterpolatorType.fromString("easeInEaseOut")) + .isEqualTo(InterpolatorType.EASE_IN_EASE_OUT); } @Test(expected = IllegalArgumentException.class) diff --git a/ReactAndroid/src/test/java/com/facebook/react/util/JSStackTraceTest.java b/ReactAndroid/src/test/java/com/facebook/react/util/JSStackTraceTest.java index d614cee9849..fdcacc37cf3 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/util/JSStackTraceTest.java +++ b/ReactAndroid/src/test/java/com/facebook/react/util/JSStackTraceTest.java @@ -1,40 +1,95 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.util; -import org.junit.Test; -import org.junit.Assert; -import com.facebook.react.bridge.JavaOnlyMap; import com.facebook.react.bridge.JavaOnlyArray; +import com.facebook.react.bridge.JavaOnlyMap; +import org.junit.Assert; +import org.junit.Test; public class JSStackTraceTest { @Test public void testSymbolication() { - JavaOnlyArray values = JavaOnlyArray.of( - JavaOnlyMap.of("methodName", "method_from_bundle", "column", 11, "lineNumber", 7, "file", "Fb4aBundle.js"), - JavaOnlyMap.of("methodName", "method_from_ram_bundle", "column", 13, "lineNumber", 18, "file", "199.js"), - JavaOnlyMap.of("methodName", "method_from_ram_bundle_with_address", "column", 13, "lineNumber", 18, "file", "address at 199.js"), - JavaOnlyMap.of("methodName", "method_from_segment", "column", 18, "lineNumber", 9, "file", "seg-1.js"), - JavaOnlyMap.of("methodName", "method_from_segment_with_address", "column", 18, "lineNumber", 9, "file", "address at seg-1.js"), - JavaOnlyMap.of("methodName", "method_from_ram_segment", "column", 20, "lineNumber", 10, "file", "seg-3_198.js"), - JavaOnlyMap.of("methodName", "method_from_ram_segment_with_address", "column", 20, "lineNumber", 10, "file", "address at seg-3_198.js") - ); + JavaOnlyArray values = + JavaOnlyArray.of( + JavaOnlyMap.of( + "methodName", + "method_from_bundle", + "column", + 11, + "lineNumber", + 7, + "file", + "Fb4aBundle.js"), + JavaOnlyMap.of( + "methodName", + "method_from_ram_bundle", + "column", + 13, + "lineNumber", + 18, + "file", + "199.js"), + JavaOnlyMap.of( + "methodName", + "method_from_ram_bundle_with_address", + "column", + 13, + "lineNumber", + 18, + "file", + "address at 199.js"), + JavaOnlyMap.of( + "methodName", + "method_from_segment", + "column", + 18, + "lineNumber", + 9, + "file", + "seg-1.js"), + JavaOnlyMap.of( + "methodName", + "method_from_segment_with_address", + "column", + 18, + "lineNumber", + 9, + "file", + "address at seg-1.js"), + JavaOnlyMap.of( + "methodName", + "method_from_ram_segment", + "column", + 20, + "lineNumber", + 10, + "file", + "seg-3_198.js"), + JavaOnlyMap.of( + "methodName", + "method_from_ram_segment_with_address", + "column", + 20, + "lineNumber", + 10, + "file", + "address at seg-3_198.js")); String message = JSStackTrace.format("Error", values); - Assert.assertEquals(message, "Error, stack:\n" - + "method_from_bundle@7:11\n" - + "method_from_ram_bundle@199.js:18:13\n" - + "method_from_ram_bundle_with_address@199.js:18:13\n" - + "method_from_segment@seg-1.js:9:18\n" - + "method_from_segment_with_address@seg-1.js:9:18\n" - + "method_from_ram_segment@seg-3_198.js:10:20\n" - + "method_from_ram_segment_with_address@seg-3_198.js:10:20\n" - ); + Assert.assertEquals( + message, + "Error, stack:\n" + + "method_from_bundle@7:11\n" + + "method_from_ram_bundle@199.js:18:13\n" + + "method_from_ram_bundle_with_address@199.js:18:13\n" + + "method_from_segment@seg-1.js:9:18\n" + + "method_from_segment_with_address@seg-1.js:9:18\n" + + "method_from_ram_segment@seg-3_198.js:10:20\n" + + "method_from_ram_segment_with_address@seg-3_198.js:10:20\n"); } - } diff --git a/ReactAndroid/src/test/java/com/facebook/react/views/image/ImageResizeModeTest.java b/ReactAndroid/src/test/java/com/facebook/react/views/image/ImageResizeModeTest.java index 6bcf6263d51..dd1009d353f 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/views/image/ImageResizeModeTest.java +++ b/ReactAndroid/src/test/java/com/facebook/react/views/image/ImageResizeModeTest.java @@ -1,50 +1,41 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.image; -import com.facebook.drawee.drawable.ScalingUtils; +import static org.fest.assertions.api.Assertions.assertThat; +import com.facebook.drawee.drawable.ScalingUtils; import org.junit.Rule; -import org.junit.runner.RunWith; import org.junit.Test; +import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.modules.junit4.rule.PowerMockRule; import org.robolectric.RobolectricTestRunner; -import org.robolectric.RuntimeEnvironment; - -import static org.fest.assertions.api.Assertions.assertThat; @RunWith(RobolectricTestRunner.class) @PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "androidx.*", "android.*"}) public class ImageResizeModeTest { - @Rule - public PowerMockRule rule = new PowerMockRule(); + @Rule public PowerMockRule rule = new PowerMockRule(); @Test public void testImageResizeMode() { - assertThat(ImageResizeMode.toScaleType(null)) - .isEqualTo(ScalingUtils.ScaleType.CENTER_CROP); + assertThat(ImageResizeMode.toScaleType(null)).isEqualTo(ScalingUtils.ScaleType.CENTER_CROP); - assertThat(ImageResizeMode.toScaleType("contain")) - .isEqualTo(ScalingUtils.ScaleType.FIT_CENTER); + assertThat(ImageResizeMode.toScaleType("contain")).isEqualTo(ScalingUtils.ScaleType.FIT_CENTER); - assertThat(ImageResizeMode.toScaleType("cover")) - .isEqualTo(ScalingUtils.ScaleType.CENTER_CROP); + assertThat(ImageResizeMode.toScaleType("cover")).isEqualTo(ScalingUtils.ScaleType.CENTER_CROP); - assertThat(ImageResizeMode.toScaleType("stretch")) - .isEqualTo(ScalingUtils.ScaleType.FIT_XY); + assertThat(ImageResizeMode.toScaleType("stretch")).isEqualTo(ScalingUtils.ScaleType.FIT_XY); assertThat(ImageResizeMode.toScaleType("center")) .isEqualTo(ScalingUtils.ScaleType.CENTER_INSIDE); // No resizeMode set - assertThat(ImageResizeMode.defaultValue()) - .isEqualTo(ScalingUtils.ScaleType.CENTER_CROP); + assertThat(ImageResizeMode.defaultValue()).isEqualTo(ScalingUtils.ScaleType.CENTER_CROP); } } diff --git a/ReactAndroid/src/test/java/com/facebook/react/views/image/ReactImagePropertyTest.java b/ReactAndroid/src/test/java/com/facebook/react/views/image/ReactImagePropertyTest.java index 95f4bd371d0..2917b523cc3 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/views/image/ReactImagePropertyTest.java +++ b/ReactAndroid/src/test/java/com/facebook/react/views/image/ReactImagePropertyTest.java @@ -1,52 +1,47 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.image; -import android.graphics.Color; -import android.util.DisplayMetrics; - -import com.facebook.drawee.backends.pipeline.Fresco; -import com.facebook.react.bridge.CatalystInstance; -import com.facebook.react.bridge.JavaOnlyArray; -import com.facebook.react.bridge.ReactTestHelper; -import com.facebook.react.bridge.JSApplicationIllegalArgumentException; -import com.facebook.react.bridge.ReactApplicationContext; -import com.facebook.react.bridge.JavaOnlyMap; -import com.facebook.react.uimanager.ReactStylesDiffMap; -import com.facebook.react.uimanager.DisplayMetricsHolder; -import com.facebook.react.uimanager.ThemedReactContext; -import com.facebook.soloader.SoLoader; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.Rule; -import org.junit.runner.RunWith; -import org.powermock.modules.junit4.rule.PowerMockRule; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.robolectric.RobolectricTestRunner; -import org.robolectric.RuntimeEnvironment; -import org.robolectric.Robolectric; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; +import android.graphics.Color; +import android.util.DisplayMetrics; +import com.facebook.drawee.backends.pipeline.Fresco; +import com.facebook.react.bridge.CatalystInstance; +import com.facebook.react.bridge.JSApplicationIllegalArgumentException; +import com.facebook.react.bridge.JavaOnlyArray; +import com.facebook.react.bridge.JavaOnlyMap; +import com.facebook.react.bridge.ReactApplicationContext; +import com.facebook.react.bridge.ReactTestHelper; +import com.facebook.react.uimanager.DisplayMetricsHolder; +import com.facebook.react.uimanager.ReactStylesDiffMap; +import com.facebook.react.uimanager.ThemedReactContext; +import com.facebook.soloader.SoLoader; +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.modules.junit4.rule.PowerMockRule; +import org.robolectric.RobolectricTestRunner; +import org.robolectric.RuntimeEnvironment; + /** - * Verify that {@link ScalingUtils} properties are being applied correctly - * by {@link ReactImageManager}. + * Verify that {@link ScalingUtils} properties are being applied correctly by {@link + * ReactImageManager}. */ @RunWith(RobolectricTestRunner.class) @PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "androidx.*", "android.*"}) public class ReactImagePropertyTest { - @Rule - public PowerMockRule rule = new PowerMockRule(); + @Rule public PowerMockRule rule = new PowerMockRule(); private ReactApplicationContext mContext; private CatalystInstance mCatalystInstanceMock; @@ -72,7 +67,7 @@ public class ReactImagePropertyTest { return new ReactStylesDiffMap(JavaOnlyMap.of(keysAndValues)); } - @Test(expected=JSApplicationIllegalArgumentException.class) + @Test(expected = JSApplicationIllegalArgumentException.class) public void testImageInvalidResizeMode() { ReactImageManager viewManager = new ReactImageManager(); ReactImageView view = viewManager.createViewInstance(mThemeContext); @@ -84,8 +79,8 @@ public class ReactImagePropertyTest { ReactImageManager viewManager = new ReactImageManager(); ReactImageView view = viewManager.createViewInstance(mThemeContext); viewManager.updateProperties( - view, - buildStyles("src", JavaOnlyArray.of(JavaOnlyMap.of("uri", "http://mysite.com/mypic.jpg")))); + view, + buildStyles("src", JavaOnlyArray.of(JavaOnlyMap.of("uri", "http://mysite.com/mypic.jpg")))); viewManager.updateProperties(view, buildStyles("borderColor", Color.argb(0, 0, 255, 255))); int borderColor = view.getHierarchy().getRoundingParams().getBorderColor(); @@ -114,8 +109,8 @@ public class ReactImagePropertyTest { ReactImageManager viewManager = new ReactImageManager(); ReactImageView view = viewManager.createViewInstance(mThemeContext); viewManager.updateProperties( - view, - buildStyles("src", JavaOnlyArray.of(JavaOnlyMap.of("uri", "http://mysite.com/mypic.jpg")))); + view, + buildStyles("src", JavaOnlyArray.of(JavaOnlyMap.of("uri", "http://mysite.com/mypic.jpg")))); // We can't easily verify if rounded corner was honored or not, this tests simply verifies // we're not crashing.. @@ -130,9 +125,9 @@ public class ReactImagePropertyTest { ReactImageView view = viewManager.createViewInstance(mThemeContext); assertNull(view.getColorFilter()); viewManager.updateProperties(view, buildStyles("tintColor", Color.argb(50, 0, 0, 255))); - // Can't actually assert the specific color so this is the next best thing. - // Does the color filter now exist? - assertNotNull(view.getColorFilter()); + // Can't actually assert the specific color so this is the next best thing. + // Does the color filter now exist? + assertNotNull(view.getColorFilter()); viewManager.updateProperties(view, buildStyles("tintColor", null)); assertNull(view.getColorFilter()); } diff --git a/ReactAndroid/src/test/java/com/facebook/react/views/slider/ReactSliderPropertyTest.java b/ReactAndroid/src/test/java/com/facebook/react/views/slider/ReactSliderPropertyTest.java index ddae7def15b..6d986579473 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/views/slider/ReactSliderPropertyTest.java +++ b/ReactAndroid/src/test/java/com/facebook/react/views/slider/ReactSliderPropertyTest.java @@ -1,12 +1,13 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.slider; +import static org.fest.assertions.api.Assertions.assertThat; + import android.widget.SeekBar; import com.facebook.react.bridge.CatalystInstance; import com.facebook.react.bridge.JavaOnlyMap; @@ -23,17 +24,12 @@ import org.powermock.modules.junit4.rule.PowerMockRule; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; -import static org.fest.assertions.api.Assertions.assertThat; - -/** - * Verify {@link SeekBar} view property being applied properly by {@link ReactSliderManager} - */ +/** Verify {@link SeekBar} view property being applied properly by {@link ReactSliderManager} */ @RunWith(RobolectricTestRunner.class) @PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "androidx.*", "android.*"}) public class ReactSliderPropertyTest { - @Rule - public PowerMockRule rule = new PowerMockRule(); + @Rule public PowerMockRule rule = new PowerMockRule(); private ThemedReactContext mThemedContext; private ReactSliderManager mManager; diff --git a/ReactAndroid/src/test/java/com/facebook/react/views/text/CustomLineHeightSpanTest.java b/ReactAndroid/src/test/java/com/facebook/react/views/text/CustomLineHeightSpanTest.java index 062ef8d0b90..d143e2d798e 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/views/text/CustomLineHeightSpanTest.java +++ b/ReactAndroid/src/test/java/com/facebook/react/views/text/CustomLineHeightSpanTest.java @@ -1,15 +1,14 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.text; -import android.graphics.Paint; - import static org.fest.assertions.api.Assertions.assertThat; + +import android.graphics.Paint; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PowerMockIgnore; diff --git a/ReactAndroid/src/test/java/com/facebook/react/views/text/ReactTextTest.java b/ReactAndroid/src/test/java/com/facebook/react/views/text/ReactTextTest.java index e8543d22f5a..9874b928d69 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/views/text/ReactTextTest.java +++ b/ReactAndroid/src/test/java/com/facebook/react/views/text/ReactTextTest.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.text; import static org.fest.assertions.api.Assertions.assertThat; @@ -33,9 +32,7 @@ import com.facebook.react.modules.core.ReactChoreographer; import com.facebook.react.uimanager.UIManagerModule; import com.facebook.react.uimanager.ViewManager; import com.facebook.react.uimanager.ViewProps; -import com.facebook.react.views.text.ReactRawTextShadowNode; import com.facebook.react.views.view.ReactViewBackgroundDrawable; -import com.facebook.react.views.text.CustomTextTransformSpan; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -52,16 +49,13 @@ import org.powermock.modules.junit4.rule.PowerMockRule; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; -/** - * Tests for {@link UIManagerModule} specifically for React Text/RawText. - */ +/** Tests for {@link UIManagerModule} specifically for React Text/RawText. */ @PrepareForTest({Arguments.class, ReactChoreographer.class}) @RunWith(RobolectricTestRunner.class) @PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "androidx.*", "android.*"}) public class ReactTextTest { - @Rule - public PowerMockRule rule = new PowerMockRule(); + @Rule public PowerMockRule rule = new PowerMockRule(); private ArrayList mPendingFrameCallbacks; @@ -70,38 +64,44 @@ public class ReactTextTest { PowerMockito.mockStatic(Arguments.class, ReactChoreographer.class); ReactChoreographer uiDriverMock = mock(ReactChoreographer.class); - PowerMockito.when(Arguments.createMap()).thenAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - return new JavaOnlyMap(); - } - }); + PowerMockito.when(Arguments.createMap()) + .thenAnswer( + new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + return new JavaOnlyMap(); + } + }); PowerMockito.when(ReactChoreographer.getInstance()).thenReturn(uiDriverMock); mPendingFrameCallbacks = new ArrayList<>(); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - mPendingFrameCallbacks - .add((ChoreographerCompat.FrameCallback) invocation.getArguments()[1]); - return null; - } - }).when(uiDriverMock).postFrameCallback( - any(ReactChoreographer.CallbackType.class), - any(ChoreographerCompat.FrameCallback.class)); + doAnswer( + new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + mPendingFrameCallbacks.add( + (ChoreographerCompat.FrameCallback) invocation.getArguments()[1]); + return null; + } + }) + .when(uiDriverMock) + .postFrameCallback( + any(ReactChoreographer.CallbackType.class), + any(ChoreographerCompat.FrameCallback.class)); } @Test public void testFontSizeApplied() { UIManagerModule uiManager = getUIManagerModule(); - ReactRootView rootView = createText( - uiManager, - JavaOnlyMap.of(ViewProps.FONT_SIZE, 21.0), - JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, "test text")); + ReactRootView rootView = + createText( + uiManager, + JavaOnlyMap.of(ViewProps.FONT_SIZE, 21.0), + JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, "test text")); - AbsoluteSizeSpan sizeSpan = getSingleSpan( - (TextView) rootView.getChildAt(0), AbsoluteSizeSpan.class); + AbsoluteSizeSpan sizeSpan = + getSingleSpan((TextView) rootView.getChildAt(0), AbsoluteSizeSpan.class); assertThat(sizeSpan.getSize()).isEqualTo(21); } @@ -109,10 +109,11 @@ public class ReactTextTest { public void testBoldFontApplied() { UIManagerModule uiManager = getUIManagerModule(); - ReactRootView rootView = createText( - uiManager, - JavaOnlyMap.of(ViewProps.FONT_WEIGHT, "bold"), - JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, "test text")); + ReactRootView rootView = + createText( + uiManager, + JavaOnlyMap.of(ViewProps.FONT_WEIGHT, "bold"), + JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, "test text")); CustomStyleSpan customStyleSpan = getSingleSpan((TextView) rootView.getChildAt(0), CustomStyleSpan.class); @@ -124,10 +125,11 @@ public class ReactTextTest { public void testNumericBoldFontApplied() { UIManagerModule uiManager = getUIManagerModule(); - ReactRootView rootView = createText( - uiManager, - JavaOnlyMap.of(ViewProps.FONT_WEIGHT, "500"), - JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, "test text")); + ReactRootView rootView = + createText( + uiManager, + JavaOnlyMap.of(ViewProps.FONT_WEIGHT, "500"), + JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, "test text")); CustomStyleSpan customStyleSpan = getSingleSpan((TextView) rootView.getChildAt(0), CustomStyleSpan.class); @@ -139,10 +141,11 @@ public class ReactTextTest { public void testItalicFontApplied() { UIManagerModule uiManager = getUIManagerModule(); - ReactRootView rootView = createText( - uiManager, - JavaOnlyMap.of(ViewProps.FONT_STYLE, "italic"), - JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, "test text")); + ReactRootView rootView = + createText( + uiManager, + JavaOnlyMap.of(ViewProps.FONT_STYLE, "italic"), + JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, "test text")); CustomStyleSpan customStyleSpan = getSingleSpan((TextView) rootView.getChildAt(0), CustomStyleSpan.class); @@ -154,10 +157,11 @@ public class ReactTextTest { public void testBoldItalicFontApplied() { UIManagerModule uiManager = getUIManagerModule(); - ReactRootView rootView = createText( - uiManager, - JavaOnlyMap.of(ViewProps.FONT_WEIGHT, "bold", ViewProps.FONT_STYLE, "italic"), - JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, "test text")); + ReactRootView rootView = + createText( + uiManager, + JavaOnlyMap.of(ViewProps.FONT_WEIGHT, "bold", ViewProps.FONT_STYLE, "italic"), + JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, "test text")); CustomStyleSpan customStyleSpan = getSingleSpan((TextView) rootView.getChildAt(0), CustomStyleSpan.class); @@ -169,10 +173,11 @@ public class ReactTextTest { public void testNormalFontWeightApplied() { UIManagerModule uiManager = getUIManagerModule(); - ReactRootView rootView = createText( - uiManager, - JavaOnlyMap.of(ViewProps.FONT_WEIGHT, "normal"), - JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, "test text")); + ReactRootView rootView = + createText( + uiManager, + JavaOnlyMap.of(ViewProps.FONT_WEIGHT, "normal"), + JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, "test text")); CustomStyleSpan customStyleSpan = getSingleSpan((TextView) rootView.getChildAt(0), CustomStyleSpan.class); @@ -183,10 +188,11 @@ public class ReactTextTest { public void testNumericNormalFontWeightApplied() { UIManagerModule uiManager = getUIManagerModule(); - ReactRootView rootView = createText( - uiManager, - JavaOnlyMap.of(ViewProps.FONT_WEIGHT, "200"), - JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, "test text")); + ReactRootView rootView = + createText( + uiManager, + JavaOnlyMap.of(ViewProps.FONT_WEIGHT, "200"), + JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, "test text")); CustomStyleSpan customStyleSpan = getSingleSpan((TextView) rootView.getChildAt(0), CustomStyleSpan.class); @@ -197,10 +203,11 @@ public class ReactTextTest { public void testNormalFontStyleApplied() { UIManagerModule uiManager = getUIManagerModule(); - ReactRootView rootView = createText( - uiManager, - JavaOnlyMap.of(ViewProps.FONT_STYLE, "normal"), - JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, "test text")); + ReactRootView rootView = + createText( + uiManager, + JavaOnlyMap.of(ViewProps.FONT_STYLE, "normal"), + JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, "test text")); CustomStyleSpan customStyleSpan = getSingleSpan((TextView) rootView.getChildAt(0), CustomStyleSpan.class); @@ -211,10 +218,11 @@ public class ReactTextTest { public void testFontFamilyStyleApplied() { UIManagerModule uiManager = getUIManagerModule(); - ReactRootView rootView = createText( - uiManager, - JavaOnlyMap.of(ViewProps.FONT_FAMILY, "sans-serif"), - JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, "test text")); + ReactRootView rootView = + createText( + uiManager, + JavaOnlyMap.of(ViewProps.FONT_FAMILY, "sans-serif"), + JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, "test text")); CustomStyleSpan customStyleSpan = getSingleSpan((TextView) rootView.getChildAt(0), CustomStyleSpan.class); @@ -227,10 +235,11 @@ public class ReactTextTest { public void testFontFamilyBoldStyleApplied() { UIManagerModule uiManager = getUIManagerModule(); - ReactRootView rootView = createText( - uiManager, - JavaOnlyMap.of(ViewProps.FONT_FAMILY, "sans-serif", ViewProps.FONT_WEIGHT, "bold"), - JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, "test text")); + ReactRootView rootView = + createText( + uiManager, + JavaOnlyMap.of(ViewProps.FONT_FAMILY, "sans-serif", ViewProps.FONT_WEIGHT, "bold"), + JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, "test text")); CustomStyleSpan customStyleSpan = getSingleSpan((TextView) rootView.getChildAt(0), CustomStyleSpan.class); @@ -243,10 +252,11 @@ public class ReactTextTest { public void testFontFamilyItalicStyleApplied() { UIManagerModule uiManager = getUIManagerModule(); - ReactRootView rootView = createText( - uiManager, - JavaOnlyMap.of(ViewProps.FONT_FAMILY, "sans-serif", ViewProps.FONT_STYLE, "italic"), - JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, "test text")); + ReactRootView rootView = + createText( + uiManager, + JavaOnlyMap.of(ViewProps.FONT_FAMILY, "sans-serif", ViewProps.FONT_STYLE, "italic"), + JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, "test text")); CustomStyleSpan customStyleSpan = getSingleSpan((TextView) rootView.getChildAt(0), CustomStyleSpan.class); @@ -259,13 +269,14 @@ public class ReactTextTest { public void testFontFamilyBoldItalicStyleApplied() { UIManagerModule uiManager = getUIManagerModule(); - ReactRootView rootView = createText( - uiManager, - JavaOnlyMap.of( - ViewProps.FONT_FAMILY, "sans-serif", - ViewProps.FONT_WEIGHT, "500", - ViewProps.FONT_STYLE, "italic"), - JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, "test text")); + ReactRootView rootView = + createText( + uiManager, + JavaOnlyMap.of( + ViewProps.FONT_FAMILY, "sans-serif", + ViewProps.FONT_WEIGHT, "500", + ViewProps.FONT_STYLE, "italic"), + JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, "test text")); CustomStyleSpan customStyleSpan = getSingleSpan((TextView) rootView.getChildAt(0), CustomStyleSpan.class); @@ -278,10 +289,11 @@ public class ReactTextTest { public void testTextDecorationLineUnderlineApplied() { UIManagerModule uiManager = getUIManagerModule(); - ReactRootView rootView = createText( - uiManager, - JavaOnlyMap.of(ViewProps.TEXT_DECORATION_LINE, "underline"), - JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, "test text")); + ReactRootView rootView = + createText( + uiManager, + JavaOnlyMap.of(ViewProps.TEXT_DECORATION_LINE, "underline"), + JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, "test text")); TextView textView = (TextView) rootView.getChildAt(0); Spanned text = (Spanned) textView.getText(); @@ -296,17 +308,16 @@ public class ReactTextTest { public void testTextDecorationLineLineThroughApplied() { UIManagerModule uiManager = getUIManagerModule(); - ReactRootView rootView = createText( - uiManager, - JavaOnlyMap.of(ViewProps.TEXT_DECORATION_LINE, "line-through"), - JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, "test text")); + ReactRootView rootView = + createText( + uiManager, + JavaOnlyMap.of(ViewProps.TEXT_DECORATION_LINE, "line-through"), + JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, "test text")); TextView textView = (TextView) rootView.getChildAt(0); Spanned text = (Spanned) textView.getText(); - UnderlineSpan[] underlineSpans = - text.getSpans(0, text.length(), UnderlineSpan.class); - StrikethroughSpan strikeThroughSpan = - getSingleSpan(textView, StrikethroughSpan.class); + UnderlineSpan[] underlineSpans = text.getSpans(0, text.length(), UnderlineSpan.class); + StrikethroughSpan strikeThroughSpan = getSingleSpan(textView, StrikethroughSpan.class); assertThat(underlineSpans).hasSize(0); assertThat(strikeThroughSpan instanceof StrikethroughSpan).isTrue(); } @@ -315,10 +326,11 @@ public class ReactTextTest { public void testTextDecorationLineUnderlineLineThroughApplied() { UIManagerModule uiManager = getUIManagerModule(); - ReactRootView rootView = createText( - uiManager, - JavaOnlyMap.of(ViewProps.TEXT_DECORATION_LINE, "underline line-through"), - JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, "test text")); + ReactRootView rootView = + createText( + uiManager, + JavaOnlyMap.of(ViewProps.TEXT_DECORATION_LINE, "underline line-through"), + JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, "test text")); UnderlineSpan underlineSpan = getSingleSpan((TextView) rootView.getChildAt(0), UnderlineSpan.class); @@ -332,10 +344,11 @@ public class ReactTextTest { public void testBackgroundColorStyleApplied() { UIManagerModule uiManager = getUIManagerModule(); - ReactRootView rootView = createText( - uiManager, - JavaOnlyMap.of(ViewProps.BACKGROUND_COLOR, Color.BLUE), - JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, "test text")); + ReactRootView rootView = + createText( + uiManager, + JavaOnlyMap.of(ViewProps.BACKGROUND_COLOR, Color.BLUE), + JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, "test text")); Drawable backgroundDrawable = ((TextView) rootView.getChildAt(0)).getBackground(); assertThat(((ReactViewBackgroundDrawable) backgroundDrawable).getColor()).isEqualTo(Color.BLUE); @@ -345,13 +358,15 @@ public class ReactTextTest { public void testTextTransformNoneApplied() { UIManagerModule uiManager = getUIManagerModule(); - String testTextEntered = ".aa\tbb\t\tcc dd EE \r\nZZ I like to eat apples. \n中文éé 我喜欢吃苹果。awdawd "; + String testTextEntered = + ".aa\tbb\t\tcc dd EE \r\nZZ I like to eat apples. \n中文éé 我喜欢吃苹果。awdawd "; String testTextTransformed = testTextEntered; - ReactRootView rootView = createText( - uiManager, - JavaOnlyMap.of("textTransform", "none"), - JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, testTextEntered)); + ReactRootView rootView = + createText( + uiManager, + JavaOnlyMap.of("textTransform", "none"), + JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, testTextEntered)); TextView textView = (TextView) rootView.getChildAt(0); assertThat(textView.getText().toString()).isEqualTo(testTextTransformed); @@ -361,13 +376,16 @@ public class ReactTextTest { public void testTextTransformUppercaseApplied() { UIManagerModule uiManager = getUIManagerModule(); - String testTextEntered = ".aa\tbb\t\tcc dd EE \r\nZZ I like to eat apples. \n中文éé 我喜欢吃苹果。awdawd "; - String testTextTransformed = ".AA\tBB\t\tCC DD EE \r\nZZ I LIKE TO EAT APPLES. \n中文ÉÉ 我喜欢吃苹果。AWDAWD "; + String testTextEntered = + ".aa\tbb\t\tcc dd EE \r\nZZ I like to eat apples. \n中文éé 我喜欢吃苹果。awdawd "; + String testTextTransformed = + ".AA\tBB\t\tCC DD EE \r\nZZ I LIKE TO EAT APPLES. \n中文ÉÉ 我喜欢吃苹果。AWDAWD "; - ReactRootView rootView = createText( - uiManager, - JavaOnlyMap.of("textTransform", "uppercase"), - JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, testTextEntered)); + ReactRootView rootView = + createText( + uiManager, + JavaOnlyMap.of("textTransform", "uppercase"), + JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, testTextEntered)); TextView textView = (TextView) rootView.getChildAt(0); assertThat(textView.getText().toString()).isEqualTo(testTextTransformed); @@ -377,13 +395,16 @@ public class ReactTextTest { public void testTextTransformLowercaseApplied() { UIManagerModule uiManager = getUIManagerModule(); - String testTextEntered = ".aa\tbb\t\tcc dd EE \r\nZZ I like to eat apples. \n中文éé 我喜欢吃苹果。awdawd "; - String testTextTransformed = ".aa\tbb\t\tcc dd ee \r\nzz i like to eat apples. \n中文éé 我喜欢吃苹果。awdawd "; + String testTextEntered = + ".aa\tbb\t\tcc dd EE \r\nZZ I like to eat apples. \n中文éé 我喜欢吃苹果。awdawd "; + String testTextTransformed = + ".aa\tbb\t\tcc dd ee \r\nzz i like to eat apples. \n中文éé 我喜欢吃苹果。awdawd "; - ReactRootView rootView = createText( - uiManager, - JavaOnlyMap.of("textTransform", "lowercase"), - JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, testTextEntered)); + ReactRootView rootView = + createText( + uiManager, + JavaOnlyMap.of("textTransform", "lowercase"), + JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, testTextEntered)); TextView textView = (TextView) rootView.getChildAt(0); assertThat(textView.getText().toString()).isEqualTo(testTextTransformed); @@ -393,13 +414,16 @@ public class ReactTextTest { public void testTextTransformCapitalizeApplied() { UIManagerModule uiManager = getUIManagerModule(); - String testTextEntered = ".aa\tbb\t\tcc dd EE \r\nZZ I like to eat apples. \n中文éé 我喜欢吃苹果。awdawd "; - String testTextTransformed = ".Aa\tBb\t\tCc Dd Ee \r\nZz I Like To Eat Apples. \n中文Éé 我喜欢吃苹果。Awdawd "; + String testTextEntered = + ".aa\tbb\t\tcc dd EE \r\nZZ I like to eat apples. \n中文éé 我喜欢吃苹果。awdawd "; + String testTextTransformed = + ".Aa\tBb\t\tCc Dd Ee \r\nZz I Like To Eat Apples. \n中文Éé 我喜欢吃苹果。Awdawd "; - ReactRootView rootView = createText( - uiManager, - JavaOnlyMap.of("textTransform", "capitalize"), - JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, testTextEntered)); + ReactRootView rootView = + createText( + uiManager, + JavaOnlyMap.of("textTransform", "capitalize"), + JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, testTextEntered)); TextView textView = (TextView) rootView.getChildAt(0); assertThat(textView.getText().toString()).isEqualTo(testTextTransformed); @@ -409,10 +433,11 @@ public class ReactTextTest { public void testMaxLinesApplied() { UIManagerModule uiManager = getUIManagerModule(); - ReactRootView rootView = createText( - uiManager, - JavaOnlyMap.of(ViewProps.NUMBER_OF_LINES, 2), - JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, "test text")); + ReactRootView rootView = + createText( + uiManager, + JavaOnlyMap.of(ViewProps.NUMBER_OF_LINES, 2), + JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, "test text")); TextView textView = (TextView) rootView.getChildAt(0); assertThat(textView.getText().toString()).isEqualTo("test text"); @@ -425,7 +450,8 @@ public class ReactTextTest { public void testTextAlignJustifyApplied() { UIManagerModule uiManager = getUIManagerModule(); - ReactRootView rootView = createText( + ReactRootView rootView = + createText( uiManager, JavaOnlyMap.of("textAlign", "justify"), JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, "test text")); @@ -435,9 +461,7 @@ public class ReactTextTest { assertThat(textView.getJustificationMode()).isEqualTo(Layout.JUSTIFICATION_MODE_INTER_WORD); } - /** - * Make sure TextView has exactly one span and that span has given type. - */ + /** Make sure TextView has exactly one span and that span has given type. */ private static TSPAN getSingleSpan(TextView textView, Class spanClass) { Spanned text = (Spanned) textView.getText(); TSPAN[] spans = text.getSpans(0, text.length(), spanClass); @@ -446,40 +470,20 @@ public class ReactTextTest { } private ReactRootView createText( - UIManagerModule uiManager, - JavaOnlyMap textProps, - JavaOnlyMap rawTextProps) { + UIManagerModule uiManager, JavaOnlyMap textProps, JavaOnlyMap rawTextProps) { ReactRootView rootView = new ReactRootView(RuntimeEnvironment.application); int rootTag = uiManager.addRootView(rootView); int textTag = rootTag + 1; int rawTextTag = textTag + 1; - uiManager.createView( - textTag, - ReactTextViewManager.REACT_CLASS, - rootTag, - textProps); - uiManager.createView( - rawTextTag, - ReactRawTextManager.REACT_CLASS, - rootTag, - rawTextProps); + uiManager.createView(textTag, ReactTextViewManager.REACT_CLASS, rootTag, textProps); + uiManager.createView(rawTextTag, ReactRawTextManager.REACT_CLASS, rootTag, rawTextProps); uiManager.manageChildren( - textTag, - null, - null, - JavaOnlyArray.of(rawTextTag), - JavaOnlyArray.of(0), - null); + textTag, null, null, JavaOnlyArray.of(rawTextTag), JavaOnlyArray.of(0), null); uiManager.manageChildren( - rootTag, - null, - null, - JavaOnlyArray.of(textTag), - JavaOnlyArray.of(0), - null); + rootTag, null, null, JavaOnlyArray.of(textTag), JavaOnlyArray.of(0), null); uiManager.onBatchComplete(); executePendingFrameCallbacks(); @@ -497,13 +501,12 @@ public class ReactTextTest { public UIManagerModule getUIManagerModule() { ReactApplicationContext reactContext = ReactTestHelper.createCatalystContextForTest(); - List viewManagers = Arrays.asList( - new ViewManager[] { - new ReactTextViewManager(), - new ReactRawTextManager(), - }); - UIManagerModule uiManagerModule = - new UIManagerModule(reactContext, viewManagers, 0); + List viewManagers = + Arrays.asList( + new ViewManager[] { + new ReactTextViewManager(), new ReactRawTextManager(), + }); + UIManagerModule uiManagerModule = new UIManagerModule(reactContext, viewManagers, 0); uiManagerModule.onHostResume(); return uiManagerModule; } diff --git a/ReactAndroid/src/test/java/com/facebook/react/views/textinput/ReactTextInputPropertyTest.java b/ReactAndroid/src/test/java/com/facebook/react/views/textinput/ReactTextInputPropertyTest.java index f6495494c21..ad07df70721 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/views/textinput/ReactTextInputPropertyTest.java +++ b/ReactAndroid/src/test/java/com/facebook/react/views/textinput/ReactTextInputPropertyTest.java @@ -1,54 +1,46 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.textinput; +import static org.fest.assertions.api.Assertions.assertThat; + import android.content.res.ColorStateList; import android.graphics.Color; import android.os.Build; -import android.text.InputType; import android.text.InputFilter; +import android.text.InputType; import android.text.Layout; import android.util.DisplayMetrics; import android.view.Gravity; import android.view.inputmethod.EditorInfo; import android.widget.EditText; - import com.facebook.react.bridge.CatalystInstance; -import com.facebook.react.bridge.ReactTestHelper; -import com.facebook.react.bridge.ReactApplicationContext; -import com.facebook.react.bridge.JSApplicationCausedNativeException; import com.facebook.react.bridge.JavaOnlyMap; -import com.facebook.react.uimanager.ReactStylesDiffMap; +import com.facebook.react.bridge.ReactApplicationContext; +import com.facebook.react.bridge.ReactTestHelper; import com.facebook.react.uimanager.DisplayMetricsHolder; -import com.facebook.react.views.text.DefaultStyleValuesUtil; +import com.facebook.react.uimanager.ReactStylesDiffMap; import com.facebook.react.uimanager.ThemedReactContext; - +import com.facebook.react.views.text.DefaultStyleValuesUtil; import org.junit.Before; -import org.junit.Test; import org.junit.Rule; +import org.junit.Test; import org.junit.runner.RunWith; -import org.robolectric.Robolectric; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.modules.junit4.rule.PowerMockRule; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; -import org.powermock.modules.junit4.rule.PowerMockRule; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import static org.fest.assertions.api.Assertions.assertThat; - -/** - * Verify {@link EditText} view property being applied properly by {@link ReactTextInputManager} - */ +/** Verify {@link EditText} view property being applied properly by {@link ReactTextInputManager} */ @RunWith(RobolectricTestRunner.class) @PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "androidx.*", "android.*"}) public class ReactTextInputPropertyTest { - @Rule - public PowerMockRule rule = new PowerMockRule(); + @Rule public PowerMockRule rule = new PowerMockRule(); private ReactApplicationContext mContext; private CatalystInstance mCatalystInstanceMock; @@ -100,29 +92,24 @@ public class ReactTextInputPropertyTest { assertThat(view.getInputType() & InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS).isZero(); mManager.updateProperties( - view, - buildStyles("autoCapitalize", InputType.TYPE_TEXT_FLAG_CAP_SENTENCES)); + view, buildStyles("autoCapitalize", InputType.TYPE_TEXT_FLAG_CAP_SENTENCES)); assertThat(view.getInputType() & InputType.TYPE_TEXT_FLAG_CAP_SENTENCES).isNotZero(); assertThat(view.getInputType() & InputType.TYPE_TEXT_FLAG_CAP_WORDS).isZero(); assertThat(view.getInputType() & InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS).isZero(); mManager.updateProperties( - view, - buildStyles("autoCapitalize", InputType.TYPE_TEXT_FLAG_CAP_WORDS)); + view, buildStyles("autoCapitalize", InputType.TYPE_TEXT_FLAG_CAP_WORDS)); assertThat(view.getInputType() & InputType.TYPE_TEXT_FLAG_CAP_SENTENCES).isZero(); assertThat(view.getInputType() & InputType.TYPE_TEXT_FLAG_CAP_WORDS).isNotZero(); assertThat(view.getInputType() & InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS).isZero(); mManager.updateProperties( - view, - buildStyles("autoCapitalize", InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS)); + view, buildStyles("autoCapitalize", InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS)); assertThat(view.getInputType() & InputType.TYPE_TEXT_FLAG_CAP_SENTENCES).isZero(); assertThat(view.getInputType() & InputType.TYPE_TEXT_FLAG_CAP_WORDS).isZero(); assertThat(view.getInputType() & InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS).isNotZero(); - mManager.updateProperties( - view, - buildStyles("autoCapitalize", InputType.TYPE_CLASS_TEXT)); + mManager.updateProperties(view, buildStyles("autoCapitalize", InputType.TYPE_CLASS_TEXT)); assertThat(view.getInputType() & InputType.TYPE_TEXT_FLAG_CAP_SENTENCES).isZero(); assertThat(view.getInputType() & InputType.TYPE_TEXT_FLAG_CAP_WORDS).isZero(); assertThat(view.getInputType() & InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS).isZero(); @@ -166,8 +153,7 @@ public class ReactTextInputPropertyTest { ReactEditText view = mManager.createViewInstance(mThemedContext); final ColorStateList defaultPlaceholderColorStateList = - DefaultStyleValuesUtil.getDefaultTextColorHint( - view.getContext()); + DefaultStyleValuesUtil.getDefaultTextColorHint(view.getContext()); ColorStateList colors = view.getHintTextColors(); assertThat(colors).isEqualTo(defaultPlaceholderColorStateList); @@ -236,16 +222,19 @@ public class ReactTextInputPropertyTest { int numberPadTypeFlags = InputType.TYPE_CLASS_NUMBER; int decimalPadTypeFlags = InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL; int numericTypeFlags = - InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | - InputType.TYPE_NUMBER_FLAG_SIGNED; + InputType.TYPE_CLASS_NUMBER + | InputType.TYPE_NUMBER_FLAG_DECIMAL + | InputType.TYPE_NUMBER_FLAG_SIGNED; int emailTypeFlags = InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS | InputType.TYPE_CLASS_TEXT; - int passwordVisibilityFlag = InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD & - ~InputType.TYPE_TEXT_VARIATION_PASSWORD; + int passwordVisibilityFlag = + InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD & ~InputType.TYPE_TEXT_VARIATION_PASSWORD; - int generalKeyboardTypeFlags = numericTypeFlags | - InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS | - InputType.TYPE_CLASS_TEXT | InputType.TYPE_CLASS_PHONE | - passwordVisibilityFlag; + int generalKeyboardTypeFlags = + numericTypeFlags + | InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS + | InputType.TYPE_CLASS_TEXT + | InputType.TYPE_CLASS_PHONE + | passwordVisibilityFlag; mManager.updateProperties(view, buildStyles()); assertThat(view.getInputType() & generalKeyboardTypeFlags).isEqualTo(InputType.TYPE_CLASS_TEXT); @@ -266,7 +255,8 @@ public class ReactTextInputPropertyTest { assertThat(view.getInputType() & generalKeyboardTypeFlags).isEqualTo(emailTypeFlags); mManager.updateProperties(view, buildStyles("keyboardType", "phone-pad")); - assertThat(view.getInputType() & generalKeyboardTypeFlags).isEqualTo(InputType.TYPE_CLASS_PHONE); + assertThat(view.getInputType() & generalKeyboardTypeFlags) + .isEqualTo(InputType.TYPE_CLASS_PHONE); mManager.updateProperties(view, buildStyles("keyboardType", "visible-password")); assertThat(view.getInputType() & generalKeyboardTypeFlags).isEqualTo(passwordVisibilityFlag); @@ -343,9 +333,11 @@ public class ReactTextInputPropertyTest { mManager.updateProperties(view, buildStyles("textAlign", "right")); assertThat(view.getGravity() & Gravity.HORIZONTAL_GRAVITY_MASK).isEqualTo(Gravity.RIGHT); mManager.updateProperties(view, buildStyles("textAlign", "center")); - assertThat(view.getGravity() & Gravity.HORIZONTAL_GRAVITY_MASK).isEqualTo(Gravity.CENTER_HORIZONTAL); + assertThat(view.getGravity() & Gravity.HORIZONTAL_GRAVITY_MASK) + .isEqualTo(Gravity.CENTER_HORIZONTAL); mManager.updateProperties(view, buildStyles("textAlign", null)); - assertThat(view.getGravity() & Gravity.HORIZONTAL_GRAVITY_MASK).isEqualTo(defaultHorizontalGravity); + assertThat(view.getGravity() & Gravity.HORIZONTAL_GRAVITY_MASK) + .isEqualTo(defaultHorizontalGravity); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { mManager.updateProperties(view, buildStyles("textAlign", "justify")); assertThat(view.getJustificationMode()).isEqualTo(Layout.JUSTIFICATION_MODE_INTER_WORD); @@ -357,29 +349,26 @@ public class ReactTextInputPropertyTest { mManager.updateProperties(view, buildStyles("textAlignVertical", "bottom")); assertThat(view.getGravity() & Gravity.VERTICAL_GRAVITY_MASK).isEqualTo(Gravity.BOTTOM); mManager.updateProperties(view, buildStyles("textAlignVertical", "center")); - assertThat(view.getGravity() & Gravity.VERTICAL_GRAVITY_MASK).isEqualTo(Gravity.CENTER_VERTICAL); + assertThat(view.getGravity() & Gravity.VERTICAL_GRAVITY_MASK) + .isEqualTo(Gravity.CENTER_VERTICAL); mManager.updateProperties(view, buildStyles("textAlignVertical", null)); assertThat(view.getGravity() & Gravity.VERTICAL_GRAVITY_MASK).isEqualTo(defaultVerticalGravity); // TextAlign + TextAlignVertical mManager.updateProperties( - view, - buildStyles("textAlign", "center", "textAlignVertical", "center")); + view, buildStyles("textAlign", "center", "textAlignVertical", "center")); assertThat(view.getGravity()).isEqualTo(Gravity.CENTER); mManager.updateProperties( - view, - buildStyles("textAlign", "right", "textAlignVertical", "bottom")); + view, buildStyles("textAlign", "right", "textAlignVertical", "bottom")); assertThat(view.getGravity()).isEqualTo(Gravity.RIGHT | Gravity.BOTTOM); - mManager.updateProperties( - view, - buildStyles("textAlign", null, "textAlignVertical", null)); + mManager.updateProperties(view, buildStyles("textAlign", null, "textAlignVertical", null)); assertThat(view.getGravity()).isEqualTo(defaultGravity); } @Test public void testMaxLength() { ReactEditText view = mManager.createViewInstance(mThemedContext); - InputFilter[] filters = new InputFilter[] { new InputFilter.AllCaps() }; + InputFilter[] filters = new InputFilter[] {new InputFilter.AllCaps()}; view.setFilters(filters); mManager.setMaxLength(view, null); assertThat(view.getFilters()).isEqualTo(filters); diff --git a/ReactAndroid/src/test/java/com/facebook/react/views/textinput/TextInputTest.java b/ReactAndroid/src/test/java/com/facebook/react/views/textinput/TextInputTest.java index d7426650e12..ff3a3e962be 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/views/textinput/TextInputTest.java +++ b/ReactAndroid/src/test/java/com/facebook/react/views/textinput/TextInputTest.java @@ -1,10 +1,9 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.textinput; import static org.fest.assertions.api.Assertions.assertThat; @@ -40,16 +39,13 @@ import org.powermock.modules.junit4.rule.PowerMockRule; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; -/** - * Tests for TextInput. - */ +/** Tests for TextInput. */ @PrepareForTest({Arguments.class, ReactChoreographer.class}) @RunWith(RobolectricTestRunner.class) @PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "androidx.*", "android.*"}) public class TextInputTest { - @Rule - public PowerMockRule rule = new PowerMockRule(); + @Rule public PowerMockRule rule = new PowerMockRule(); private ArrayList mPendingChoreographerCallbacks; @@ -58,25 +54,30 @@ public class TextInputTest { PowerMockito.mockStatic(Arguments.class, ReactChoreographer.class); ReactChoreographer choreographerMock = mock(ReactChoreographer.class); - PowerMockito.when(Arguments.createMap()).thenAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - return new JavaOnlyMap(); - } - }); + PowerMockito.when(Arguments.createMap()) + .thenAnswer( + new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + return new JavaOnlyMap(); + } + }); PowerMockito.when(ReactChoreographer.getInstance()).thenReturn(choreographerMock); mPendingChoreographerCallbacks = new ArrayList<>(); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - mPendingChoreographerCallbacks - .add((ChoreographerCompat.FrameCallback) invocation.getArguments()[1]); - return null; - } - }).when(choreographerMock).postFrameCallback( - any(ReactChoreographer.CallbackType.class), - any(ChoreographerCompat.FrameCallback.class)); + doAnswer( + new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + mPendingChoreographerCallbacks.add( + (ChoreographerCompat.FrameCallback) invocation.getArguments()[1]); + return null; + } + }) + .when(choreographerMock) + .postFrameCallback( + any(ReactChoreographer.CallbackType.class), + any(ChoreographerCompat.FrameCallback.class)); } @Test @@ -93,16 +94,10 @@ public class TextInputTest { textInputTag, ReactTextInputManager.REACT_CLASS, rootTag, - JavaOnlyMap.of( - ViewProps.FONT_SIZE, 13.37, ViewProps.HEIGHT, 20.0, "placeholder", hintStr)); + JavaOnlyMap.of(ViewProps.FONT_SIZE, 13.37, ViewProps.HEIGHT, 20.0, "placeholder", hintStr)); uiManager.manageChildren( - rootTag, - null, - null, - JavaOnlyArray.of(textInputTag), - JavaOnlyArray.of(0), - null); + rootTag, null, null, JavaOnlyArray.of(textInputTag), JavaOnlyArray.of(0), null); uiManager.onBatchComplete(); executePendingChoreographerCallbacks(); @@ -127,16 +122,10 @@ public class TextInputTest { textInputTag, ReactTextInputManager.REACT_CLASS, rootTag, - JavaOnlyMap.of( - ViewProps.FONT_SIZE, 13.37, ViewProps.HEIGHT, 20.0, "placeholder", hintStr)); + JavaOnlyMap.of(ViewProps.FONT_SIZE, 13.37, ViewProps.HEIGHT, 20.0, "placeholder", hintStr)); uiManager.manageChildren( - rootTag, - null, - null, - JavaOnlyArray.of(textInputTag), - JavaOnlyArray.of(0), - null); + rootTag, null, null, JavaOnlyArray.of(textInputTag), JavaOnlyArray.of(0), null); uiManager.onBatchComplete(); executePendingChoreographerCallbacks(); @@ -172,12 +161,12 @@ public class TextInputTest { public UIManagerModule getUIManagerModule() { ReactApplicationContext reactContext = ReactTestHelper.createCatalystContextForTest(); - List viewManagers = Arrays.asList( - new ViewManager[] { - new ReactTextInputManager(), - }); - UIManagerModule uiManagerModule = - new UIManagerModule(reactContext, viewManagers, 0); + List viewManagers = + Arrays.asList( + new ViewManager[] { + new ReactTextInputManager(), + }); + UIManagerModule uiManagerModule = new UIManagerModule(reactContext, viewManagers, 0); uiManagerModule.onHostResume(); return uiManagerModule; } diff --git a/ReactAndroid/src/test/java/com/facebook/react/views/view/ColorUtilTest.java b/ReactAndroid/src/test/java/com/facebook/react/views/view/ColorUtilTest.java index 925b7ea3cc2..64fd5d0a7f1 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/views/view/ColorUtilTest.java +++ b/ReactAndroid/src/test/java/com/facebook/react/views/view/ColorUtilTest.java @@ -1,14 +1,14 @@ /** * Copyright (c) Facebook, Inc. and its affiliates. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + *

This source code is licensed under the MIT license found in the LICENSE file in the root + * directory of this source tree. */ - package com.facebook.react.views.view; -import android.graphics.PixelFormat; +import static org.junit.Assert.*; +import android.graphics.PixelFormat; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; @@ -16,17 +16,12 @@ import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.modules.junit4.rule.PowerMockRule; import org.robolectric.RobolectricTestRunner; -import static org.junit.Assert.*; - -/** - * Based on Fresco's DrawableUtilsTest (https://github.com/facebook/fresco). - */ +/** Based on Fresco's DrawableUtilsTest (https://github.com/facebook/fresco). */ @RunWith(RobolectricTestRunner.class) @PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "androidx.*", "android.*"}) public class ColorUtilTest { - @Rule - public PowerMockRule rule = new PowerMockRule(); + @Rule public PowerMockRule rule = new PowerMockRule(); @Test public void testMultiplyColorAlpha() { diff --git a/ReactAndroid/src/test/java/org/mockito/configuration/MockitoConfiguration.java b/ReactAndroid/src/test/java/org/mockito/configuration/MockitoConfiguration.java index 6f48dee254c..152fb90f509 100644 --- a/ReactAndroid/src/test/java/org/mockito/configuration/MockitoConfiguration.java +++ b/ReactAndroid/src/test/java/org/mockito/configuration/MockitoConfiguration.java @@ -10,7 +10,7 @@ package org.mockito.configuration; /** * Disables the Mockito cache to prevent Mockito & Robolectric bugs. * - * Mockito loads this with reflection, so this class might appear unused. + *

Mockito loads this with reflection, so this class might appear unused. */ @SuppressWarnings("unused") public class MockitoConfiguration extends DefaultMockitoConfiguration { diff --git a/template/android/app/src/main/java/com/helloworld/MainActivity.java b/template/android/app/src/main/java/com/helloworld/MainActivity.java index 1e9c1894804..c7106d573c5 100644 --- a/template/android/app/src/main/java/com/helloworld/MainActivity.java +++ b/template/android/app/src/main/java/com/helloworld/MainActivity.java @@ -4,12 +4,12 @@ import com.facebook.react.ReactActivity; public class MainActivity extends ReactActivity { - /** - * Returns the name of the main component registered from JavaScript. - * This is used to schedule rendering of the component. - */ - @Override - protected String getMainComponentName() { - return "HelloWorld"; - } + /** + * Returns the name of the main component registered from JavaScript. This is used to schedule + * rendering of the component. + */ + @Override + protected String getMainComponentName() { + return "HelloWorld"; + } } diff --git a/template/android/app/src/main/java/com/helloworld/MainApplication.java b/template/android/app/src/main/java/com/helloworld/MainApplication.java index c35b2706379..68c6007108a 100644 --- a/template/android/app/src/main/java/com/helloworld/MainApplication.java +++ b/template/android/app/src/main/java/com/helloworld/MainApplication.java @@ -1,37 +1,36 @@ package com.helloworld; import android.app.Application; - import com.facebook.react.PackageList; import com.facebook.react.ReactApplication; import com.facebook.react.ReactNativeHost; import com.facebook.react.ReactPackage; import com.facebook.soloader.SoLoader; - import java.util.List; public class MainApplication extends Application implements ReactApplication { - private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) { - @Override - public boolean getUseDeveloperSupport() { - return BuildConfig.DEBUG; - } + private final ReactNativeHost mReactNativeHost = + new ReactNativeHost(this) { + @Override + public boolean getUseDeveloperSupport() { + return BuildConfig.DEBUG; + } - @Override - protected List getPackages() { - @SuppressWarnings("UnnecessaryLocalVariable") - List packages = new PackageList(this).getPackages(); - // Packages that cannot be autolinked yet can be added manually here, for example: - // packages.add(new MyReactNativePackage()); - return packages; - } + @Override + protected List getPackages() { + @SuppressWarnings("UnnecessaryLocalVariable") + List packages = new PackageList(this).getPackages(); + // Packages that cannot be autolinked yet can be added manually here, for example: + // packages.add(new MyReactNativePackage()); + return packages; + } - @Override - protected String getJSMainModuleName() { - return "index"; - } - }; + @Override + protected String getJSMainModuleName() { + return "index"; + } + }; @Override public ReactNativeHost getReactNativeHost() {