Java Code Examples for com.facebook.infer.annotation.Assertions#assertCondition()

The following examples show how to use com.facebook.infer.annotation.Assertions#assertCondition() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PostProcessorRegistry.java    From react-native-image-filter-kit with MIT License 6 votes vote down vote up
@Nullable
Postprocessor createComposition(
  @Nullable String name,
  int width,
  int height,
  @Nullable JSONObject config,
  @Nonnull CloseableReference<CloseableImage> imageRef,
  @Nonnull CacheKey imageKey,
  @Nonnull Context context
) {
  @Nullable CreateComposition filter = mCompositions.get(name);

  Assertions.assertCondition(
    filter != null,
    "ImageFilterKit: Can't find '" + name + "' filter in registry."
  );

  return filter != null
    ? filter.create(width, height, config, imageRef, imageKey, context)
    : null;
}
 
Example 2
Source File: NativeViewHierarchyOptimizer.java    From react-native-GPay with MIT License 6 votes vote down vote up
private void addGrandchildren(
    ReactShadowNode nativeParent,
    ReactShadowNode child,
    int index) {
  Assertions.assertCondition(!nativeParent.isLayoutOnly());

  // `child` can't hold native children. Add all of `child`'s children to `parent`.
  int currentIndex = index;
  for (int i = 0; i < child.getChildCount(); i++) {
    ReactShadowNode grandchild = child.getChildAt(i);
    Assertions.assertCondition(grandchild.getNativeParent() == null);

    if (grandchild.isLayoutOnly()) {
      // Adding this child could result in adding multiple native views
      int grandchildCountBefore = nativeParent.getNativeChildCount();
      addLayoutOnlyNode(nativeParent, grandchild, currentIndex);
      int grandchildCountAfter = nativeParent.getNativeChildCount();
      currentIndex += grandchildCountAfter - grandchildCountBefore;
    } else {
      addNonLayoutNode(nativeParent, grandchild, currentIndex);
      currentIndex++;
    }
  }
}
 
Example 3
Source File: ReactViewGroup.java    From react-native-GPay with MIT License 6 votes vote down vote up
void addViewWithSubviewClippingEnabled(
    View child, int index, ViewGroup.LayoutParams params) {
  Assertions.assertCondition(mRemoveClippedSubviews);
  Assertions.assertNotNull(mClippingRect);
  Assertions.assertNotNull(mAllChildren);
  addInArray(child, index);
  // we add view as "clipped" and then run {@link #updateSubviewClipStatus} to conditionally
  // attach it
  int childIndexOffset = 0;
  for (int i = 0; i < index; i++) {
    if (!isChildInViewGroup(mAllChildren[i])) {
      childIndexOffset++;
    }
  }
  updateSubviewClipStatus(mClippingRect, index, childIndexOffset);
  child.addOnLayoutChangeListener(mChildrenLayoutChangeListener);
}
 
Example 4
Source File: ReactViewGroup.java    From react-native-GPay with MIT License 6 votes vote down vote up
void removeViewWithSubviewClippingEnabled(View view) {
  Assertions.assertCondition(mRemoveClippedSubviews);
  Assertions.assertNotNull(mClippingRect);
  Assertions.assertNotNull(mAllChildren);
  view.removeOnLayoutChangeListener(mChildrenLayoutChangeListener);
  int index = indexOfChildInAllChildren(view);
  if (isChildInViewGroup(mAllChildren[index])) {
    int childIndexOffset = 0;
    for (int i = 0; i < index; i++) {
      if (!isChildInViewGroup(mAllChildren[i])) {
        childIndexOffset++;
      }
    }
    super.removeViewsInLayout(index - childIndexOffset, 1);
  }
  removeFromArray(index);
}
 
Example 5
Source File: CatalystInstanceImpl.java    From react-native-GPay with MIT License 6 votes vote down vote up
@Override
public void runJSBundle() {
  Log.d(ReactConstants.TAG, "CatalystInstanceImpl.runJSBundle()");
  Assertions.assertCondition(!mJSBundleHasLoaded, "JS bundle was already loaded!");
  // incrementPendingJSCalls();
  mJSBundleLoader.loadScript(CatalystInstanceImpl.this);

  synchronized (mJSCallsPendingInitLock) {

    // Loading the bundle is queued on the JS thread, but may not have
    // run yet.  It's safe to set this here, though, since any work it
    // gates will be queued on the JS thread behind the load.
    mAcceptCalls = true;

    for (PendingJSCall function : mJSCallsPendingInit) {
      function.call(this);
    }
    mJSCallsPendingInit.clear();
    mJSBundleHasLoaded = true;
  }

  // This is registered after JS starts since it makes a JS call
  Systrace.registerListener(mTraceListener);
}
 
