com.facebook.common.executors.UiThreadImmediateExecutorService Java Examples

The following examples show how to use com.facebook.common.executors.UiThreadImmediateExecutorService. 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: DefaultFrescoContext.java    From fresco with MIT License 6 votes vote down vote up
private static synchronized FrescoContext createDefaultContext(
    Resources resources, @Nullable FrescoExperiments frescoExperiments) {
  FrescoExperiments actualFrescoExperiments =
      frescoExperiments != null ? frescoExperiments : new FrescoExperiments();
  return new FrescoContextImpl(
      new HierarcherImpl(createDefaultDrawableFactory(resources, actualFrescoExperiments)),
      new NoOpCallerContextVerifier(),
      actualFrescoExperiments,
      UiThreadImmediateExecutorService.getInstance(),
      Fresco.getImagePipeline().getConfig().getExecutorSupplier().forLightweightBackgroundTasks(),
      null,
      null,
      null,
      sDebugOverlayEnabledSupplier == null
          ? new NoOpDebugOverlayFactory()
          : new DefaultDebugOverlayFactory(sDebugOverlayEnabledSupplier));
}
 
Example #2
Source File: AnimationBackendUtils.java    From fresco with MIT License 6 votes vote down vote up
/**
 * Wraps the given animation backend with an activity check. When no frame has been drawn for more
 * than 2 seconds, an inactivity toast message will be displayed.
 *
 * @param context the context to be used for displaying the toast message
 * @param animationBackend the backend to wrap with the inactivity check
 * @return the wrapped backend to use
 */
public static AnimationBackend wrapAnimationBackendWithInactivityCheck(
    final Context context, final AnimationBackend animationBackend) {
  AnimationBackendDelegateWithInactivityCheck.InactivityListener inactivityListener =
      new AnimationBackendDelegateWithInactivityCheck.InactivityListener() {
        @Override
        public void onInactive() {
          // Forward the inactive callback to the backend if needed
          if (animationBackend
              instanceof AnimationBackendDelegateWithInactivityCheck.InactivityListener) {
            ((AnimationBackendDelegateWithInactivityCheck.InactivityListener) animationBackend)
                .onInactive();
          }
          Toast.makeText(context, "Animation backend inactive.", Toast.LENGTH_SHORT).show();
        }
      };
  return createForBackend(
      animationBackend,
      inactivityListener,
      RealtimeSinceBootClock.get(),
      UiThreadImmediateExecutorService.getInstance());
}
 
Example #3
Source File: TempFileUtils.java    From react-native-image-filter-kit with MIT License 5 votes vote down vote up
static void writeFile(
  @NonNull final ReactContext context,
  @NonNull final CloseableReference<CloseableImage> ref,
  @NonNull final Functor.Arity1<String> sendUri,
  @NonNull final Functor.Arity1<String> sendError
) {
  CloseableReference<CloseableImage> cloned = ref.clone();

  Task.callInBackground((Callable<Void>) () -> {
    try {
      final File outputFile = createFile(context);
      final FileOutputStream fos = new FileOutputStream(outputFile);
      final Bitmap bitmap = ((CloseableBitmap) cloned.get()).getUnderlyingBitmap();

      bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);

      final String path = Uri.fromFile(outputFile).toString();

      FLog.w(ReactConstants.TAG, "ImageFilterKit: created file " + path);

      Task.call((Callable<Void>) () -> {
        sendUri.call(path);

        return null;
      }, UiThreadImmediateExecutorService.getInstance());

    } catch (Exception e) {
      Task.call((Callable<Void>) () -> {
        sendError.call(e.getMessage());

        return null;
      }, UiThreadImmediateExecutorService.getInstance());

    } finally {
      CloseableReference.closeSafely(cloned);
    }

    return null;
  });
}
 
