idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
8,200
public boolean getPadding ( Rect padding ) { padding . set ( mPadding , mPadding , mPadding , mPadding ) ; return mPadding != 0 ; }
Gets the progress bar padding .
8,201
public static < T extends View > T findViewById ( Activity act , int viewId ) { View containerView = act . getWindow ( ) . getDecorView ( ) ; return findViewById ( containerView , viewId ) ; }
This method returns the reference of the View with the given Id in the layout of the Activity passed as parameter
8,202
@ SuppressWarnings ( "unchecked" ) public static < T extends View > T findViewById ( View containerView , int viewId ) { View foundView = containerView . findViewById ( viewId ) ; return ( T ) foundView ; }
This method returns the reference of the View with the given Id in the view passed as parameter
8,203
private void resetInternal ( ) { mTransitionState = TRANSITION_NONE ; Arrays . fill ( mStartAlphas , mDefaultLayerAlpha ) ; mStartAlphas [ 0 ] = 255 ; Arrays . fill ( mAlphas , mDefaultLayerAlpha ) ; mAlphas [ 0 ] = 255 ; Arrays . fill ( mIsLayerOn , mDefaultLayerIsOn ) ; mIsLayerOn [ 0 ] = true ; }
Resets internal state to the initial state .
8,204
public void fadeToLayer ( int index ) { mTransitionState = TRANSITION_STARTING ; Arrays . fill ( mIsLayerOn , false ) ; mIsLayerOn [ index ] = true ; invalidateSelf ( ) ; }
Starts fading to the specified layer .
8,205
public void finishTransitionImmediately ( ) { mTransitionState = TRANSITION_NONE ; for ( int i = 0 ; i < mLayers . length ; i ++ ) { mAlphas [ i ] = mIsLayerOn [ i ] ? 255 : 0 ; } invalidateSelf ( ) ; }
Finishes transition immediately .
8,206
private boolean updateAlphas ( float ratio ) { boolean done = true ; for ( int i = 0 ; i < mLayers . length ; i ++ ) { int dir = mIsLayerOn [ i ] ? + 1 : - 1 ; mAlphas [ i ] = ( int ) ( mStartAlphas [ i ] + dir * 255 * ratio ) ; if ( mAlphas [ i ] < 0 ) { mAlphas [ i ] = 0 ; } if ( mAlphas [ i ] > 255 ) { mAlphas [ i ] = 255 ; } if ( mIsLayerOn [ i ] && mAlphas [ i ] < 255 ) { done = false ; } if ( ! mIsLayerOn [ i ] && mAlphas [ i ] > 0 ) { done = false ; } } return done ; }
Updates the current alphas based on the ratio of the elapsed time and duration .
8,207
public static void boxBlurBitmapInPlace ( final Bitmap bitmap , final int iterations , final int radius ) { Preconditions . checkNotNull ( bitmap ) ; Preconditions . checkArgument ( bitmap . isMutable ( ) ) ; Preconditions . checkArgument ( bitmap . getHeight ( ) <= BitmapUtil . MAX_BITMAP_SIZE ) ; Preconditions . checkArgument ( bitmap . getWidth ( ) <= BitmapUtil . MAX_BITMAP_SIZE ) ; Preconditions . checkArgument ( radius > 0 && radius <= RenderScriptBlurFilter . BLUR_MAX_RADIUS ) ; Preconditions . checkArgument ( iterations > 0 ) ; try { fastBoxBlur ( bitmap , iterations , radius ) ; } catch ( OutOfMemoryError oom ) { FLog . e ( TAG , String . format ( ( Locale ) null , "OOM: %d iterations on %dx%d with %d radius" , iterations , bitmap . getWidth ( ) , bitmap . getHeight ( ) , radius ) ) ; throw oom ; } }
An in - place iterative box blur algorithm that runs faster than a traditional box blur .
8,208
public synchronized boolean increase ( Bitmap bitmap ) { final int bitmapSize = BitmapUtil . getSizeInBytes ( bitmap ) ; if ( mCount >= mMaxCount || mSize + bitmapSize > mMaxSize ) { return false ; } mCount ++ ; mSize += bitmapSize ; return true ; }
Includes given bitmap in the bitmap count . The bitmap is included only if doing so does not violate configured limit
8,209
public synchronized void decrease ( Bitmap bitmap ) { final int bitmapSize = BitmapUtil . getSizeInBytes ( bitmap ) ; Preconditions . checkArgument ( mCount > 0 , "No bitmaps registered." ) ; Preconditions . checkArgument ( bitmapSize <= mSize , "Bitmap size bigger than the total registered size: %d, %d" , bitmapSize , mSize ) ; mSize -= bitmapSize ; mCount -- ; }
Excludes given bitmap from the count .
8,210
public static void addOptionalFeatures ( ImageRequestBuilder imageRequestBuilder , Config config ) { if ( config . usePostprocessor ) { final Postprocessor postprocessor ; switch ( config . postprocessorType ) { case "use_slow_postprocessor" : postprocessor = DelayPostprocessor . getMediumPostprocessor ( ) ; break ; case "use_fast_postprocessor" : postprocessor = DelayPostprocessor . getFastPostprocessor ( ) ; break ; default : postprocessor = DelayPostprocessor . getMediumPostprocessor ( ) ; } imageRequestBuilder . setPostprocessor ( postprocessor ) ; } if ( config . rotateUsingMetaData ) { imageRequestBuilder . setRotationOptions ( RotationOptions . autoRotateAtRenderTime ( ) ) ; } else { imageRequestBuilder . setRotationOptions ( RotationOptions . forceRotation ( config . forcedRotationAngle ) ) ; } }
Utility method which adds optional configuration to ImageRequest
8,211
public static long skip ( final InputStream inputStream , final long bytesCount ) throws IOException { Preconditions . checkNotNull ( inputStream ) ; Preconditions . checkArgument ( bytesCount >= 0 ) ; long toSkip = bytesCount ; while ( toSkip > 0 ) { final long skipped = inputStream . skip ( toSkip ) ; if ( skipped > 0 ) { toSkip -= skipped ; continue ; } if ( inputStream . read ( ) != - 1 ) { toSkip -- ; continue ; } return bytesCount - toSkip ; } return bytesCount ; }
Skips exactly bytesCount bytes in inputStream unless end of stream is reached first .
8,212
public void clearJob ( ) { EncodedImage oldEncodedImage ; synchronized ( this ) { oldEncodedImage = mEncodedImage ; mEncodedImage = null ; mStatus = 0 ; } EncodedImage . closeSafely ( oldEncodedImage ) ; }
Clears the currently set job .
8,213
private void ensureInitialized ( ) { if ( ! mInitialized ) { lock . lock ( ) ; try { if ( ! mInitialized ) { mInternalPath = Environment . getDataDirectory ( ) ; mExternalPath = Environment . getExternalStorageDirectory ( ) ; updateStats ( ) ; mInitialized = true ; } } finally { lock . unlock ( ) ; } } }
Initialization code that can sometimes take a long time .
8,214
@ SuppressLint ( "DeprecatedMethod" ) public long getFreeStorageSpace ( StorageType storageType ) { ensureInitialized ( ) ; maybeUpdateStats ( ) ; StatFs statFS = storageType == StorageType . INTERNAL ? mInternalStatFs : mExternalStatFs ; if ( statFS != null ) { long blockSize , availableBlocks ; if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . JELLY_BEAN_MR2 ) { blockSize = statFS . getBlockSizeLong ( ) ; availableBlocks = statFS . getFreeBlocksLong ( ) ; } else { blockSize = statFS . getBlockSize ( ) ; availableBlocks = statFS . getFreeBlocks ( ) ; } return blockSize * availableBlocks ; } return - 1 ; }
Gets the information about the free storage space including reserved blocks either internal or external depends on the given input
8,215
@ SuppressLint ( "DeprecatedMethod" ) public long getTotalStorageSpace ( StorageType storageType ) { ensureInitialized ( ) ; maybeUpdateStats ( ) ; StatFs statFS = storageType == StorageType . INTERNAL ? mInternalStatFs : mExternalStatFs ; if ( statFS != null ) { long blockSize , totalBlocks ; if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . JELLY_BEAN_MR2 ) { blockSize = statFS . getBlockSizeLong ( ) ; totalBlocks = statFS . getBlockCountLong ( ) ; } else { blockSize = statFS . getBlockSize ( ) ; totalBlocks = statFS . getBlockCount ( ) ; } return blockSize * totalBlocks ; } return - 1 ; }
Gets the information about the total storage space either internal or external depends on the given input
8,216
@ SuppressLint ( "DeprecatedMethod" ) public long getAvailableStorageSpace ( StorageType storageType ) { ensureInitialized ( ) ; maybeUpdateStats ( ) ; StatFs statFS = storageType == StorageType . INTERNAL ? mInternalStatFs : mExternalStatFs ; if ( statFS != null ) { long blockSize , availableBlocks ; if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . JELLY_BEAN_MR2 ) { blockSize = statFS . getBlockSizeLong ( ) ; availableBlocks = statFS . getAvailableBlocksLong ( ) ; } else { blockSize = statFS . getBlockSize ( ) ; availableBlocks = statFS . getAvailableBlocks ( ) ; } return blockSize * availableBlocks ; } return 0 ; }
Gets the information about the available storage space either internal or external depends on the give input
8,217
public void reset ( ) { mGestureInProgress = false ; mPointerCount = 0 ; for ( int i = 0 ; i < MAX_POINTERS ; i ++ ) { mId [ i ] = MotionEvent . INVALID_POINTER_ID ; } }
Resets the component to the initial state .
8,218
private int getPressedPointerIndex ( MotionEvent event , int i ) { final int count = event . getPointerCount ( ) ; final int action = event . getActionMasked ( ) ; final int index = event . getActionIndex ( ) ; if ( action == MotionEvent . ACTION_UP || action == MotionEvent . ACTION_POINTER_UP ) { if ( i >= index ) { i ++ ; } } return ( i < count ) ? i : - 1 ; }
Gets the index of the i - th pressed pointer . Normally the index will be equal to i except in the case when the pointer is released .
8,219
public boolean onTouchEvent ( final MotionEvent event ) { switch ( event . getActionMasked ( ) ) { case MotionEvent . ACTION_MOVE : { updatePointersOnMove ( event ) ; if ( ! mGestureInProgress && mPointerCount > 0 && shouldStartGesture ( ) ) { startGesture ( ) ; } if ( mGestureInProgress && mListener != null ) { mListener . onGestureUpdate ( this ) ; } break ; } case MotionEvent . ACTION_DOWN : case MotionEvent . ACTION_POINTER_DOWN : case MotionEvent . ACTION_POINTER_UP : case MotionEvent . ACTION_UP : { mNewPointerCount = getPressedPointerCount ( event ) ; stopGesture ( ) ; updatePointersOnTap ( event ) ; if ( mPointerCount > 0 && shouldStartGesture ( ) ) { startGesture ( ) ; } break ; } case MotionEvent . ACTION_CANCEL : { mNewPointerCount = 0 ; stopGesture ( ) ; reset ( ) ; break ; } } return true ; }
Handles the given motion event .
8,220
public boolean onTouchEvent ( MotionEvent event ) { switch ( event . getAction ( ) ) { case MotionEvent . ACTION_DOWN : mIsCapturingGesture = true ; mIsClickCandidate = true ; mActionDownTime = event . getEventTime ( ) ; mActionDownX = event . getX ( ) ; mActionDownY = event . getY ( ) ; break ; case MotionEvent . ACTION_MOVE : if ( Math . abs ( event . getX ( ) - mActionDownX ) > mSingleTapSlopPx || Math . abs ( event . getY ( ) - mActionDownY ) > mSingleTapSlopPx ) { mIsClickCandidate = false ; } break ; case MotionEvent . ACTION_CANCEL : mIsCapturingGesture = false ; mIsClickCandidate = false ; break ; case MotionEvent . ACTION_UP : mIsCapturingGesture = false ; if ( Math . abs ( event . getX ( ) - mActionDownX ) > mSingleTapSlopPx || Math . abs ( event . getY ( ) - mActionDownY ) > mSingleTapSlopPx ) { mIsClickCandidate = false ; } if ( mIsClickCandidate ) { if ( event . getEventTime ( ) - mActionDownTime <= ViewConfiguration . getLongPressTimeout ( ) ) { if ( mClickListener != null ) { mClickListener . onClick ( ) ; } } else { } } mIsClickCandidate = false ; break ; } return true ; }
Handles the touch event
8,221
public synchronized List < ProducerContextCallbacks > setIsPrefetchNoCallbacks ( boolean isPrefetch ) { if ( isPrefetch == mIsPrefetch ) { return null ; } mIsPrefetch = isPrefetch ; return new ArrayList < > ( mCallbacks ) ; }
Changes isPrefetch property .
8,222
public synchronized List < ProducerContextCallbacks > setPriorityNoCallbacks ( Priority priority ) { if ( priority == mPriority ) { return null ; } mPriority = priority ; return new ArrayList < > ( mCallbacks ) ; }
Changes priority .
8,223
public synchronized List < ProducerContextCallbacks > setIsIntermediateResultExpectedNoCallbacks ( boolean isIntermediateResultExpected ) { if ( isIntermediateResultExpected == mIsIntermediateResultExpected ) { return null ; } mIsIntermediateResultExpected = isIntermediateResultExpected ; return new ArrayList < > ( mCallbacks ) ; }
Changes isIntermediateResultExpected property .
8,224
public synchronized List < ProducerContextCallbacks > cancelNoCallbacks ( ) { if ( mIsCancelled ) { return null ; } mIsCancelled = true ; return new ArrayList < > ( mCallbacks ) ; }
Marks this ProducerContext as cancelled .
8,225
public static int getOrientation ( InputStream is ) { try { int length = moveToAPP1EXIF ( is ) ; if ( length == 0 ) { return ExifInterface . ORIENTATION_UNDEFINED ; } return TiffUtil . readOrientationFromTIFF ( is , length ) ; } catch ( IOException ioe ) { return ExifInterface . ORIENTATION_UNDEFINED ; } }
Get orientation information from jpeg input stream .
8,226
public static boolean moveToMarker ( InputStream is , int markerToFind ) throws IOException { Preconditions . checkNotNull ( is ) ; while ( StreamProcessor . readPackedInt ( is , 1 , false ) == MARKER_FIRST_BYTE ) { int marker = MARKER_FIRST_BYTE ; while ( marker == MARKER_FIRST_BYTE ) { marker = StreamProcessor . readPackedInt ( is , 1 , false ) ; } if ( markerToFind == MARKER_SOFn && isSOFn ( marker ) ) { return true ; } if ( marker == markerToFind ) { return true ; } if ( marker == MARKER_SOI || marker == MARKER_TEM ) { continue ; } if ( marker == MARKER_EOI || marker == MARKER_SOS ) { return false ; } int length = StreamProcessor . readPackedInt ( is , 2 , false ) - 2 ; is . skip ( length ) ; } return false ; }
Reads the content of the input stream until specified marker is found . Marker will be consumed and the input stream will be positioned after the specified marker .
8,227
private static int moveToAPP1EXIF ( InputStream is ) throws IOException { if ( moveToMarker ( is , MARKER_APP1 ) ) { int length = StreamProcessor . readPackedInt ( is , 2 , false ) - 2 ; if ( length > 6 ) { int magic = StreamProcessor . readPackedInt ( is , 4 , false ) ; length -= 4 ; int zero = StreamProcessor . readPackedInt ( is , 2 , false ) ; length -= 2 ; if ( magic == APP1_EXIF_MAGIC && zero == 0 ) { return length ; } } } return 0 ; }
Positions the given input stream to the beginning of the EXIF data in the JPEG APP1 block .
8,228
public void setZoomableController ( ZoomableController zoomableController ) { Preconditions . checkNotNull ( zoomableController ) ; mZoomableController . setListener ( null ) ; mZoomableController = zoomableController ; mZoomableController . setListener ( mZoomableListener ) ; }
Sets a custom zoomable controller instead of using the default one .
8,229
public void setScaleType ( ScaleType scaleType ) { if ( Objects . equal ( mScaleType , scaleType ) ) { return ; } mScaleType = scaleType ; mScaleTypeState = null ; configureBounds ( ) ; invalidateSelf ( ) ; }
Sets the scale type .
8,230
public static WriterCallback from ( final byte [ ] data ) { return new WriterCallback ( ) { public void write ( OutputStream os ) throws IOException { os . write ( data ) ; } } ; }
Creates a writer callback that writes some byte array to the target stream .
8,231
public void renderFrame ( int frameNumber , Bitmap bitmap ) { Canvas canvas = new Canvas ( bitmap ) ; canvas . drawColor ( Color . TRANSPARENT , PorterDuff . Mode . SRC ) ; int nextIndex ; if ( ! isKeyFrame ( frameNumber ) ) { nextIndex = prepareCanvasWithClosestCachedFrame ( frameNumber - 1 , canvas ) ; } else { nextIndex = frameNumber ; } for ( int index = nextIndex ; index < frameNumber ; index ++ ) { AnimatedDrawableFrameInfo frameInfo = mAnimatedDrawableBackend . getFrameInfo ( index ) ; DisposalMethod disposalMethod = frameInfo . disposalMethod ; if ( disposalMethod == DisposalMethod . DISPOSE_TO_PREVIOUS ) { continue ; } if ( frameInfo . blendOperation == BlendOperation . NO_BLEND ) { disposeToBackground ( canvas , frameInfo ) ; } mAnimatedDrawableBackend . renderFrame ( index , canvas ) ; mCallback . onIntermediateResult ( index , bitmap ) ; if ( disposalMethod == DisposalMethod . DISPOSE_TO_BACKGROUND ) { disposeToBackground ( canvas , frameInfo ) ; } } AnimatedDrawableFrameInfo frameInfo = mAnimatedDrawableBackend . getFrameInfo ( frameNumber ) ; if ( frameInfo . blendOperation == BlendOperation . NO_BLEND ) { disposeToBackground ( canvas , frameInfo ) ; } mAnimatedDrawableBackend . renderFrame ( frameNumber , canvas ) ; }
Renders the specified frame . Only should be called on the rendering thread .
8,232
private int prepareCanvasWithClosestCachedFrame ( int previousFrameNumber , Canvas canvas ) { for ( int index = previousFrameNumber ; index >= 0 ; index -- ) { FrameNeededResult neededResult = isFrameNeededForRendering ( index ) ; switch ( neededResult ) { case REQUIRED : AnimatedDrawableFrameInfo frameInfo = mAnimatedDrawableBackend . getFrameInfo ( index ) ; CloseableReference < Bitmap > startBitmap = mCallback . getCachedBitmap ( index ) ; if ( startBitmap != null ) { try { canvas . drawBitmap ( startBitmap . get ( ) , 0 , 0 , null ) ; if ( frameInfo . disposalMethod == DisposalMethod . DISPOSE_TO_BACKGROUND ) { disposeToBackground ( canvas , frameInfo ) ; } return index + 1 ; } finally { startBitmap . close ( ) ; } } else { if ( isKeyFrame ( index ) ) { return index ; } else { break ; } } case NOT_REQUIRED : return index + 1 ; case ABORT : return index ; case SKIP : default : } } return 0 ; }
Given a frame number prepares the canvas to render based on the nearest cached frame at or before the frame . On return the canvas will be prepared as if the nearest cached frame had been rendered and disposed . The returned index is the next frame that needs to be composited onto the canvas .
8,233
private void scale ( int viewPortWidth , int viewPortHeight , int sourceWidth , int sourceHeight ) { float inputRatio = ( ( float ) sourceWidth ) / sourceHeight ; float outputRatio = ( ( float ) viewPortWidth ) / viewPortHeight ; int scaledWidth = viewPortWidth ; int scaledHeight = viewPortHeight ; if ( outputRatio > inputRatio ) { scaledWidth = ( int ) ( viewPortHeight * inputRatio ) ; scaledHeight = viewPortHeight ; } else if ( outputRatio < inputRatio ) { scaledHeight = ( int ) ( viewPortWidth / inputRatio ) ; scaledWidth = viewPortWidth ; } float scale = scaledWidth / ( float ) sourceWidth ; mMidX = ( ( viewPortWidth - scaledWidth ) / 2f ) / scale ; mMidY = ( ( viewPortHeight - scaledHeight ) / 2f ) / scale ; }
Measures the source and sets the size based on them . Maintains aspect ratio of source and ensures that screen is filled in at least one dimension .
8,234
static CloseableReference < Bitmap > convertToBitmapReferenceAndClose ( final CloseableReference < CloseableImage > closeableImage ) { try { if ( CloseableReference . isValid ( closeableImage ) && closeableImage . get ( ) instanceof CloseableStaticBitmap ) { CloseableStaticBitmap closeableStaticBitmap = ( CloseableStaticBitmap ) closeableImage . get ( ) ; if ( closeableStaticBitmap != null ) { return closeableStaticBitmap . cloneUnderlyingBitmapReference ( ) ; } } return null ; } finally { CloseableReference . closeSafely ( closeableImage ) ; } }
Converts the given image reference to a bitmap reference and closes the original image reference .
8,235
synchronized DiskStorage get ( ) throws IOException { if ( shouldCreateNewStorage ( ) ) { deleteOldStorageIfNecessary ( ) ; createStorage ( ) ; } return Preconditions . checkNotNull ( mCurrentState . delegate ) ; }
Gets a concrete disk - storage instance . If nothing has changed since the last call then the last state is returned
8,236
static ScaleTypeDrawable wrapChildWithScaleType ( DrawableParent parent , ScalingUtils . ScaleType scaleType ) { Drawable child = parent . setDrawable ( sEmptyDrawable ) ; child = maybeWrapWithScaleType ( child , scaleType ) ; parent . setDrawable ( child ) ; Preconditions . checkNotNull ( child , "Parent has no child drawable!" ) ; return ( ScaleTypeDrawable ) child ; }
Wraps the parent s child with a ScaleTypeDrawable .
8,237
static void applyRoundingParams ( Rounded rounded , RoundingParams roundingParams ) { rounded . setCircle ( roundingParams . getRoundAsCircle ( ) ) ; rounded . setRadii ( roundingParams . getCornersRadii ( ) ) ; rounded . setBorder ( roundingParams . getBorderColor ( ) , roundingParams . getBorderWidth ( ) ) ; rounded . setPadding ( roundingParams . getPadding ( ) ) ; rounded . setScaleDownInsideBorders ( roundingParams . getScaleDownInsideBorders ( ) ) ; rounded . setPaintFilterBitmap ( roundingParams . getPaintFilterBitmap ( ) ) ; }
Applies the given rounding params on the specified rounded drawable .
8,238
static void resetRoundingParams ( Rounded rounded ) { rounded . setCircle ( false ) ; rounded . setRadius ( 0 ) ; rounded . setBorder ( Color . TRANSPARENT , 0 ) ; rounded . setPadding ( 0 ) ; rounded . setScaleDownInsideBorders ( false ) ; rounded . setPaintFilterBitmap ( false ) ; }
Resets the rounding params on the specified rounded drawable so that no rounding occurs .
8,239
static DrawableParent findDrawableParentForLeaf ( DrawableParent parent ) { while ( true ) { Drawable child = parent . getDrawable ( ) ; if ( child == parent || ! ( child instanceof DrawableParent ) ) { break ; } parent = ( DrawableParent ) child ; } return parent ; }
Finds the immediate parent of a leaf drawable .
8,240
private static boolean hasColorGamutMismatch ( final BitmapFactory . Options options ) { return options . outColorSpace != null && options . outColorSpace . isWideGamut ( ) && options . inPreferredConfig != Bitmap . Config . RGBA_F16 ; }
Check if the color space has a wide color gamut and is consistent with the Bitmap config
8,241
public static ImagePipelineConfig getImagePipelineConfig ( Context context ) { if ( sImagePipelineConfig == null ) { ImagePipelineConfig . Builder configBuilder = ImagePipelineConfig . newBuilder ( context ) ; configureCaches ( configBuilder , context ) ; configureLoggingListeners ( configBuilder ) ; configureOptions ( configBuilder ) ; sImagePipelineConfig = configBuilder . build ( ) ; } return sImagePipelineConfig ; }
Creates config using android http stack as network backend .
8,242
public static ImagePipelineConfig getOkHttpImagePipelineConfig ( Context context ) { if ( sOkHttpImagePipelineConfig == null ) { OkHttpClient okHttpClient = new OkHttpClient . Builder ( ) . addNetworkInterceptor ( new StethoInterceptor ( ) ) . build ( ) ; ImagePipelineConfig . Builder configBuilder = OkHttpImagePipelineConfigFactory . newBuilder ( context , okHttpClient ) ; configureCaches ( configBuilder , context ) ; configureLoggingListeners ( configBuilder ) ; sOkHttpImagePipelineConfig = configBuilder . build ( ) ; } return sOkHttpImagePipelineConfig ; }
Creates config using OkHttp as network backed .
8,243
private static void configureCaches ( ImagePipelineConfig . Builder configBuilder , Context context ) { final MemoryCacheParams bitmapCacheParams = new MemoryCacheParams ( ConfigConstants . MAX_MEMORY_CACHE_SIZE , Integer . MAX_VALUE , ConfigConstants . MAX_MEMORY_CACHE_SIZE , Integer . MAX_VALUE , Integer . MAX_VALUE , TimeUnit . MINUTES . toMillis ( 5 ) ) ; configBuilder . setBitmapMemoryCacheParamsSupplier ( new Supplier < MemoryCacheParams > ( ) { public MemoryCacheParams get ( ) { return bitmapCacheParams ; } } ) . setMainDiskCacheConfig ( DiskCacheConfig . newBuilder ( context ) . setBaseDirectoryPath ( context . getApplicationContext ( ) . getCacheDir ( ) ) . setBaseDirectoryName ( IMAGE_PIPELINE_CACHE_DIR ) . setMaxCacheSize ( ConfigConstants . MAX_DISK_CACHE_SIZE ) . build ( ) ) ; }
Configures disk and memory cache not to exceed common limits
8,244
public void close ( ) { CloseableReference < Bitmap > reference = detachBitmapReference ( ) ; if ( reference != null ) { reference . close ( ) ; } }
Releases the bitmap to the pool .
8,245
public V get ( ) { V value = pop ( ) ; if ( value != null ) { mInUseLength ++ ; } return value ; }
Gets a free item if possible from the freelist . Returns null if the free list is empty Updates the bucket inUse count
8,246
public void release ( V value ) { Preconditions . checkNotNull ( value ) ; if ( mFixBucketsReinitialization ) { Preconditions . checkState ( mInUseLength > 0 ) ; mInUseLength -- ; addToFreeList ( value ) ; } else { if ( mInUseLength > 0 ) { mInUseLength -- ; addToFreeList ( value ) ; } else { FLog . e ( TAG , "Tried to release value %s from an empty bucket!" , value ) ; } } }
Releases a value to this bucket and decrements the inUse count
8,247
public static < T > IncreasingQualityDataSourceSupplier < T > create ( List < Supplier < DataSource < T > > > dataSourceSuppliers ) { return create ( dataSourceSuppliers , false ) ; }
Creates a new data source supplier with increasing - quality strategy .
8,248
public static < T > IncreasingQualityDataSourceSupplier < T > create ( List < Supplier < DataSource < T > > > dataSourceSuppliers , boolean dataSourceLazy ) { return new IncreasingQualityDataSourceSupplier < T > ( dataSourceSuppliers , dataSourceLazy ) ; }
Creates a new data source supplier with increasing - quality strategy with optional lazy state creation .
8,249
public float getTranslationX ( ) { return calcAverage ( mDetector . getCurrentX ( ) , mDetector . getPointerCount ( ) ) - calcAverage ( mDetector . getStartX ( ) , mDetector . getPointerCount ( ) ) ; }
Gets the X component of the translation
8,250
public float getTranslationY ( ) { return calcAverage ( mDetector . getCurrentY ( ) , mDetector . getPointerCount ( ) ) - calcAverage ( mDetector . getStartY ( ) , mDetector . getPointerCount ( ) ) ; }
Gets the Y component of the translation
8,251
public float getScale ( ) { if ( mDetector . getPointerCount ( ) < 2 ) { return 1 ; } else { float startDeltaX = mDetector . getStartX ( ) [ 1 ] - mDetector . getStartX ( ) [ 0 ] ; float startDeltaY = mDetector . getStartY ( ) [ 1 ] - mDetector . getStartY ( ) [ 0 ] ; float currentDeltaX = mDetector . getCurrentX ( ) [ 1 ] - mDetector . getCurrentX ( ) [ 0 ] ; float currentDeltaY = mDetector . getCurrentY ( ) [ 1 ] - mDetector . getCurrentY ( ) [ 0 ] ; float startDist = ( float ) Math . hypot ( startDeltaX , startDeltaY ) ; float currentDist = ( float ) Math . hypot ( currentDeltaX , currentDeltaY ) ; return currentDist / startDist ; } }
Gets the scale
8,252
public float getRotation ( ) { if ( mDetector . getPointerCount ( ) < 2 ) { return 0 ; } else { float startDeltaX = mDetector . getStartX ( ) [ 1 ] - mDetector . getStartX ( ) [ 0 ] ; float startDeltaY = mDetector . getStartY ( ) [ 1 ] - mDetector . getStartY ( ) [ 0 ] ; float currentDeltaX = mDetector . getCurrentX ( ) [ 1 ] - mDetector . getCurrentX ( ) [ 0 ] ; float currentDeltaY = mDetector . getCurrentY ( ) [ 1 ] - mDetector . getCurrentY ( ) [ 0 ] ; float startAngle = ( float ) Math . atan2 ( startDeltaY , startDeltaX ) ; float currentAngle = ( float ) Math . atan2 ( currentDeltaY , currentDeltaX ) ; return currentAngle - startAngle ; } }
Gets the rotation in radians
8,253
public void dump ( DumperContext dumpContext ) throws DumpException { ensureInitialized ( ) ; List < String > args = dumpContext . getArgsAsList ( ) ; PrintStream writer = dumpContext . getStdout ( ) ; String cmd = args . isEmpty ( ) ? null : args . get ( 0 ) ; List < String > rest = args . isEmpty ( ) ? new ArrayList < String > ( ) : args . subList ( 1 , args . size ( ) ) ; if ( cmd != null && cmd . equals ( "memcache" ) ) { memcache ( writer , rest ) ; } else if ( cmd != null && cmd . equals ( "diskcache" ) ) { diskcache ( mMainFileCache , "Main" , writer , rest ) ; diskcache ( mSmallFileCache , "Small" , writer , rest ) ; } else { usage ( writer ) ; if ( TextUtils . isEmpty ( cmd ) ) { throw new DumpUsageException ( "Missing command" ) ; } else { throw new DumpUsageException ( "Unknown command: " + cmd ) ; } } }
Entry point for the Stetho dumpapp script .
8,254
public void onAttach ( ) { if ( mIsAttached ) { return ; } mIsAttached = true ; for ( int i = 0 ; i < mHolders . size ( ) ; ++ i ) { mHolders . get ( i ) . onAttach ( ) ; } }
Gets the controller ready to display the images .
8,255
public void onDetach ( ) { if ( ! mIsAttached ) { return ; } mIsAttached = false ; for ( int i = 0 ; i < mHolders . size ( ) ; ++ i ) { mHolders . get ( i ) . onDetach ( ) ; } }
Releases resources used to display the image .
8,256
public void draw ( Canvas canvas ) { for ( int i = 0 ; i < mHolders . size ( ) ; ++ i ) { Drawable drawable = get ( i ) . getTopLevelDrawable ( ) ; if ( drawable != null ) { drawable . draw ( canvas ) ; } } }
Convenience method to draw all the top - level drawables in this holder .
8,257
public boolean verifyDrawable ( Drawable who ) { for ( int i = 0 ; i < mHolders . size ( ) ; ++ i ) { if ( who == get ( i ) . getTopLevelDrawable ( ) ) { return true ; } } return false ; }
Returns true if the argument is a top - level Drawable in this holder .
8,258
public ImageDecodeOptionsBuilder setFrom ( ImageDecodeOptions options ) { mDecodePreviewFrame = options . decodePreviewFrame ; mUseLastFrameForPreview = options . useLastFrameForPreview ; mDecodeAllFrames = options . decodeAllFrames ; mForceStaticImage = options . forceStaticImage ; mBitmapConfig = options . bitmapConfig ; mCustomImageDecoder = options . customImageDecoder ; mBitmapTransformation = options . bitmapTransformation ; mColorSpace = options . colorSpace ; return this ; }
Sets the builder to be equivalent to the specified options .
8,259
public static void toCircle ( Bitmap bitmap , boolean antiAliased ) { Preconditions . checkNotNull ( bitmap ) ; nativeToCircleFilter ( bitmap , antiAliased ) ; }
This is a fast native implementation for rounding a bitmap . It takes the given bitmap and modifies it to be circular .
8,260
public synchronized void onProgressUpdate ( float progress ) { if ( mIsFinished ) { return ; } try { onProgressUpdateImpl ( progress ) ; } catch ( Exception e ) { onUnhandledException ( e ) ; } }
Called when the progress updates .
8,261
public Task < Boolean > contains ( final CacheKey key ) { if ( containsSync ( key ) ) { return Task . forResult ( true ) ; } return containsAsync ( key ) ; }
Performs a key - value look up in the disk cache . If no value is found in the staging area then disk cache checks are scheduled on a background thread . Any error manifests itself as a cache miss i . e . the returned Task resolves to false .
8,262
public Task < EncodedImage > get ( CacheKey key , AtomicBoolean isCancelled ) { try { if ( FrescoSystrace . isTracing ( ) ) { FrescoSystrace . beginSection ( "BufferedDiskCache#get" ) ; } final EncodedImage pinnedImage = mStagingArea . get ( key ) ; if ( pinnedImage != null ) { return foundPinnedImage ( key , pinnedImage ) ; } return getAsync ( key , isCancelled ) ; } finally { if ( FrescoSystrace . isTracing ( ) ) { FrescoSystrace . endSection ( ) ; } } }
Performs key - value look up in disk cache . If value is not found in disk cache staging area then disk cache read is scheduled on background thread . Any error manifests itself as cache miss i . e . the returned task resolves to null .
8,263
private boolean checkInStagingAreaAndFileCache ( final CacheKey key ) { EncodedImage result = mStagingArea . get ( key ) ; if ( result != null ) { result . close ( ) ; FLog . v ( TAG , "Found image for %s in staging area" , key . getUriString ( ) ) ; mImageCacheStatsTracker . onStagingAreaHit ( key ) ; return true ; } else { FLog . v ( TAG , "Did not find image for %s in staging area" , key . getUriString ( ) ) ; mImageCacheStatsTracker . onStagingAreaMiss ( ) ; try { return mFileCache . hasKey ( key ) ; } catch ( Exception exception ) { return false ; } } }
Performs key - value loop up in staging area and file cache . Any error manifests itself as a miss i . e . returns false .
8,264
public void put ( final CacheKey key , EncodedImage encodedImage ) { try { if ( FrescoSystrace . isTracing ( ) ) { FrescoSystrace . beginSection ( "BufferedDiskCache#put" ) ; } Preconditions . checkNotNull ( key ) ; Preconditions . checkArgument ( EncodedImage . isValid ( encodedImage ) ) ; mStagingArea . put ( key , encodedImage ) ; final EncodedImage finalEncodedImage = EncodedImage . cloneOrNull ( encodedImage ) ; try { mWriteExecutor . execute ( new Runnable ( ) { public void run ( ) { try { if ( FrescoSystrace . isTracing ( ) ) { FrescoSystrace . beginSection ( "BufferedDiskCache#putAsync" ) ; } writeToDiskCache ( key , finalEncodedImage ) ; } finally { mStagingArea . remove ( key , finalEncodedImage ) ; EncodedImage . closeSafely ( finalEncodedImage ) ; if ( FrescoSystrace . isTracing ( ) ) { FrescoSystrace . endSection ( ) ; } } } } ) ; } catch ( Exception exception ) { FLog . w ( TAG , exception , "Failed to schedule disk-cache write for %s" , key . getUriString ( ) ) ; mStagingArea . remove ( key , encodedImage ) ; EncodedImage . closeSafely ( finalEncodedImage ) ; } } finally { if ( FrescoSystrace . isTracing ( ) ) { FrescoSystrace . endSection ( ) ; } } }
Associates encodedImage with given key in disk cache . Disk write is performed on background thread so the caller of this method is not blocked
8,265
public Task < Void > remove ( final CacheKey key ) { Preconditions . checkNotNull ( key ) ; mStagingArea . remove ( key ) ; try { return Task . call ( new Callable < Void > ( ) { public Void call ( ) throws Exception { try { if ( FrescoSystrace . isTracing ( ) ) { FrescoSystrace . beginSection ( "BufferedDiskCache#remove" ) ; } mStagingArea . remove ( key ) ; mFileCache . remove ( key ) ; } finally { if ( FrescoSystrace . isTracing ( ) ) { FrescoSystrace . endSection ( ) ; } } return null ; } } , mWriteExecutor ) ; } catch ( Exception exception ) { FLog . w ( TAG , exception , "Failed to schedule disk-cache remove for %s" , key . getUriString ( ) ) ; return Task . forError ( exception ) ; } }
Removes the item from the disk cache and the staging area .
8,266
public Task < Void > clearAll ( ) { mStagingArea . clearAll ( ) ; try { return Task . call ( new Callable < Void > ( ) { public Void call ( ) throws Exception { mStagingArea . clearAll ( ) ; mFileCache . clearAll ( ) ; return null ; } } , mWriteExecutor ) ; } catch ( Exception exception ) { FLog . w ( TAG , exception , "Failed to schedule disk-cache clear" ) ; return Task . forError ( exception ) ; } }
Clears the disk cache and the staging area .
8,267
private PooledByteBuffer readFromDiskCache ( final CacheKey key ) throws IOException { try { FLog . v ( TAG , "Disk cache read for %s" , key . getUriString ( ) ) ; final BinaryResource diskCacheResource = mFileCache . getResource ( key ) ; if ( diskCacheResource == null ) { FLog . v ( TAG , "Disk cache miss for %s" , key . getUriString ( ) ) ; mImageCacheStatsTracker . onDiskCacheMiss ( ) ; return null ; } else { FLog . v ( TAG , "Found entry in disk cache for %s" , key . getUriString ( ) ) ; mImageCacheStatsTracker . onDiskCacheHit ( key ) ; } PooledByteBuffer byteBuffer ; final InputStream is = diskCacheResource . openStream ( ) ; try { byteBuffer = mPooledByteBufferFactory . newByteBuffer ( is , ( int ) diskCacheResource . size ( ) ) ; } finally { is . close ( ) ; } FLog . v ( TAG , "Successful read from disk cache for %s" , key . getUriString ( ) ) ; return byteBuffer ; } catch ( IOException ioe ) { FLog . w ( TAG , ioe , "Exception reading from cache for %s" , key . getUriString ( ) ) ; mImageCacheStatsTracker . onDiskCacheGetFail ( ) ; throw ioe ; } }
Performs disk cache read . In case of any exception null is returned .
8,268
private void writeToDiskCache ( final CacheKey key , final EncodedImage encodedImage ) { FLog . v ( TAG , "About to write to disk-cache for key %s" , key . getUriString ( ) ) ; try { mFileCache . insert ( key , new WriterCallback ( ) { public void write ( OutputStream os ) throws IOException { mPooledByteStreams . copy ( encodedImage . getInputStream ( ) , os ) ; } } ) ; FLog . v ( TAG , "Successful disk-cache write for key %s" , key . getUriString ( ) ) ; } catch ( IOException ioe ) { FLog . w ( TAG , ioe , "Failed to write to disk-cache for key %s" , key . getUriString ( ) ) ; } }
Writes to disk cache
8,269
private synchronized boolean canCacheNewValue ( V value ) { int newValueSize = mValueDescriptor . getSizeInBytes ( value ) ; return ( newValueSize <= mMemoryCacheParams . maxCacheEntrySize ) && ( getInUseCount ( ) <= mMemoryCacheParams . maxCacheEntries - 1 ) && ( getInUseSizeInBytes ( ) <= mMemoryCacheParams . maxCacheSize - newValueSize ) ; }
Checks the cache constraints to determine whether the new value can be cached or not .
8,270
public CloseableReference < V > get ( final K key ) { Preconditions . checkNotNull ( key ) ; Entry < K , V > oldExclusive ; CloseableReference < V > clientRef = null ; synchronized ( this ) { oldExclusive = mExclusiveEntries . remove ( key ) ; Entry < K , V > entry = mCachedEntries . get ( key ) ; if ( entry != null ) { clientRef = newClientReference ( entry ) ; } } maybeNotifyExclusiveEntryRemoval ( oldExclusive ) ; maybeUpdateCacheParams ( ) ; maybeEvictEntries ( ) ; return clientRef ; }
Gets the item with the given key or null if there is no such item .
8,271
private synchronized CloseableReference < V > newClientReference ( final Entry < K , V > entry ) { increaseClientCount ( entry ) ; return CloseableReference . of ( entry . valueRef . get ( ) , new ResourceReleaser < V > ( ) { public void release ( V unused ) { releaseClientReference ( entry ) ; } } ) ; }
Creates a new reference for the client .
8,272
private void releaseClientReference ( final Entry < K , V > entry ) { Preconditions . checkNotNull ( entry ) ; boolean isExclusiveAdded ; CloseableReference < V > oldRefToClose ; synchronized ( this ) { decreaseClientCount ( entry ) ; isExclusiveAdded = maybeAddToExclusives ( entry ) ; oldRefToClose = referenceToClose ( entry ) ; } CloseableReference . closeSafely ( oldRefToClose ) ; maybeNotifyExclusiveEntryInsertion ( isExclusiveAdded ? entry : null ) ; maybeUpdateCacheParams ( ) ; maybeEvictEntries ( ) ; }
Called when the client closes its reference .
8,273
private synchronized boolean maybeAddToExclusives ( Entry < K , V > entry ) { if ( ! entry . isOrphan && entry . clientCount == 0 ) { mExclusiveEntries . put ( entry . key , entry ) ; return true ; } return false ; }
Adds the entry to the exclusively owned queue if it is viable for eviction .
8,274
public CloseableReference < V > reuse ( K key ) { Preconditions . checkNotNull ( key ) ; CloseableReference < V > clientRef = null ; boolean removed = false ; Entry < K , V > oldExclusive = null ; synchronized ( this ) { oldExclusive = mExclusiveEntries . remove ( key ) ; if ( oldExclusive != null ) { Entry < K , V > entry = mCachedEntries . remove ( key ) ; Preconditions . checkNotNull ( entry ) ; Preconditions . checkState ( entry . clientCount == 0 ) ; clientRef = entry . valueRef ; removed = true ; } } if ( removed ) { maybeNotifyExclusiveEntryRemoval ( oldExclusive ) ; } return clientRef ; }
Gets the value with the given key to be reused or null if there is no such value .
8,275
public int removeAll ( Predicate < K > predicate ) { ArrayList < Entry < K , V > > oldExclusives ; ArrayList < Entry < K , V > > oldEntries ; synchronized ( this ) { oldExclusives = mExclusiveEntries . removeAll ( predicate ) ; oldEntries = mCachedEntries . removeAll ( predicate ) ; makeOrphans ( oldEntries ) ; } maybeClose ( oldEntries ) ; maybeNotifyExclusiveEntryRemoval ( oldExclusives ) ; maybeUpdateCacheParams ( ) ; maybeEvictEntries ( ) ; return oldEntries . size ( ) ; }
Removes all the items from the cache whose key matches the specified predicate .
8,276
public void clear ( ) { ArrayList < Entry < K , V > > oldExclusives ; ArrayList < Entry < K , V > > oldEntries ; synchronized ( this ) { oldExclusives = mExclusiveEntries . clear ( ) ; oldEntries = mCachedEntries . clear ( ) ; makeOrphans ( oldEntries ) ; } maybeClose ( oldEntries ) ; maybeNotifyExclusiveEntryRemoval ( oldExclusives ) ; maybeUpdateCacheParams ( ) ; }
Removes all the items from the cache .
8,277
public void trim ( MemoryTrimType trimType ) { ArrayList < Entry < K , V > > oldEntries ; final double trimRatio = mCacheTrimStrategy . getTrimRatio ( trimType ) ; synchronized ( this ) { int targetCacheSize = ( int ) ( mCachedEntries . getSizeInBytes ( ) * ( 1 - trimRatio ) ) ; int targetEvictionQueueSize = Math . max ( 0 , targetCacheSize - getInUseSizeInBytes ( ) ) ; oldEntries = trimExclusivelyOwnedEntries ( Integer . MAX_VALUE , targetEvictionQueueSize ) ; makeOrphans ( oldEntries ) ; } maybeClose ( oldEntries ) ; maybeNotifyExclusiveEntryRemoval ( oldEntries ) ; maybeUpdateCacheParams ( ) ; maybeEvictEntries ( ) ; }
Trims the cache according to the specified trimming strategy and the given trim type .
8,278
private void maybeEvictEntries ( ) { ArrayList < Entry < K , V > > oldEntries ; synchronized ( this ) { int maxCount = Math . min ( mMemoryCacheParams . maxEvictionQueueEntries , mMemoryCacheParams . maxCacheEntries - getInUseCount ( ) ) ; int maxSize = Math . min ( mMemoryCacheParams . maxEvictionQueueSize , mMemoryCacheParams . maxCacheSize - getInUseSizeInBytes ( ) ) ; oldEntries = trimExclusivelyOwnedEntries ( maxCount , maxSize ) ; makeOrphans ( oldEntries ) ; } maybeClose ( oldEntries ) ; maybeNotifyExclusiveEntryRemoval ( oldEntries ) ; }
Removes the exclusively owned items until the cache constraints are met .
8,279
private synchronized void makeOrphan ( Entry < K , V > entry ) { Preconditions . checkNotNull ( entry ) ; Preconditions . checkState ( ! entry . isOrphan ) ; entry . isOrphan = true ; }
Marks the entry as orphan .
8,280
private synchronized void increaseClientCount ( Entry < K , V > entry ) { Preconditions . checkNotNull ( entry ) ; Preconditions . checkState ( ! entry . isOrphan ) ; entry . clientCount ++ ; }
Increases the entry s client count .
8,281
private synchronized void decreaseClientCount ( Entry < K , V > entry ) { Preconditions . checkNotNull ( entry ) ; Preconditions . checkState ( entry . clientCount > 0 ) ; entry . clientCount -- ; }
Decreases the entry s client count .
8,282
private synchronized CloseableReference < V > referenceToClose ( Entry < K , V > entry ) { Preconditions . checkNotNull ( entry ) ; return ( entry . isOrphan && entry . clientCount == 0 ) ? entry . valueRef : null ; }
Returns the value reference of the entry if it should be closed null otherwise .
8,283
public void onVisibilityChange ( boolean isVisible ) { if ( mIsVisible == isVisible ) { return ; } mEventTracker . recordEvent ( isVisible ? Event . ON_DRAWABLE_SHOW : Event . ON_DRAWABLE_HIDE ) ; mIsVisible = isVisible ; attachOrDetachController ( ) ; }
Callback used to notify about top - level - drawable s visibility changes .
8,284
public void onDraw ( ) { if ( mIsControllerAttached ) { return ; } FLog . w ( DraweeEventTracker . class , "%x: Draw requested for a non-attached controller %x. %s" , System . identityHashCode ( this ) , System . identityHashCode ( mController ) , toString ( ) ) ; mIsHolderAttached = true ; mIsVisible = true ; attachOrDetachController ( ) ; }
Callback used to notify about top - level - drawable being drawn .
8,285
public void setHierarchy ( DH hierarchy ) { mEventTracker . recordEvent ( Event . ON_SET_HIERARCHY ) ; final boolean isControllerValid = isControllerValid ( ) ; setVisibilityCallback ( null ) ; mHierarchy = Preconditions . checkNotNull ( hierarchy ) ; Drawable drawable = mHierarchy . getTopLevelDrawable ( ) ; onVisibilityChange ( drawable == null || drawable . isVisible ( ) ) ; setVisibilityCallback ( this ) ; if ( isControllerValid ) { mController . setHierarchy ( hierarchy ) ; } }
Sets the drawee hierarchy .
8,286
public CloseableReference < Bitmap > process ( Bitmap sourceBitmap , PlatformBitmapFactory bitmapFactory ) { final Bitmap . Config sourceBitmapConfig = sourceBitmap . getConfig ( ) ; CloseableReference < Bitmap > destBitmapRef = bitmapFactory . createBitmapInternal ( sourceBitmap . getWidth ( ) , sourceBitmap . getHeight ( ) , sourceBitmapConfig != null ? sourceBitmapConfig : FALLBACK_BITMAP_CONFIGURATION ) ; try { process ( destBitmapRef . get ( ) , sourceBitmap ) ; return CloseableReference . cloneOrNull ( destBitmapRef ) ; } finally { CloseableReference . closeSafely ( destBitmapRef ) ; } }
Clients should override this method only if the post - processed bitmap has to be of a different size than the source bitmap . If the post - processed bitmap is of the same size clients should override one of the other two methods .
8,287
private boolean doParseMoreData ( final InputStream inputStream ) { final int oldBestScanNumber = mBestScanNumber ; try { int nextByte ; while ( mParserState != NOT_A_JPEG && ( nextByte = inputStream . read ( ) ) != - 1 ) { mBytesParsed ++ ; if ( mEndMarkerRead ) { mParserState = NOT_A_JPEG ; mEndMarkerRead = false ; return false ; } switch ( mParserState ) { case READ_FIRST_JPEG_BYTE : if ( nextByte == JfifUtil . MARKER_FIRST_BYTE ) { mParserState = READ_SECOND_JPEG_BYTE ; } else { mParserState = NOT_A_JPEG ; } break ; case READ_SECOND_JPEG_BYTE : if ( nextByte == JfifUtil . MARKER_SOI ) { mParserState = READ_MARKER_FIRST_BYTE_OR_ENTROPY_DATA ; } else { mParserState = NOT_A_JPEG ; } break ; case READ_MARKER_FIRST_BYTE_OR_ENTROPY_DATA : if ( nextByte == JfifUtil . MARKER_FIRST_BYTE ) { mParserState = READ_MARKER_SECOND_BYTE ; } break ; case READ_MARKER_SECOND_BYTE : if ( nextByte == JfifUtil . MARKER_FIRST_BYTE ) { mParserState = READ_MARKER_SECOND_BYTE ; } else if ( nextByte == JfifUtil . MARKER_ESCAPE_BYTE ) { mParserState = READ_MARKER_FIRST_BYTE_OR_ENTROPY_DATA ; } else if ( nextByte == JfifUtil . MARKER_EOI ) { mEndMarkerRead = true ; newScanOrImageEndFound ( mBytesParsed - 2 ) ; mParserState = READ_MARKER_FIRST_BYTE_OR_ENTROPY_DATA ; } else { if ( nextByte == JfifUtil . MARKER_SOS ) { newScanOrImageEndFound ( mBytesParsed - 2 ) ; } if ( doesMarkerStartSegment ( nextByte ) ) { mParserState = READ_SIZE_FIRST_BYTE ; } else { mParserState = READ_MARKER_FIRST_BYTE_OR_ENTROPY_DATA ; } } break ; case READ_SIZE_FIRST_BYTE : mParserState = READ_SIZE_SECOND_BYTE ; break ; case READ_SIZE_SECOND_BYTE : final int size = ( mLastByteRead << 8 ) + nextByte ; final int bytesToSkip = size - 2 ; StreamUtil . skip ( inputStream , bytesToSkip ) ; mBytesParsed += bytesToSkip ; mParserState = READ_MARKER_FIRST_BYTE_OR_ENTROPY_DATA ; break ; case NOT_A_JPEG : default : Preconditions . checkState ( false ) ; } mLastByteRead = nextByte ; } } catch ( IOException ioe ) { Throwables . propagate ( ioe ) ; } return mParserState != NOT_A_JPEG && mBestScanNumber != oldBestScanNumber ; }
Parses more data from inputStream .
8,288
private static boolean doesMarkerStartSegment ( int markerSecondByte ) { if ( markerSecondByte == JfifUtil . MARKER_TEM ) { return false ; } if ( markerSecondByte >= JfifUtil . MARKER_RST0 && markerSecondByte <= JfifUtil . MARKER_RST7 ) { return false ; } return markerSecondByte != JfifUtil . MARKER_EOI && markerSecondByte != JfifUtil . MARKER_SOI ; }
Not every marker is followed by associated segment
8,289
public static ValueAnimator createValueAnimator ( Drawable drawable , int maxDurationMs ) { if ( Build . VERSION . SDK_INT < Build . VERSION_CODES . HONEYCOMB ) { return null ; } if ( drawable instanceof AnimatedDrawable2 ) { return AnimatedDrawable2ValueAnimatorHelper . createValueAnimator ( ( AnimatedDrawable2 ) drawable , maxDurationMs ) ; } return null ; }
Create a value animator for the given animation drawable and max animation duration in ms .
8,290
@ TargetApi ( Build . VERSION_CODES . HONEYCOMB ) public static RoundedColorDrawable fromColorDrawable ( ColorDrawable colorDrawable ) { return new RoundedColorDrawable ( colorDrawable . getColor ( ) ) ; }
Creates a new instance of RoundedColorDrawable from the given ColorDrawable .
8,291
public void setRadius ( float radius ) { Preconditions . checkArgument ( radius >= 0 , "radius should be non negative" ) ; Arrays . fill ( mRadii , radius ) ; updatePath ( ) ; invalidateSelf ( ) ; }
Sets the rounding radius .
8,292
private static void addLiveReference ( Object value ) { synchronized ( sLiveObjects ) { Integer count = sLiveObjects . get ( value ) ; if ( count == null ) { sLiveObjects . put ( value , 1 ) ; } else { sLiveObjects . put ( value , count + 1 ) ; } } }
Increases the reference count of a live object in the static map . Adds it if it s not being held .
8,293
private static void removeLiveReference ( Object value ) { synchronized ( sLiveObjects ) { Integer count = sLiveObjects . get ( value ) ; if ( count == null ) { FLog . wtf ( "SharedReference" , "No entry in sLiveObjects for value of type %s" , value . getClass ( ) ) ; } else if ( count == 1 ) { sLiveObjects . remove ( value ) ; } else { sLiveObjects . put ( value , count - 1 ) ; } } }
Decreases the reference count of live object from the static map . Removes it if it s reference count has become 0 .
8,294
public void deleteReference ( ) { if ( decreaseRefCount ( ) == 0 ) { T deleted ; synchronized ( this ) { deleted = mValue ; mValue = null ; } mResourceReleaser . release ( deleted ) ; removeLiveReference ( deleted ) ; } }
Decrement the reference count for the shared reference . If the reference count drops to zero then dispose of the referenced value
8,295
private void init ( Context context ) { try { if ( FrescoSystrace . isTracing ( ) ) { FrescoSystrace . beginSection ( "DraweeView#init" ) ; } if ( mInitialised ) { return ; } mInitialised = true ; mDraweeHolder = DraweeHolder . create ( null , context ) ; if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . LOLLIPOP ) { ColorStateList imageTintList = getImageTintList ( ) ; if ( imageTintList == null ) { return ; } setColorFilter ( imageTintList . getDefaultColor ( ) ) ; } mLegacyVisibilityHandlingEnabled = sGlobalLegacyVisibilityHandlingEnabled && context . getApplicationInfo ( ) . targetSdkVersion >= 24 ; } finally { if ( FrescoSystrace . isTracing ( ) ) { FrescoSystrace . endSection ( ) ; } } }
This method is idempotent so it only has effect the first time it s called
8,296
static byte [ ] readFile ( InputStream in , long expectedSize ) throws IOException { if ( expectedSize > Integer . MAX_VALUE ) { throw new OutOfMemoryError ( "file is too large to fit in a byte array: " + expectedSize + " bytes" ) ; } return expectedSize == 0 ? ByteStreams . toByteArray ( in ) : ByteStreams . toByteArray ( in , ( int ) expectedSize ) ; }
Reads a file of the given expected size from the given input stream if it will fit into a byte array . This method handles the case where the file size changes between when the size is read and when the contents are read from the stream .
8,297
public static byte [ ] toByteArray ( File file ) throws IOException { FileInputStream in = null ; try { in = new FileInputStream ( file ) ; return readFile ( in , in . getChannel ( ) . size ( ) ) ; } finally { if ( in != null ) { in . close ( ) ; } } }
Reads all bytes from a file into a byte array .
8,298
private static Bitmap . Config getSuitableBitmapConfig ( Bitmap source ) { Bitmap . Config finalConfig = Bitmap . Config . ARGB_8888 ; final Bitmap . Config sourceConfig = source . getConfig ( ) ; if ( sourceConfig != null ) { switch ( sourceConfig ) { case RGB_565 : finalConfig = Bitmap . Config . RGB_565 ; break ; case ALPHA_8 : finalConfig = Bitmap . Config . ALPHA_8 ; break ; case ARGB_4444 : case ARGB_8888 : default : finalConfig = Bitmap . Config . ARGB_8888 ; break ; } } return finalConfig ; }
Returns suitable Bitmap Config for the new Bitmap based on the source Bitmap configurations .
8,299
private static void checkFinalImageBounds ( Bitmap source , int x , int y , int width , int height ) { Preconditions . checkArgument ( x + width <= source . getWidth ( ) , "x + width must be <= bitmap.width()" ) ; Preconditions . checkArgument ( y + height <= source . getHeight ( ) , "y + height must be <= bitmap.height()" ) ; }
Common code for checking that x + width and y + height are within image bounds