Example 6
Source File: HeadlessJsTaskContext.java    From react-native-GPay with MIT License 6 votes vote down vote up
/**
 * Finish a JS task. Doesn't actually stop the task on the JS side, only removes it from the list
 * of active tasks and notifies listeners. A task can only be finished once.
 *
 * @param taskId the unique id returned by {@link #startTask}.
 */
public synchronized void finishTask(final int taskId) {
  Assertions.assertCondition(
    mActiveTasks.remove(taskId),
    "Tried to finish non-existent task with id " + taskId + ".");
  Runnable timeout = mTaskTimeouts.get(taskId);
  if (timeout != null) {
    mHandler.removeCallbacks(timeout);
    mTaskTimeouts.remove(taskId);
  }
  UiThreadUtil.runOnUiThread(new Runnable() {
    @Override
    public void run() {
      for (HeadlessJsTaskEventListener listener : mHeadlessJsTaskEventListeners) {
        listener.onHeadlessJsTaskFinish(taskId);
      }
    }
  });
}
 
Example 7
Source File: ReactShadowNodeImpl.java    From react-native-GPay with MIT License 6 votes vote down vote up
@Override
public ReactShadowNodeImpl mutableCopy(long instanceHandle) {
  ReactShadowNodeImpl copy = copy();
  Assertions.assertCondition(
      getClass() == copy.getClass(),
      "Copied shadow node must use the same class");
  copy.mInstanceHandle = instanceHandle;
  if (mYogaNode != null) {
    copy.mYogaNode = mYogaNode.clone();
    copy.mYogaNode.setData(copy);
  } else {
    // Virtual ReactShadowNode do not have a YogaNode associated
    copy.mYogaNode = null;
  }
  copy.mTotalNativeChildren = mTotalNativeChildren;
  copy.mNativeChildren = copyChildren(mNativeChildren);
  copy.mChildren = copyChildren(mChildren);

  return copy;
}
 
Example 8
Source File: PostProcessorRegistry.java    From react-native-image-filter-kit with MIT License 6 votes vote down vote up
@Nullable
Postprocessor createSingular(
  @Nullable String name,
  int width,
  int height,
  @Nullable JSONObject config,
  @Nonnull Context context
) {
  @Nullable CreateSingular filter = mSingulars.get(name);

  Assertions.assertCondition(
    filter != null,
    "ImageFilterKit: Can't find '" + name + "' filter in registry."
  );

  return filter != null ? filter.create(width, height, config, context) : null;
}
 
Example 9
Source File: NdkCxxPlatforms.java    From buck with Apache License 2.0 6 votes vote down vote up
private NdkCxxToolchainPaths(
    ProjectFilesystem filesystem,
    Path ndkRoot,
    String ndkVersion,
    NdkCxxPlatformTargetConfiguration targetConfiguration,
    String hostName,
    NdkCxxRuntime cxxRuntime,
    boolean strict,
    boolean unifiedHeaders) {
  this.filesystem = filesystem;
  this.cachedPaths = new HashMap<>();
  this.strict = strict;
  this.unifiedHeaders = unifiedHeaders;

  this.targetConfiguration = targetConfiguration;
  this.hostName = hostName;
  this.cxxRuntime = cxxRuntime;
  this.ndkRoot = ndkRoot;
  this.ndkVersion = ndkVersion;
  this.ndkMajorVersion = getNdkMajorVersion(ndkVersion);

  Assertions.assertCondition(ndkMajorVersion > 0, "Unknown ndk version: " + ndkVersion);
}
 
Example 10
Source File: ReactChoreographer.java    From react-native-GPay with MIT License 5 votes vote down vote up
public synchronized void postFrameCallback(
  CallbackType type,
  ChoreographerCompat.FrameCallback frameCallback) {
  mCallbackQueues[type.getOrder()].addLast(frameCallback);
  mTotalCallbacks++;
  Assertions.assertCondition(mTotalCallbacks > 0);
  if (!mHasPostedCallback) {
    mChoreographer.postFrameCallback(mReactChoreographerDispatcher);
    mHasPostedCallback = true;
  }
}
 
Example 11
Source File: ReactRootView.java    From react-native-GPay with MIT License 5 votes vote down vote up
/**
 * 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
 * properties for the react component.
 */
public void startReactApplication(
    ReactInstanceManager reactInstanceManager,
    String moduleName,
    @Nullable Bundle initialProperties) {
  Systrace.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "startReactApplication");
  try {
    UiThreadUtil.assertOnUiThread();

    // TODO(6788889): Use POJO instead of bundle here, apparently we can't just use WritableMap
    // 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 = reactInstanceManager;
    mJSModuleName = moduleName;
    mAppProperties = initialProperties;

    if (!mReactInstanceManager.hasStartedCreatingInitialContext()) {
      mReactInstanceManager.createReactContextInBackground();
    }

    attachToReactInstanceManager();

  } finally {
    Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE);
  }
}
 