Example #4
Source File: ImageFilter.java    From react-native-image-filter-kit with MIT License 5 votes vote down vote up
private void handleError(
  final @Nonnull Throwable error,
  final @Nullable Functor.Arity1<Integer> retry,
  final int retries
) {
  FLog.w(ReactConstants.TAG, "ImageFilterKit: " + error.toString());

  MemoryTrimmer trimmer = MemoryTrimmer.getInstance();

  if (
    error instanceof TooManyBitmapsException &&
    trimmer.isUsed() &&
    retries < mClearCachesMaxRetries
  ) {
    FLog.d(ReactConstants.TAG, "ImageFilterKit: clearing caches ...");
    trimmer.trim();
    Fresco.getImagePipeline().clearCaches();

    Task.delay(1, mFiltering.getToken()).continueWith(task -> {
      if (retry != null) {
        retry.call(retries + 1);
      }
      return null;
    }, UiThreadImmediateExecutorService.getInstance(), mFiltering.getToken());

  } else {
    sendJSEvent(ImageFilterEvent.ON_FILTERING_ERROR, error.toString());
  }
}
 
Example #5
Source File: FrescoController.java    From base-module with Apache License 2.0 5 votes vote down vote up
/**
 * 加载图片获取 Bitmap 对象
 * @param subscriber
 */
public void intoTarget(BaseBitmapDataSubscriber subscriber) {
    ImageRequestBuilder builder = ImageRequestBuilder.newBuilderWithSource(mUri)
            .setProgressiveRenderingEnabled(true);

    if (mWidth > 0 && mHeight > 0) {
        builder.setResizeOptions(new ResizeOptions(mWidth, mHeight));
    }

    ImageRequest imageRequest = builder.build();
    ImagePipeline imagePipeline = Fresco.getImagePipeline();
    DataSource<CloseableReference<CloseableImage>> dataSource = imagePipeline.fetchDecodedImage(imageRequest, this);
    dataSource.subscribe(subscriber, UiThreadImmediateExecutorService.getInstance());
}
 
Example #6
Source File: FrescoController.java    From base-module with Apache License 2.0 5 votes vote down vote up
/**
 * 只下载图片到磁盘,可设置下载回调
 * @param context
 * @param baseDataSubscriber
 */
public void downloadOnly(Context context, BaseDataSubscriber baseDataSubscriber) {
    ImageRequest imageRequest = ImageRequestBuilder.newBuilderWithSource(mUri)
            .setProgressiveRenderingEnabled(true)
            .build();
    ImagePipeline imagePipeline = Fresco.getImagePipeline();

    DataSource<Void> dataSource = imagePipeline.prefetchToDiskCache(imageRequest, context.getApplicationContext());
    if(baseDataSubscriber != null) {
        dataSource.subscribe(baseDataSubscriber, UiThreadImmediateExecutorService.getInstance());
    }
}
 
Example #7
Source File: ApplicationActivity.java    From react-native-turbolinks with MIT License 5 votes vote down vote up
private void bitmapFor(Bundle image, Context context, BaseBitmapDataSubscriber baseBitmapDataSubscriber) {
    ImageSource source = new ImageSource(context, image.getString("uri"));
    ImageRequest imageRequest = ImageRequestBuilder.newBuilderWithSource(source.getUri()).build();

    ImagePipeline imagePipeline = Fresco.getImagePipeline();
    DataSource<CloseableReference<CloseableImage>> dataSource = imagePipeline.fetchDecodedImage(imageRequest, context);

    dataSource.subscribe(baseBitmapDataSubscriber, UiThreadImmediateExecutorService.getInstance());
}
 
Example #8
Source File: PipelineDraweeControllerBuilderSupplier.java    From FanXin-based-HuanXin with GNU General Public License v2.0 5 votes vote down vote up
public PipelineDraweeControllerBuilderSupplier(
    Context context,
    ImagePipelineFactory imagePipelineFactory,
    Set<ControllerListener> boundControllerListeners) {
  mContext = context;
  mImagePipeline = imagePipelineFactory.getImagePipeline();
  mPipelineDraweeControllerFactory = new PipelineDraweeControllerFactory(
      context.getResources(),
      DeferredReleaser.getInstance(),
      imagePipelineFactory.getAnimatedDrawableFactory(),
      UiThreadImmediateExecutorService.getInstance());
  mBoundControllerListeners = boundControllerListeners;
}
 
