Example #1
0
  @Before
  public void setUp() {
    PowerMockito.mockStatic(Arguments.class);
    PowerMockito.when(Arguments.createArray())
        .thenAnswer(
            new Answer<Object>() {
              @Override
              public Object answer(InvocationOnMock invocation) throws Throwable {
                return new SimpleArray();
              }
            });
    PowerMockito.when(Arguments.createMap())
        .thenAnswer(
            new Answer<Object>() {
              @Override
              public Object answer(InvocationOnMock invocation) throws Throwable {
                return new SimpleMap();
              }
            });

    mCatalystInstanceMock = ReactTestHelper.createMockCatalystInstance();
    mReactContext = new ReactApplicationContext(RuntimeEnvironment.application);
    mReactContext.initializeWithInstance(mCatalystInstanceMock);
    DisplayMetrics displayMetrics = mReactContext.getResources().getDisplayMetrics();
    DisplayMetricsHolder.setWindowDisplayMetrics(displayMetrics);

    UIManagerModule uiManagerModuleMock = mock(UIManagerModule.class);
    when(mCatalystInstanceMock.getNativeModule(UIManagerModule.class))
        .thenReturn(uiManagerModuleMock);
  }
  /**
   * Replaces the View specified by oldTag with the View specified by newTag within oldTag's parent.
   */
  public void replaceExistingNonRootView(int oldTag, int newTag) {
    if (mShadowNodeRegistry.isRootNode(oldTag) || mShadowNodeRegistry.isRootNode(newTag)) {
      throw new IllegalViewOperationException("Trying to add or replace a root tag!");
    }

    ReactShadowNode oldNode = mShadowNodeRegistry.getNode(oldTag);
    if (oldNode == null) {
      throw new IllegalViewOperationException("Trying to replace unknown view tag: " + oldTag);
    }

    ReactShadowNode parent = oldNode.getParent();
    if (parent == null) {
      throw new IllegalViewOperationException("Node is not attached to a parent: " + oldTag);
    }

    int oldIndex = parent.indexOf(oldNode);
    if (oldIndex < 0) {
      throw new IllegalStateException("Didn't find child tag in parent");
    }

    WritableArray tagsToAdd = Arguments.createArray();
    tagsToAdd.pushInt(newTag);

    WritableArray addAtIndices = Arguments.createArray();
    addAtIndices.pushInt(oldIndex);

    WritableArray indicesToRemove = Arguments.createArray();
    indicesToRemove.pushInt(oldIndex);

    manageChildren(parent.getReactTag(), null, null, tagsToAdd, addAtIndices, indicesToRemove);
  }
  private WritableMap serializeEventData() {
    WritableMap eventData = Arguments.createMap();

    WritableMap selectionData = Arguments.createMap();
    selectionData.putInt("start", mSelectionStart);
    selectionData.putInt("end", mSelectionEnd);

    eventData.putMap("selection", selectionData);
    return eventData;
  }
  public void onActivityResult(int requestCode, int resultCode, Intent data) {
    // robustness code
    if (mCallback == null
        || (mCameraCaptureURI == null && requestCode == REQUEST_LAUNCH_CAMERA)
        || (requestCode != REQUEST_LAUNCH_CAMERA && requestCode != REQUEST_LAUNCH_IMAGE_LIBRARY)) {
      return;
    }

    // user cancel
    if (resultCode != Activity.RESULT_OK) {
      mCallback.invoke(true, Arguments.createMap());
      return;
    }

    WritableMap response = Arguments.createMap();
    Uri uri = (requestCode == REQUEST_LAUNCH_CAMERA) ? mCameraCaptureURI : data.getData();

    // let's set data
    String realPath = getRealPathFromURI(uri);

    response.putString("path", uri.toString());
    response.putString("uri", realPath);
    if (!noData) {
      response.putString("data", getBase64StringFromFile(realPath));
    }

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(realPath, options);
    response.putInt("width", options.outWidth);
    response.putInt("height", options.outHeight);

    try {
      ExifInterface exif = new ExifInterface(realPath);
      int orientation =
          exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
      boolean isVertical = true;
      switch (orientation) {
        case ExifInterface.ORIENTATION_ROTATE_270:
          isVertical = false;
          break;
        case ExifInterface.ORIENTATION_ROTATE_90:
          isVertical = false;
          break;
      }
      response.putBoolean("isVertical", isVertical);
    } catch (IOException e) {
      e.printStackTrace();
    }

    mCallback.invoke(false, response);
  }
  @ReactProp(name = PROP_CENTER)
  public void setPropCenter(MapView view, @Nullable ReadableMap center) {
    WritableMap properties = getProperties();
    if (center != null) {
      WritableMap centerLatLng = Arguments.createMap();
      WritableMap centerMap = Arguments.createMap();
      centerLatLng.putDouble("lat", center.getDouble("lat"));
      centerLatLng.putDouble("lng", center.getDouble("lng"));

      centerMap.putMap("center", centerLatLng);
      properties.merge(centerMap);
      updateCenter();
    }
  }
  @Before
  public void setUp() {
    PowerMockito.mockStatic(Arguments.class, ReactChoreographer.class);

    ReactChoreographer choreographerMock = mock(ReactChoreographer.class);
    PowerMockito.when(Arguments.createMap())
        .thenAnswer(
            new Answer<Object>() {
              @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(
                    (Choreographer.FrameCallback) invocation.getArguments()[1]);
                return null;
              }
            })
        .when(choreographerMock)
        .postFrameCallback(
            any(ReactChoreographer.CallbackType.class), any(Choreographer.FrameCallback.class));
  }
  private void notifyNotification(Bundle bundle) {
    String bundleString = convertJSON(bundle);

    WritableMap params = Arguments.createMap();
    params.putString("dataJSON", bundleString);

    sendEvent("remoteNotificationReceived", params);
  }
  private void sendMapError(String message, String type) {
    WritableMap error = Arguments.createMap();
    error.putString("message", message);
    error.putString("type", type);

    reactContext
        .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
        .emit("mapError", error);
  }
  // NOTE: Currently not reentrant / doesn't support concurrent requests
  @ReactMethod
  public void launchImageLibrary(final ReadableMap options, final Callback callback) {
    response = Arguments.createMap();

    if (options.hasKey("noData")) {
      noData = options.getBoolean("noData");
    }
    if (options.hasKey("maxWidth")) {
      maxWidth = options.getInt("maxWidth");
    }
    if (options.hasKey("maxHeight")) {
      maxHeight = options.getInt("maxHeight");
    }
    if (options.hasKey("aspectX")) {
      aspectX = options.getInt("aspectX");
    }
    if (options.hasKey("aspectY")) {
      aspectY = options.getInt("aspectY");
    }
    if (options.hasKey("quality")) {
      quality = (int) (options.getDouble("quality") * 100);
    }
    tmpImage = true;
    if (options.hasKey("storageOptions")) {
      tmpImage = false;
    }
    if (options.hasKey("allowsEditing")) {
      allowEditing = options.getBoolean("allowsEditing");
    }
    forceAngle = false;
    if (options.hasKey("angle")) {
      forceAngle = true;
      angle = options.getInt("angle");
    }
    if (options.hasKey("assetProperties")) {
      assetProperties = options.getBoolean("assetProperties");
    }

    Intent libraryIntent =
        new Intent(
            Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

    if (libraryIntent.resolveActivity(mMainActivity.getPackageManager()) == null) {
      response.putString("error", "Cannot launch photo library");
      callback.invoke(response);
      return;
    }

    mCallback = callback;

    try {
      mMainActivity.startActivityForResult(libraryIntent, REQUEST_LAUNCH_IMAGE_LIBRARY);
    } catch (ActivityNotFoundException e) {
      e.printStackTrace();
    }
  }
  private void attachMeasuredRootViewToInstance(
      ReactRootView rootView, CatalystInstance catalystInstance) {
    UiThreadUtil.assertOnUiThread();

    // Reset view content as it's going to be populated by the application content from JS
    rootView.removeAllViews();
    rootView.setId(View.NO_ID);

    UIManagerModule uiManagerModule = catalystInstance.getNativeModule(UIManagerModule.class);
    int rootTag = uiManagerModule.addMeasuredRootView(rootView);
    @Nullable Bundle launchOptions = rootView.getLaunchOptions();
    WritableMap initialProps =
        launchOptions != null ? Arguments.fromBundle(launchOptions) : Arguments.createMap();
    String jsAppModuleName = rootView.getJSModuleName();

    WritableNativeMap appParams = new WritableNativeMap();
    appParams.putDouble("rootTag", rootTag);
    appParams.putMap("initialProps", initialProps);
    catalystInstance.getJSModule(AppRegistry.class).runApplication(jsAppModuleName, appParams);
  }
 public void disconnect() {
   connectCallback = null;
   connected = false;
   if (gatt != null) {
     gatt.close();
     gatt = null;
     Log.d(LOG_TAG, "Disconnect");
     WritableMap map = Arguments.createMap();
     map.putString("peripheral", device.getAddress());
     sendEvent("BleManagerDisconnectPeripheral", map);
   } else Log.d(LOG_TAG, "GATT is null");
 }
  @Before
  public void prepareModules() {
    PowerMockito.mockStatic(Arguments.class);
    Mockito.when(Arguments.createArray())
        .thenAnswer(
            new Answer<Object>() {
              @Override
              public Object answer(InvocationOnMock invocation) throws Throwable {
                return new SimpleArray();
              }
            });

    Mockito.when(Arguments.createMap())
        .thenAnswer(
            new Answer<Object>() {
              @Override
              public Object answer(InvocationOnMock invocation) throws Throwable {
                return new SimpleMap();
              }
            });
  }
  /**
   * 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
   *
   * @param containerTag the tag of the container for which the subviews must be removed
   */
  public void removeSubviewsFromContainerWithID(int containerTag) {
    ReactShadowNode containerNode = mShadowNodeRegistry.getNode(containerTag);
    if (containerNode == null) {
      throw new IllegalViewOperationException(
          "Trying to remove subviews of an unknown view tag: " + containerTag);
    }

    WritableArray indicesToRemove = Arguments.createArray();
    for (int childIndex = 0; childIndex < containerNode.getChildCount(); childIndex++) {
      indicesToRemove.pushInt(childIndex);
    }

    manageChildren(containerTag, null, null, null, null, indicesToRemove);
  }
  @Override
  public void onCharacteristicChanged(
      BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
    super.onCharacteristicChanged(gatt, characteristic);

    // Log.d(LOG_TAG, "onCharacteristicChanged " + characteristic);
    byte[] dataValue = characteristic.getValue();
    Log.d(LOG_TAG, "Letto:" + BleManager.bytesToHex(dataValue) + " da:" + device.getAddress());

    WritableMap map = Arguments.createMap();
    map.putString("peripheral", device.getAddress());
    map.putString("characteristic", characteristic.getUuid().toString());
    map.putString("value", BleManager.bytesToHex(dataValue));
    sendEvent("BleManagerDidUpdateValueForCharacteristic", map);
  }
  @Override
  public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {

    Log.d(
        LOG_TAG,
        "onConnectionStateChange da "
            + status
            + " a "
            + newState
            + " peripheral:"
            + device.getAddress());

    this.gatt = gatt;

    if (newState == BluetoothGatt.STATE_CONNECTED) {

      connected = true;
      gatt.discoverServices();

    } else if (newState == BluetoothGatt.STATE_DISCONNECTED) {

      if (connected) {
        connected = false;

        if (gatt != null) {
          gatt.close();
          gatt = null;
        }

        WritableMap map = Arguments.createMap();
        map.putString("peripheral", device.getAddress());
        sendEvent("BleManagerDisconnectPeripheral", map);
        Log.d(LOG_TAG, "BleManagerDisconnectPeripheral peripheral:" + device.getAddress());
      }
      if (connectFailCallback != null) {
        connectFailCallback.invoke();
        connectFailCallback = null;
        connectCallback = null;
      }
    }
  }
 public void onReceiveNativeEvent(String value) {
   WritableMap event = Arguments.createMap();
   event.putString("message", value);
   ReactContext reactContext = (ReactContext) getContext();
   reactContext.getJSModule(RCTEventEmitter.class).receiveEvent(getId(), "topChange", event);
 }
  @ReactMethod
  public void showImagePicker(final ReadableMap options, final Callback callback) {
    response = Arguments.createMap();

    List<String> mTitles = new ArrayList<String>();
    List<String> mActions = new ArrayList<String>();

    String cancelButtonTitle = "Cancel";

    if (options.hasKey("takePhotoButtonTitle")
        && options.getString("takePhotoButtonTitle") != null
        && !options.getString("takePhotoButtonTitle").isEmpty()) {
      mTitles.add(options.getString("takePhotoButtonTitle"));
      mActions.add("photo");
    }
    if (options.hasKey("chooseFromLibraryButtonTitle")
        && options.getString("chooseFromLibraryButtonTitle") != null
        && !options.getString("chooseFromLibraryButtonTitle").isEmpty()) {
      mTitles.add(options.getString("chooseFromLibraryButtonTitle"));
      mActions.add("library");
    }
    if (options.hasKey("cancelButtonTitle") && !options.getString("cancelButtonTitle").isEmpty()) {
      cancelButtonTitle = options.getString("cancelButtonTitle");
    }
    mTitles.add(cancelButtonTitle);
    mActions.add("cancel");

    String[] option = new String[mTitles.size()];
    option = mTitles.toArray(option);

    String[] action = new String[mActions.size()];
    action = mActions.toArray(action);
    final String[] act = action;

    ArrayAdapter<String> adapter =
        new ArrayAdapter<String>(mMainActivity, android.R.layout.select_dialog_item, option);
    AlertDialog.Builder builder = new AlertDialog.Builder(mMainActivity);
    if (options.hasKey("title")
        && options.getString("title") != null
        && !options.getString("title").isEmpty()) {
      builder.setTitle(options.getString("title"));
    }

    builder.setAdapter(
        adapter,
        new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int index) {
            if (act[index].equals("photo")) {
              launchCamera(options, callback);
            } else if (act[index].equals("library")) {
              launchImageLibrary(options, callback);
            } else {
              response.putBoolean("didCancel", true);
              callback.invoke(response);
            }
          }
        });

    final AlertDialog dialog = builder.create();
    /**
     * override onCancel method to callback cancel in case of a touch outside of the dialog or the
     * BACK key pressed
     */
    dialog.setOnCancelListener(
        new DialogInterface.OnCancelListener() {
          @Override
          public void onCancel(DialogInterface dialog) {
            dialog.dismiss();
            response.putBoolean("didCancel", true);
            callback.invoke(response);
          }
        });
    dialog.show();
  }
  // NOTE: Currently not reentrant / doesn't support concurrent requests
  @ReactMethod
  public void launchCamera(final ReadableMap options, final Callback callback) {
    response = Arguments.createMap();

    if (options.hasKey("noData")) {
      noData = options.getBoolean("noData");
    }
    if (options.hasKey("maxWidth")) {
      maxWidth = options.getInt("maxWidth");
    }
    if (options.hasKey("maxHeight")) {
      maxHeight = options.getInt("maxHeight");
    }
    if (options.hasKey("aspectX")) {
      aspectX = options.getInt("aspectX");
    }
    if (options.hasKey("aspectY")) {
      aspectY = options.getInt("aspectY");
    }
    if (options.hasKey("quality")) {
      quality = (int) (options.getDouble("quality") * 100);
    }
    tmpImage = true;
    if (options.hasKey("storageOptions")) {
      tmpImage = false;
    }
    if (options.hasKey("allowsEditing")) {
      allowEditing = options.getBoolean("allowsEditing");
    }
    forceAngle = false;
    if (options.hasKey("angle")) {
      forceAngle = true;
      angle = options.getInt("angle");
    }
    if (options.hasKey("assetProperties")) {
      assetProperties = options.getBoolean("assetProperties");
    }

    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (cameraIntent.resolveActivity(mMainActivity.getPackageManager()) == null) {
      response.putString("error", "Cannot launch camera");
      callback.invoke(response);
      return;
    }

    // we create a tmp file to save the result
    File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    File imageFile;
    try {
      // Make sure the Pictures directory exists.
      path.mkdirs();
      imageFile = File.createTempFile("capture", ".jpg", path);
    } catch (IOException e) {
      e.printStackTrace();
      response.putString("error", e.getMessage());
      callback.invoke(response);
      return;
    }
    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(imageFile));
    mCameraCaptureURI = Uri.fromFile(imageFile);
    mCallback = callback;

    try {
      mMainActivity.startActivityForResult(cameraIntent, REQUEST_LAUNCH_CAMERA);
    } catch (ActivityNotFoundException e) {
      e.printStackTrace();
    }
  }
 private WritableMap serializeEventData() {
   WritableMap eventData = Arguments.createMap();
   eventData.putInt("selected", getPosition());
   eventData.putString("value", getValue());
   return eventData;
 }
 @ReactMethod
 public void presentLocalNotification(ReadableMap details) {
   Bundle bundle = Arguments.toBundle(details);
   mRNPushNotificationHelper.sendNotification(bundle);
 }
 private WritableMap getProperties() {
   if (_properties == null) {
     _properties = Arguments.createMap();
   }
   return _properties;
 }
Example #22
0
 private WritableMap serializeEventData() {
   WritableMap eventData = Arguments.createMap();
   eventData.putInt("target", getViewTag());
   eventData.putBoolean("value", getIsChecked());
   return eventData;
 }