Example 12
Source File: ReactInstanceManager.java    From react-native-GPay with MIT License 5 votes vote down vote up
/**
 * 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. This should only be called the first time the
 * application is set up, which is enforced to keep developers from accidentally creating their
 * application multiple times without realizing it.
 *
 * Called from UI thread.
 */
@ThreadConfined(UI)
public void createReactContextInBackground() {
  Log.d(ReactConstants.TAG, "ReactInstanceManager.createReactContextInBackground()");
  Assertions.assertCondition(
      !mHasStartedCreatingInitialContext,
      "createReactContextInBackground should only be called when creating the react " +
          "application for the first time. When reloading JS, e.g. from a new file, explicitly" +
          "use recreateReactContextInBackground");

  mHasStartedCreatingInitialContext = true;
  recreateReactContextInBackgroundInner();
}
 
Example 13
Source File: ReactChoreographer.java    From react-native-GPay with MIT License 5 votes vote down vote up
private void maybeRemoveFrameCallback() {
  Assertions.assertCondition(mTotalCallbacks >= 0);
  if (mTotalCallbacks == 0 && mHasPostedCallback) {
    mChoreographer.removeFrameCallback(mReactChoreographerDispatcher);
    mHasPostedCallback = false;
  }
}
 
Example 14
Source File: ReactQueueConfigurationSpec.java    From react-native-GPay with MIT License 5 votes vote down vote up
public Builder setNativeModulesQueueThreadSpec(MessageQueueThreadSpec spec) {
  Assertions.assertCondition(
    mNativeModulesQueueSpec == null,
    "Setting native modules queue spec multiple times!");
  mNativeModulesQueueSpec = spec;
  return this;
}
 
Example 15
Source File: ReactViewGroup.java    From react-native-GPay with MIT License 5 votes vote down vote up
void removeAllViewsWithSubviewClippingEnabled() {
  Assertions.assertCondition(mRemoveClippedSubviews);
  Assertions.assertNotNull(mAllChildren);
  for (int i = 0; i < mAllChildrenCount; i++) {
    mAllChildren[i].removeOnLayoutChangeListener(mChildrenLayoutChangeListener);
  }
  removeAllViewsInLayout();
  mAllChildrenCount = 0;
}
 