Example #9
Source File: FrescoImageLoader.java    From ScrollGalleryView with MIT License 5 votes vote down vote up
@Override
public void loadMedia(Context context, final ImageView imageView, SuccessCallback callback) {
    if (!Fresco.hasBeenInitialized()) {
        Fresco.initialize(context);
    }
    ImagePipeline pipeline = Fresco.getImagePipeline();
    DataSubscriber subscriber = getSubscriber(imageView, callback);
    DataSource<CloseableReference<CloseableImage>> dataSource = pipeline.fetchDecodedImage(createImageRequest(), context);
    dataSource.subscribe(subscriber, UiThreadImmediateExecutorService.getInstance());
}
 
Example #10
Source File: FrescoImageLoader.java    From ScrollGalleryView with MIT License 5 votes vote down vote up
@Override
public void loadThumbnail(Context context, ImageView thumbnailView, SuccessCallback callback) {
    if (!Fresco.hasBeenInitialized()){
        Fresco.initialize(context);
    }
    ImagePipeline pipeline = Fresco.getImagePipeline();
    DataSubscriber subscriber = getSubscriber(thumbnailView, callback);
    DataSource<CloseableReference<CloseableImage>> dataSource = pipeline.fetchDecodedImage(createImageRequest(thumbnailWidth, thumbnailHeight), context);
    dataSource.subscribe(subscriber, UiThreadImmediateExecutorService.getInstance());
}
 
Example #11
Source File: PipelineDraweeControllerBuilderSupplier.java    From fresco with MIT License 5 votes vote down vote up
public PipelineDraweeControllerBuilderSupplier(
    Context context,
    ImagePipelineFactory imagePipelineFactory,
    Set<ControllerListener> boundControllerListeners,
    Set<ControllerListener2> boundControllerListeners2,
    @Nullable DraweeConfig draweeConfig) {
  mContext = context;
  mImagePipeline = imagePipelineFactory.getImagePipeline();

  if (draweeConfig != null && draweeConfig.getPipelineDraweeControllerFactory() != null) {
    mPipelineDraweeControllerFactory = draweeConfig.getPipelineDraweeControllerFactory();
  } else {
    mPipelineDraweeControllerFactory = new PipelineDraweeControllerFactory();
  }
  mPipelineDraweeControllerFactory.init(
      context.getResources(),
      DeferredReleaser.getInstance(),
      imagePipelineFactory.getAnimatedDrawableFactory(context),
      UiThreadImmediateExecutorService.getInstance(),
      mImagePipeline.getBitmapMemoryCache(),
      draweeConfig != null ? draweeConfig.getCustomDrawableFactories() : null,
      draweeConfig != null ? draweeConfig.getDebugOverlayEnabledSupplier() : null);
  mBoundControllerListeners = boundControllerListeners;
  mBoundControllerListeners2 = boundControllerListeners2;

  mDefaultImagePerfDataListener =
      draweeConfig != null ? draweeConfig.getImagePerfDataListener() : null;
}
 
Example #12
Source File: AnimatedFactoryV2Impl.java    From fresco with MIT License 5 votes vote down vote up
private ExperimentalBitmapAnimationDrawableFactory createDrawableFactory() {
  Supplier<Integer> cachingStrategySupplier =
      new Supplier<Integer>() {
        @Override
        public Integer get() {
          return ExperimentalBitmapAnimationDrawableFactory
              .CACHING_STRATEGY_FRESCO_CACHE_NO_REUSING;
        }
      };

  final SerialExecutorService serialExecutorServiceForFramePreparing =
      new DefaultSerialExecutorService(mExecutorSupplier.forDecode());

  Supplier<Integer> numberOfFramesToPrepareSupplier =
      new Supplier<Integer>() {
        @Override
        public Integer get() {
          return NUMBER_OF_FRAMES_TO_PREPARE;
        }
      };

  return new ExperimentalBitmapAnimationDrawableFactory(
      getAnimatedDrawableBackendProvider(),
      UiThreadImmediateExecutorService.getInstance(),
      serialExecutorServiceForFramePreparing,
      RealtimeSinceBootClock.get(),
      mPlatformBitmapFactory,
      mBackingCache,
      cachingStrategySupplier,
      numberOfFramesToPrepareSupplier);
}
 
