public PipelineDraweeController newController( Supplier<DataSource<CloseableReference<CloseableImage>>> dataSourceSupplier, String id, CacheKey cacheKey, Object callerContext, @Nullable ImmutableList<DrawableFactory> customDrawableFactories) { Preconditions.checkState(mResources != null, "init() not called"); // Field values passed as arguments so that any subclass of PipelineDraweeControllerFactory // can simply override internalCreateController() and return a custom Drawee controller PipelineDraweeController controller = internalCreateController( mResources, mDeferredReleaser, mAnimatedDrawableFactory, mUiThreadExecutor, mMemoryCache, mDrawableFactories, customDrawableFactories, dataSourceSupplier, id, cacheKey, callerContext); if (mDebugOverlayEnabledSupplier != null) { controller.setDrawDebugOverlay(mDebugOverlayEnabledSupplier.get()); } return controller; }
protected PipelineDraweeController internalCreateController( Resources resources, DeferredReleaser deferredReleaser, DrawableFactory animatedDrawableFactory, Executor uiThreadExecutor, MemoryCache<CacheKey, CloseableImage> memoryCache, @Nullable ImmutableList<DrawableFactory> globalDrawableFactories, @Nullable ImmutableList<DrawableFactory> customDrawableFactories, Supplier<DataSource<CloseableReference<CloseableImage>>> dataSourceSupplier, String id, CacheKey cacheKey, Object callerContext) { PipelineDraweeController controller = new PipelineDraweeController( resources, deferredReleaser, animatedDrawableFactory, uiThreadExecutor, memoryCache, dataSourceSupplier, id, cacheKey, callerContext, globalDrawableFactories); controller.setCustomDrawableFactories(customDrawableFactories); return controller; }
public PipelineDraweeController( Resources resources, DeferredReleaser deferredReleaser, DrawableFactory animatedDrawableFactory, Executor uiThreadExecutor, MemoryCache<CacheKey, CloseableImage> memoryCache, Supplier<DataSource<CloseableReference<CloseableImage>>> dataSourceSupplier, String id, CacheKey cacheKey, Object callerContext) { this( resources, deferredReleaser, animatedDrawableFactory, uiThreadExecutor, memoryCache, dataSourceSupplier, id, cacheKey, callerContext, null); }
public PipelineDraweeController( Resources resources, DeferredReleaser deferredReleaser, DrawableFactory animatedDrawableFactory, Executor uiThreadExecutor, MemoryCache<CacheKey, CloseableImage> memoryCache, Supplier<DataSource<CloseableReference<CloseableImage>>> dataSourceSupplier, String id, CacheKey cacheKey, Object callerContext, @Nullable ImmutableList<DrawableFactory> globalDrawableFactories) { super(deferredReleaser, uiThreadExecutor, id, callerContext); mResources = resources; mAnimatedDrawableFactory = animatedDrawableFactory; mMemoryCache = memoryCache; mCacheKey = cacheKey; mGlobalDrawableFactories = globalDrawableFactories; init(dataSourceSupplier); }
@Override public void onNewResultImpl(DataSource<CloseableReference<CloseableImage>> dataSource) { if (!dataSource.isFinished()) { return; } CloseableReference<CloseableImage> closeableImageRef = dataSource.getResult(); Bitmap bitmap = null; if (closeableImageRef != null && closeableImageRef.get() instanceof CloseableBitmap) { bitmap = ((CloseableBitmap) closeableImageRef.get()).getUnderlyingBitmap(); } try { onNewResultImpl(bitmap); } finally { CloseableReference.closeSafely(closeableImageRef); } }
/** * Returns a DataSource supplier that will on get submit the request for execution and return a * DataSource representing the pending results of the task. * * @param imageRequest the request to submit (what to execute). * @param callerContext the caller context of the caller of data source supplier * @param requestLevel which level to look down until for the image * @return a DataSource representing pending results and completion of the request */ public Supplier<DataSource<CloseableReference<CloseableImage>>> getDataSourceSupplier( final ImageRequest imageRequest, final Object callerContext, final ImageRequest.RequestLevel requestLevel) { return new Supplier<DataSource<CloseableReference<CloseableImage>>>() { @Override public DataSource<CloseableReference<CloseableImage>> get() { return fetchDecodedImage(imageRequest, callerContext, requestLevel); } @Override public String toString() { return Objects.toStringHelper(this) .add("uri", imageRequest.getSourceUri()) .toString(); } }; }
/** * Returns a DataSource supplier that will on get submit the request for execution and return a * DataSource representing the pending results of the task. * * @param imageRequest the request to submit (what to execute). * @return a DataSource representing pending results and completion of the request */ public Supplier<DataSource<CloseableReference<PooledByteBuffer>>> getEncodedImageDataSourceSupplier( final ImageRequest imageRequest, final Object callerContext) { return new Supplier<DataSource<CloseableReference<PooledByteBuffer>>>() { @Override public DataSource<CloseableReference<PooledByteBuffer>> get() { return fetchEncodedImage(imageRequest, callerContext); } @Override public String toString() { return Objects.toStringHelper(this) .add("uri", imageRequest.getSourceUri()) .toString(); } }; }
/** * Submits a request for execution and returns a DataSource representing the pending decoded * image(s). * <p>The returned DataSource must be closed once the client has finished with it. * * @param imageRequest the request to submit * @param callerContext the caller context for image request * @param lowestPermittedRequestLevelOnSubmit the lowest request level permitted for image request * @return a DataSource representing the pending decoded image(s) */ public DataSource<CloseableReference<CloseableImage>> fetchDecodedImage( ImageRequest imageRequest, Object callerContext, ImageRequest.RequestLevel lowestPermittedRequestLevelOnSubmit) { try { Producer<CloseableReference<CloseableImage>> producerSequence = mProducerSequenceFactory.getDecodedImageProducerSequence(imageRequest); return submitFetchRequest( producerSequence, imageRequest, lowestPermittedRequestLevelOnSubmit, callerContext); } catch (Exception exception) { return DataSources.immediateFailedDataSource(exception); } }
/** * Submits a request for prefetching to the bitmap cache. * * <p> Beware that if your network fetcher doesn't support priorities prefetch requests may slow * down images which are immediately required on screen. * * @param imageRequest the request to submit * @return a DataSource that can safely be ignored. */ public DataSource<Void> prefetchToBitmapCache( ImageRequest imageRequest, Object callerContext) { if (!mIsPrefetchEnabledSupplier.get()) { return DataSources.immediateFailedDataSource(PREFETCH_EXCEPTION); } try { Producer<Void> producerSequence = mSuppressBitmapPrefetchingSupplier.get() ? mProducerSequenceFactory.getEncodedImagePrefetchProducerSequence(imageRequest) : mProducerSequenceFactory.getDecodedImagePrefetchProducerSequence(imageRequest); return submitPrefetchRequest( producerSequence, imageRequest, ImageRequest.RequestLevel.FULL_FETCH, callerContext, Priority.MEDIUM); } catch (Exception exception) { return DataSources.immediateFailedDataSource(exception); } }
/** * Submits a request for prefetching to the disk cache. * * <p> Beware that if your network fetcher doesn't support priorities prefetch requests may slow * down images which are immediately required on screen. * * @param imageRequest the request to submit * @param priority custom priority for the fetch * @return a DataSource that can safely be ignored. */ public DataSource<Void> prefetchToDiskCache( ImageRequest imageRequest, Object callerContext, Priority priority) { if (!mIsPrefetchEnabledSupplier.get()) { return DataSources.immediateFailedDataSource(PREFETCH_EXCEPTION); } try { Producer<Void> producerSequence = mProducerSequenceFactory.getEncodedImagePrefetchProducerSequence(imageRequest); return submitPrefetchRequest( producerSequence, imageRequest, ImageRequest.RequestLevel.FULL_FETCH, callerContext, priority); } catch (Exception exception) { return DataSources.immediateFailedDataSource(exception); } }
private void verifyState( boolean isFinished, boolean hasResult, Object result, boolean hasFailed, Throwable failureCause) { DataSource<Object> dataSource = mDataSource; assertEquals("isFinished", isFinished, dataSource.isFinished()); assertEquals("hasResult", hasResult, dataSource.hasResult()); assertSame("getResult", result, dataSource.getResult()); assertEquals("hasFailed", hasFailed, dataSource.hasFailed()); if (failureCause == NPE) { assertNotNull("failure", dataSource.getFailureCause()); assertSame("failure", NullPointerException.class, dataSource.getFailureCause().getClass()); } else { assertSame("failure", failureCause, dataSource.getFailureCause()); } }
private void verifyState( boolean isFinished, boolean hasResult, CloseableReference<Object> resultRef, boolean hasFailed, Throwable failureCause) { DataSource<CloseableReference<Object>> dataSource = mDataSource; assertEquals("isFinished", isFinished, dataSource.isFinished()); assertEquals("hasResult", hasResult, dataSource.hasResult()); CloseableReference<Object> dataSourceRef = dataSource.getResult(); assertReferencesSame("getResult", resultRef, dataSourceRef); CloseableReference.closeSafely(dataSourceRef); assertEquals("hasFailed", hasFailed, dataSource.hasFailed()); if (failureCause == NPE) { assertNotNull("failure", dataSource.getFailureCause()); assertSame("failure", NullPointerException.class, dataSource.getFailureCause().getClass()); } else { assertSame("failure", failureCause, dataSource.getFailureCause()); } }
@Test public void testPrefetchToBitmapCache() { Producer<Void> prefetchProducerSequence = mock(Producer.class); when(mProducerSequenceFactory.getDecodedImagePrefetchProducerSequence(mImageRequest)) .thenReturn(prefetchProducerSequence); DataSource<Void> dataSource = mImagePipeline.prefetchToBitmapCache(mImageRequest, mCallerContext); assertTrue(!dataSource.isFinished()); verify(mRequestListener1).onRequestStart(mImageRequest, mCallerContext, "0", true); verify(mRequestListener2).onRequestStart(mImageRequest, mCallerContext, "0", true); ArgumentCaptor<ProducerContext> producerContextArgumentCaptor = ArgumentCaptor.forClass(ProducerContext.class); verify(prefetchProducerSequence) .produceResults(any(Consumer.class), producerContextArgumentCaptor.capture()); assertFalse(producerContextArgumentCaptor.getValue().isIntermediateResultExpected()); assertEquals(producerContextArgumentCaptor.getValue().getPriority(), Priority.MEDIUM); }
@Test public void testFetchDecodedImage() { Producer<CloseableReference<CloseableImage>> decodedSequence = mock(Producer.class); when(mProducerSequenceFactory.getDecodedImageProducerSequence(mImageRequest)) .thenReturn(decodedSequence); DataSource<CloseableReference<CloseableImage>> dataSource = mImagePipeline.fetchDecodedImage(mImageRequest, mCallerContext); assertFalse(dataSource.isFinished()); verify(mRequestListener1).onRequestStart(mImageRequest, mCallerContext, "0", false); verify(mRequestListener2).onRequestStart(mImageRequest, mCallerContext, "0", false); ArgumentCaptor<ProducerContext> producerContextArgumentCaptor = ArgumentCaptor.forClass(ProducerContext.class); verify(decodedSequence) .produceResults(any(Consumer.class), producerContextArgumentCaptor.capture()); assertTrue(producerContextArgumentCaptor.getValue().isIntermediateResultExpected()); assertEquals(producerContextArgumentCaptor.getValue().getPriority(), Priority.HIGH); }
@Test public void testFetchDecodedImageWithRequestLevel() { Producer<CloseableReference<CloseableImage>> decodedSequence = mock(Producer.class); when(mProducerSequenceFactory.getDecodedImageProducerSequence(mImageRequest)) .thenReturn(decodedSequence); DataSource<CloseableReference<CloseableImage>> dataSource = mImagePipeline.fetchDecodedImage( mImageRequest, mCallerContext, ImageRequest.RequestLevel.DISK_CACHE); assertFalse(dataSource.isFinished()); verify(mRequestListener1).onRequestStart(mImageRequest, mCallerContext, "0", false); verify(mRequestListener2).onRequestStart(mImageRequest, mCallerContext, "0", false); ArgumentCaptor<ProducerContext> producerContextArgumentCaptor = ArgumentCaptor.forClass(ProducerContext.class); verify(decodedSequence) .produceResults(any(Consumer.class), producerContextArgumentCaptor.capture()); assertTrue(producerContextArgumentCaptor.getValue().isIntermediateResultExpected()); assertEquals(producerContextArgumentCaptor.getValue().getPriority(), Priority.HIGH); assertEquals( producerContextArgumentCaptor.getValue().getLowestPermittedRequestLevel(), ImageRequest.RequestLevel.DISK_CACHE); }
@Test public void testGetBitmapCacheGetSupplier() { Supplier<DataSource<CloseableReference<CloseableImage>>> dataSourceSupplier = mImagePipeline.getDataSourceSupplier( mImageRequest, mCallerContext, ImageRequest.RequestLevel.BITMAP_MEMORY_CACHE); Producer<CloseableReference<CloseableImage>> bitmapCacheSequence = mock(Producer.class); when(mProducerSequenceFactory.getDecodedImageProducerSequence(mImageRequest)) .thenReturn(bitmapCacheSequence); dataSourceSupplier.get(); verify(mRequestListener1).onRequestStart(mImageRequest, mCallerContext, "0", false); verify(mRequestListener2).onRequestStart(mImageRequest, mCallerContext, "0", false); ArgumentCaptor<ProducerContext> producerContextArgumentCaptor = ArgumentCaptor.forClass(ProducerContext.class); verify(bitmapCacheSequence) .produceResults(any(Consumer.class), producerContextArgumentCaptor.capture()); assertTrue(producerContextArgumentCaptor.getValue().isIntermediateResultExpected()); assertEquals(producerContextArgumentCaptor.getValue().getPriority(), Priority.HIGH); }
@Test public void testGetFullFetchSupplier() { Supplier<DataSource<CloseableReference<CloseableImage>>> dataSourceSupplier = mImagePipeline .getDataSourceSupplier(mImageRequest, mCallerContext, ImageRequest.RequestLevel.FULL_FETCH); Producer<CloseableReference<CloseableImage>> decodedSequence = mock(Producer.class); when(mProducerSequenceFactory.getDecodedImageProducerSequence(mImageRequest)) .thenReturn(decodedSequence); DataSource<CloseableReference<CloseableImage>> dataSource = dataSourceSupplier.get(); assertFalse(dataSource.isFinished()); verify(mRequestListener1).onRequestStart(mImageRequest, mCallerContext, "0", false); verify(mRequestListener2).onRequestStart(mImageRequest, mCallerContext, "0", false); ArgumentCaptor<ProducerContext> producerContextArgumentCaptor = ArgumentCaptor.forClass(ProducerContext.class); verify(decodedSequence) .produceResults(any(Consumer.class), producerContextArgumentCaptor.capture()); assertTrue(producerContextArgumentCaptor.getValue().isIntermediateResultExpected()); assertEquals(producerContextArgumentCaptor.getValue().getPriority(), Priority.HIGH); }
protected Supplier<DataSource<IMAGE>> getFirstAvailableDataSourceSupplier( REQUEST[] imageRequests, boolean tryBitmapCacheOnlyFirst) { List<Supplier<DataSource<IMAGE>>> suppliers = new ArrayList<>(imageRequests.length * 2); if (tryBitmapCacheOnlyFirst) { // we first add bitmap-cache-only suppliers, then the full-fetch ones for (int i = 0; i < imageRequests.length; i++) { suppliers.add( getDataSourceSupplierForRequest(imageRequests[i], CacheLevel.BITMAP_MEMORY_CACHE)); } } for (int i = 0; i < imageRequests.length; i++) { suppliers.add(getDataSourceSupplierForRequest(imageRequests[i])); } return FirstAvailableDataSourceSupplier.create(suppliers); }
/** Creates a data source supplier for the given image request. */ protected Supplier<DataSource<IMAGE>> getDataSourceSupplierForRequest( final REQUEST imageRequest, final CacheLevel cacheLevel) { final Object callerContext = getCallerContext(); return new Supplier<DataSource<IMAGE>>() { @Override public DataSource<IMAGE> get() { return getDataSourceForRequest(imageRequest, callerContext, cacheLevel); } @Override public String toString() { return Objects.toStringHelper(this) .add("request", imageRequest.toString()) .toString(); } }; }
private void onFailureInternal(String id, DataSource<CloseableReference<CloseableImage>> dataSource, Throwable throwable, boolean isFinished) { if (FLog.isLoggable(Log.WARN)) { FLog.w(DraweeSpan.class, id + " load failure", throwable); } // ignored this result if (!getId().equals(id) || dataSource != mDataSource || !mIsRequestSubmitted) { dataSource.close(); return; } if (isFinished) { mDataSource = null; // Set the previously available image if available. setDrawableInner(mDrawable); } }
public static void loadBitmapFromUrl(Context context, String url, String cookie, String referer, BaseBitmapDataSubscriber dataSubscriber) { if (TextUtils.isEmpty(url)) return; Uri uri = Uri.parse(url); JsonObject header = new JsonObject(); header.addProperty("Cookie", cookie); header.addProperty("Referer", referer); if (HProxy.isEnabled() && HProxy.isAllowPicture()) { HProxy proxy = new HProxy(url); header.addProperty(proxy.getHeaderKey(), proxy.getHeaderValue()); } MyOkHttpNetworkFetcher.headers.put(uri, getGson().toJson(header)); ImagePipeline imagePipeline = Fresco.getImagePipeline(); ImageRequestBuilder builder = ImageRequestBuilder.newBuilderWithSource(uri); ImageRequest request = builder.build(); DataSource<CloseableReference<CloseableImage>> dataSource = imagePipeline.fetchDecodedImage(request, context); dataSource.subscribe(dataSubscriber, CallerThreadExecutor.getInstance()); }
public static void loadResourceFromUrl(Context context, Uri uri, String cookie, String referer, BaseDataSubscriber dataSubscriber) { if (uri.getScheme().startsWith("http")) { JsonObject header = new JsonObject(); header.addProperty("Cookie", cookie); header.addProperty("Referer", referer); if (HProxy.isEnabled() && HProxy.isAllowPicture()) { HProxy proxy = new HProxy(uri.toString()); header.addProperty(proxy.getHeaderKey(), proxy.getHeaderValue()); } MyOkHttpNetworkFetcher.headers.put(uri, getGson().toJson(header)); } ImagePipeline imagePipeline = Fresco.getImagePipeline(); ImageRequestBuilder builder = ImageRequestBuilder.newBuilderWithSource(uri); ImageRequest request = builder.build(); DataSource<CloseableReference<PooledByteBuffer>> dataSource = imagePipeline.fetchEncodedImage(request, context); dataSource.subscribe(dataSubscriber, CallerThreadExecutor.getInstance()); }
public void setSupplier(@Nullable Supplier<DataSource<T>> supplier) { // early return without calling {@code supplier.get()} in case we are closed if (isClosed()) { return; } DataSource<T> oldDataSource; DataSource<T> newDataSource = (supplier != null) ? supplier.get() : null; synchronized (RetainingDataSource.this) { if (isClosed()) { oldDataSource = newDataSource; newDataSource = null; } else { oldDataSource = mDataSource; mDataSource = newDataSource; } } if (newDataSource != null) { newDataSource.subscribe(new InternalDataSubscriber(), CallerThreadExecutor.getInstance()); } closeSafely(oldDataSource); }
@Override public void onRun() throws Throwable { Log.i(TAG, "RUNNING UploadJob for Item["+itemId+"] Uri["+uri.toString()+"]"); if(MediaUtils.isPhoto(UriUtils.extractMimeType(weakReference.get(), uri))) { DataSource<CloseableReference<CloseableImage>> dataSource = Fresco.getImagePipeline().fetchDecodedImage(ImageRequest.fromUri(uri), weakReference.get()); Throwable failureCause = dataSource.getFailureCause(); if (failureCause != null) { throw failureCause; } CloseableReference<CloseableImage> result = dataSource.getResult(); if (result != null) { CloseableImage closeableImage = result.get(); if (closeableImage instanceof CloseableBitmap) { Bitmap bitmap = ((CloseableBitmap) closeableImage).getUnderlyingBitmap(); uploadFile(createImageTempFile(bitmap)); } } }else{ uploadFile(new File(uri.getPath())); } }
@Override protected void onNewResultImpl(DataSource<CloseableReference<PooledByteBuffer>> dataSource) { if (!dataSource.isFinished() || dataSource.getResult() == null) { return; } // if we try to retrieve image file by cache key, it will return null // so we need to create a temp file, little bit hack :( PooledByteBufferInputStream inputStream = null; FileOutputStream outputStream = null; try { inputStream = new PooledByteBufferInputStream(dataSource.getResult().get()); outputStream = new FileOutputStream(mTempFile); IOUtils.copy(inputStream, outputStream); mFinished = true; onSuccess(mTempFile); } catch (IOException e) { onFail(e); } finally { IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(outputStream); } }
public static void LoadImageFromURLAndCallBack(SimpleDraweeView destImageView , String URL,Context context,BaseBitmapDataSubscriber bbds) { int w = destImageView.getWidth(); int h =destImageView.getHeight(); if(w<1){ w = destImageView.getLayoutParams().width; } if(h<1){ h =destImageView.getLayoutParams().height; } ImageRequest imageRequest = ImageRequestBuilder.newBuilderWithSource(Uri.parse(URL)) .setResizeOptions(new ResizeOptions(w,h)) .setProgressiveRenderingEnabled(true) .build(); ImagePipeline imagePipeline = Fresco.getImagePipeline(); DataSource<CloseableReference<CloseableImage>> dataSource = imagePipeline.fetchDecodedImage(imageRequest, context); dataSource.subscribe(bbds, CallerThreadExecutor.getInstance()); DraweeController draweeController = Fresco.newDraweeControllerBuilder() .setImageRequest(imageRequest) .setOldController(destImageView.getController()) .setAutoPlayAnimations(true) .build(); destImageView.setController(draweeController); }
public static void LoadImageFromURIAndCallBack(SimpleDraweeView destImageView , Uri uri,Context context,BaseBitmapDataSubscriber bbds) { int w = destImageView.getWidth(); int h =destImageView.getHeight(); if(w<1){ w = destImageView.getLayoutParams().width; } if(h<1){ h =destImageView.getLayoutParams().height; } ImageRequest imageRequest = ImageRequestBuilder.newBuilderWithSource(uri) .setResizeOptions(new ResizeOptions(w,h)) .setProgressiveRenderingEnabled(true) .build(); ImagePipeline imagePipeline = Fresco.getImagePipeline(); DataSource<CloseableReference<CloseableImage>> dataSource = imagePipeline.fetchDecodedImage(imageRequest, context); dataSource.subscribe(bbds, CallerThreadExecutor.getInstance()); DraweeController draweeController = Fresco.newDraweeControllerBuilder() .setImageRequest(imageRequest) .setOldController(destImageView.getController()) .setAutoPlayAnimations(true) .build(); destImageView.setController(draweeController); }