Example 16
Source File: JavaMethodWrapper.java    From react-native-GPay with MIT License 5 votes vote down vote up
private ArgumentExtractor[] buildArgumentExtractors(Class[] paramTypes) {
  ArgumentExtractor[] argumentExtractors = new ArgumentExtractor[paramTypes.length];
  for (int i = 0; i < paramTypes.length; i += argumentExtractors[i].getJSArgumentsNeeded()) {
    Class argumentClass = paramTypes[i];
    if (argumentClass == Boolean.class || argumentClass == boolean.class) {
      argumentExtractors[i] = ARGUMENT_EXTRACTOR_BOOLEAN;
    } else if (argumentClass == Integer.class || argumentClass == int.class) {
      argumentExtractors[i] = ARGUMENT_EXTRACTOR_INTEGER;
    } else if (argumentClass == Double.class || argumentClass == double.class) {
      argumentExtractors[i] = ARGUMENT_EXTRACTOR_DOUBLE;
    } else if (argumentClass == Float.class || argumentClass == float.class) {
      argumentExtractors[i] = ARGUMENT_EXTRACTOR_FLOAT;
    } else if (argumentClass == String.class) {
      argumentExtractors[i] = ARGUMENT_EXTRACTOR_STRING;
    } else if (argumentClass == Callback.class) {
      argumentExtractors[i] = ARGUMENT_EXTRACTOR_CALLBACK;
    } else if (argumentClass == Promise.class) {
      argumentExtractors[i] = ARGUMENT_EXTRACTOR_PROMISE;
      Assertions.assertCondition(
        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) {
      argumentExtractors[i] = ARGUMENT_EXTRACTOR_ARRAY;
    } else if (argumentClass == Dynamic.class) {
      argumentExtractors[i] = ARGUMENT_EXTRACTOR_DYNAMIC;
    } else {
      throw new RuntimeException(
        "Got unknown argument class: " + argumentClass.getSimpleName());
    }
  }
  return argumentExtractors;
}
 
Example 17
Source File: WritableNativeMap.java    From react-native-GPay with MIT License 4 votes vote down vote up
@Override
public void putArray(String key, WritableArray value) {
  Assertions.assertCondition(
      value == null || value instanceof WritableNativeArray, "Illegal type provided");
  putNativeArray(key, (WritableNativeArray) value);
}
 
Example 18
Source File: NativeViewHierarchyOptimizer.java    From react-native-GPay with MIT License 4 votes vote down vote up
private void transitionLayoutOnlyViewToNativeView(
    ReactShadowNode node,
    @Nullable ReactStylesDiffMap props) {
  ReactShadowNode parent = node.getParent();
  if (parent == null) {
    node.setIsLayoutOnly(false);
    return;
  }

  // First, remove the node from its parent. This causes the parent to update its native children
  // count. The removeNodeFromParent call will cause all the view's children to be detached from
  // their native parent.
  int childIndex = parent.indexOf(node);
  parent.removeChildAt(childIndex);
  removeNodeFromParent(node, false);

  node.setIsLayoutOnly(false);

  // Create the view since it doesn't exist in the native hierarchy yet
  mUIViewOperationQueue.enqueueCreateView(
      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);
  addNodeToNode(parent, node, childIndex);
  for (int i = 0; i < node.getChildCount(); i++) {
    addNodeToNode(node, node.getChildAt(i), i);
  }

  // Update layouts since the children of the node were offset by its x/y position previously.
  // Bit of a hack: we need to update the layout of this node's children now that it's no longer
  // layout-only, but we may still receive more layout updates at the end of this batch that we
  // don't want to ignore.
  Assertions.assertCondition(mTagsWithLayoutVisited.size() == 0);
  applyLayoutBase(node);
  for (int i = 0; i < node.getChildCount(); i++) {
    applyLayoutBase(node.getChildAt(i));
  }
  mTagsWithLayoutVisited.clear();
}
 
Example 19
Source File: ImageFilter.java    From react-native-image-filter-kit with MIT License 4 votes vote down vote up
private void runFilterPipeline() {
  ImageFilter.ashmemInfo("before filtering");
  final ArrayList<ReactImageView> images = images();

  if (!mIsReady && getChildCount() > 0) {
    getChildAt(0).setVisibility(View.INVISIBLE);
  }

  if (mConfig != null && images.size() > 0) {
    try {
      final ImageFilter self = this;
      final CacheKey auxKey = AuxCache.auxKey(mConfig, images);

      final WeakFilterableImage target = AuxCache.get(auxKey);
      final ArrayList<Postprocessor> postProcessors = target != null
        ? target.getPostProcessors()
        : null;

      if (target != null && postProcessors != null) {
        if (!self.mIsReady && getChildCount() > 0) {
          getChildAt(0).setVisibility(View.VISIBLE);
          self.mIsReady = true;
        }

        final ReactImageView mainImage = images.get(0);

        ImageFilter.filterImage(
          new FilterableImage(
            mainImage,
            postProcessors,
            target.isCacheDisabled()
          ),
          mImageListeners.get(mainImage),
          mFiltering
        ).onSuccess(task -> {
          sendJSEvent(ImageFilterEvent.ON_FILTERING_FINISH, null);
          self.extractImage(task.getResult());
          return null;
        }, mFiltering.getToken());

      } else {
        parseConfig(mConfig, images)
          .onSuccess((Continuation<FilterableImage, Void>) task -> {
            if (!self.mIsReady && getChildCount() > 0) {
              getChildAt(0).setVisibility(View.VISIBLE);
              self.mIsReady = true;
            }

            final FilterableImage result = task.getResult();

            ImageFilter.filterImage(result, mImageListeners.get(result.getImage()), mFiltering)
              .onSuccess((Continuation<ReactImageView, Void>) task1 -> {
                if (!result.isCacheDisabled()) {
                  AuxCache.put(
                    auxKey,
                    new WeakFilterableImage(
                      result.getPostProcessors(),
                      result.isCacheDisabled()
                    )
                  );
                }

                ImageFilter.ashmemInfo("after filtering");

                sendJSEvent(ImageFilterEvent.ON_FILTERING_FINISH, null);
                self.extractImage(task1.getResult());

                return null;
              }, mFiltering.getToken());

            return null;
          }, mFiltering.getToken())
          .continueWith((Continuation<Void, Void>) task -> {
            if (task.isFaulted()) {
              handleError(task.getError());
            }

            return null;
          });
      }

    } catch (JSONException exc) {
      Assertions.assertCondition(
        false,
        "ImageFilterKit: Unable to parse config - " + exc.getMessage()
      );
    }
  }
}
 
Example 20
Source File: WritableNativeArray.java    From react-native-GPay with MIT License 4 votes vote down vote up
@Override
public void pushArray(WritableArray array) {
  Assertions.assertCondition(
      array == null || array instanceof WritableNativeArray, "Illegal type provided");
  pushNativeArray((WritableNativeArray) array);
}