Example #13
Source File: FrescoControllerImplTest.java    From fresco with MIT License 5 votes vote down vote up
private RequestListener baseTestListeners() {
  ImageOptions imageOptions = ImageOptions.create().build();
  RequestListener requestListener = mock(BaseRequestListener.class);

  when(mFrescoContext.getUiThreadExecutorService())
      .thenReturn(UiThreadImmediateExecutorService.getInstance());

  final Uri uri = Uri.parse("http://fresco");
  ImageRequest imageRequest = ImageRequestBuilder.newBuilderWithSource(uri).build();
  when(mFrescoState.getImageRequest()).thenReturn(imageRequest);

  when(mFrescoState.getImageOptions()).thenReturn(imageOptions);
  when(mFrescoState.getRequestListener()).thenReturn(requestListener);

  when(mFrescoState.getUri()).thenReturn(uri);

  SimpleDataSource dataSource = SimpleDataSource.create();

  when(mImagePipeline.submitFetchRequest(
          any(Producer.class),
          any(com.facebook.imagepipeline.producers.SettableProducerContext.class),
          eq(requestListener)))
      .thenReturn(dataSource);
  when(mImagePipeline.fetchDecodedImage(
          any(ImageRequest.class),
          any(Object.class),
          any(ImageRequest.RequestLevel.class),
          eq(requestListener),
          eq(IMAGE_ID_STRING)))
      .thenReturn(dataSource);

  mFrescoController.onAttach(mFrescoState, null);

  verify(mFrescoContext, atLeast(1)).getImagePipeline();
  verify(mFrescoState, atLeast(1)).getCachedImage();
  verify(mFrescoState).onSubmit(eq(IMAGE_ID), eq(CALLER_CONTEXT));
  verify(mFrescoState, atLeast(1)).getImageRequest();
  return requestListener;
}
 
Example #14
Source File: ImageFilter.java    From react-native-image-filter-kit with MIT License 4 votes vote down vote up
private static Task<ReactImageView> filterImage(
  final @Nonnull FilterableImage filterableImage,
  final @Nullable FrescoControllerListener listener,
  final @Nonnull CancellationTokenSource cancellationTokenSource
) {
  final ReactImageView image = filterableImage.getImage();
  final TaskCompletionSource<ReactImageView> deferred = new TaskCompletionSource<>();

  ArrayList<Postprocessor> postProcessors = new ArrayList<>(filterableImage.getPostProcessors());

  if (postProcessors.size() == 0) {
    postProcessors.add(new DummyPostProcessor());
  }

  IterativeBoxBlurPostProcessor next = new MultiPostProcessor(
    postProcessors,
    filterableImage.isCacheDisabled()
  );

  if (listener != null) {
    listener.setDisabled();
  }

  final ControllerListener<ImageInfo> prevListener = ReactImageViewUtils
    .getControllerListener(image);

  FrescoControllerListener nextListener = new FrescoControllerListener(
    prevListener,
    () -> {
      if (!deferred.getTask().isCompleted()) {
        ReactImageViewUtils.setControllerListener(image, prevListener);
        deferred.setResult(image);
      }
    }
  );

  ReactImageViewUtils.setControllerListener(image, nextListener);

  ReactImageViewUtils.setPostProcessor(image, next);

  ReactImageViewUtils.setDirty(image);

  Task.call((Callable<Void>) () -> {
    image.maybeUpdateView();
    return null;
  }, UiThreadImmediateExecutorService.getInstance(), cancellationTokenSource.getToken());

  return deferred.getTask();
}