idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
8,100
protected static void buildGetMethod ( final Class < ? > originalClass , final String className , final Class < ? > superClass , final Method getterMethod , final ClassWriter cw ) { final Class < ? > fieldType = getterMethod . getReturnType ( ) ; Method overridingMethod ; try { overridingMethod = superClass . getMethod ( getOverridingGetMethodName ( fieldType ) , InternalWorkingMemory . class , Object . class ) ; } catch ( final Exception e ) { throw new RuntimeException ( "This is a bug. Please report back to JBoss Rules team." , e ) ; } final MethodVisitor mv = cw . visitMethod ( Opcodes . ACC_PUBLIC , overridingMethod . getName ( ) , Type . getMethodDescriptor ( overridingMethod ) , null , null ) ; mv . visitCode ( ) ; final Label l0 = new Label ( ) ; mv . visitLabel ( l0 ) ; mv . visitVarInsn ( Opcodes . ALOAD , 2 ) ; mv . visitTypeInsn ( Opcodes . CHECKCAST , Type . getInternalName ( originalClass ) ) ; if ( originalClass . isInterface ( ) ) { mv . visitMethodInsn ( Opcodes . INVOKEINTERFACE , Type . getInternalName ( originalClass ) , getterMethod . getName ( ) , Type . getMethodDescriptor ( getterMethod ) ) ; } else { mv . visitMethodInsn ( Opcodes . INVOKEVIRTUAL , Type . getInternalName ( originalClass ) , getterMethod . getName ( ) , Type . getMethodDescriptor ( getterMethod ) ) ; } mv . visitInsn ( Type . getType ( fieldType ) . getOpcode ( Opcodes . IRETURN ) ) ; final Label l1 = new Label ( ) ; mv . visitLabel ( l1 ) ; mv . visitLocalVariable ( "this" , "L" + className + ";" , null , l0 , l1 , 0 ) ; mv . visitLocalVariable ( "workingMemory" , Type . getDescriptor ( InternalWorkingMemory . class ) , null , l0 , l1 , 1 ) ; mv . visitLocalVariable ( "object" , Type . getDescriptor ( Object . class ) , null , l0 , l1 , 2 ) ; mv . visitMaxs ( 0 , 0 ) ; mv . visitEnd ( ) ; }
Creates the proxy reader method for the given method
8,101
public boolean supports ( final String line ) { final List < String > splits = new ArrayList < String > ( ) ; int depth = 0 ; int textDepth = 0 ; boolean escape = false ; StringBuffer split = new StringBuffer ( ) ; for ( char c : line . toCharArray ( ) ) { if ( depth == 0 && c == '.' ) { splits . add ( split . toString ( ) ) ; split = new StringBuffer ( ) ; depth = 0 ; textDepth = 0 ; escape = false ; continue ; } else if ( c == '\\' ) { escape = true ; split . append ( c ) ; continue ; } else if ( textDepth == 0 && c == '"' ) { textDepth ++ ; } else if ( ! escape && textDepth > 0 && c == '"' ) { textDepth -- ; } else if ( textDepth == 0 && c == '(' ) { depth ++ ; } else if ( textDepth == 0 && c == ')' ) { depth -- ; } split . append ( c ) ; escape = false ; } splits . add ( split . toString ( ) ) ; return splits . size ( ) == 2 ; }
ActionCallMethods do not support chained method invocations
8,102
public static RoundedBitmapDrawable fromBitmapDrawable ( Resources res , BitmapDrawable bitmapDrawable ) { return new RoundedBitmapDrawable ( res , bitmapDrawable . getBitmap ( ) , bitmapDrawable . getPaint ( ) ) ; }
Creates a new RoundedBitmapDrawable from the given BitmapDrawable .
8,103
public static void mkdirs ( File directory ) throws CreateDirectoryException { if ( directory . exists ( ) ) { if ( directory . isDirectory ( ) ) { return ; } if ( ! directory . delete ( ) ) { throw new CreateDirectoryException ( directory . getAbsolutePath ( ) , new FileDeleteException ( directory . getAbsolutePath ( ) ) ) ; } } if ( ! directory . mkdirs ( ) && ! directory . isDirectory ( ) ) { throw new CreateDirectoryException ( directory . getAbsolutePath ( ) ) ; } }
Creates the specified directory along with all parent paths if necessary
8,104
public static void rename ( File source , File target ) throws RenameException { Preconditions . checkNotNull ( source ) ; Preconditions . checkNotNull ( target ) ; target . delete ( ) ; if ( source . renameTo ( target ) ) { return ; } Throwable innerException = null ; if ( target . exists ( ) ) { innerException = new FileDeleteException ( target . getAbsolutePath ( ) ) ; } else if ( ! source . getParentFile ( ) . exists ( ) ) { innerException = new ParentDirNotFoundException ( source . getAbsolutePath ( ) ) ; } else if ( ! source . exists ( ) ) { innerException = new FileNotFoundException ( source . getAbsolutePath ( ) ) ; } throw new RenameException ( "Unknown error renaming " + source . getAbsolutePath ( ) + " to " + target . getAbsolutePath ( ) , innerException ) ; }
Renames the source file to the target file . If the target file exists then we attempt to delete it . If the delete or the rename operation fails then we raise an exception
8,105
private void init ( ) { mFadeDuration = DEFAULT_FADE_DURATION ; mDesiredAspectRatio = 0 ; mPlaceholderImage = null ; mPlaceholderImageScaleType = DEFAULT_SCALE_TYPE ; mRetryImage = null ; mRetryImageScaleType = DEFAULT_SCALE_TYPE ; mFailureImage = null ; mFailureImageScaleType = DEFAULT_SCALE_TYPE ; mProgressBarImage = null ; mProgressBarImageScaleType = DEFAULT_SCALE_TYPE ; mActualImageScaleType = DEFAULT_ACTUAL_IMAGE_SCALE_TYPE ; mActualImageMatrix = null ; mActualImageFocusPoint = null ; mActualImageColorFilter = null ; mBackground = null ; mOverlays = null ; mPressedStateOverlay = null ; mRoundingParams = null ; }
Initializes this builder to its defaults .
8,106
public static final int normalizeAlignment ( int alignment ) { switch ( alignment ) { case DynamicDrawableSpan . ALIGN_BOTTOM : return ALIGN_BOTTOM ; case ALIGN_CENTER : return ALIGN_CENTER ; case DynamicDrawableSpan . ALIGN_BASELINE : default : return ALIGN_BASELINE ; } }
A helper function to allow dropping in BetterImageSpan as a replacement to ImageSpan and allowing for center alignment if passed in .
8,107
public int getSize ( Paint paint , CharSequence text , int start , int end , Paint . FontMetricsInt fontMetrics ) { updateBounds ( ) ; if ( fontMetrics == null ) { return mWidth ; } int offsetAbove = getOffsetAboveBaseline ( fontMetrics ) ; int offsetBelow = mHeight + offsetAbove ; if ( offsetAbove < fontMetrics . ascent ) { fontMetrics . ascent = offsetAbove ; } if ( offsetAbove < fontMetrics . top ) { fontMetrics . top = offsetAbove ; } if ( offsetBelow > fontMetrics . descent ) { fontMetrics . descent = offsetBelow ; } if ( offsetBelow > fontMetrics . bottom ) { fontMetrics . bottom = offsetBelow ; } return mWidth ; }
Returns the width of the image span and increases the height if font metrics are available .
8,108
public Producer < CloseableReference < PooledByteBuffer > > getEncodedImageProducerSequence ( ImageRequest imageRequest ) { try { if ( FrescoSystrace . isTracing ( ) ) { FrescoSystrace . beginSection ( "ProducerSequenceFactory#getEncodedImageProducerSequence" ) ; } validateEncodedImageRequest ( imageRequest ) ; final Uri uri = imageRequest . getSourceUri ( ) ; switch ( imageRequest . getSourceUriType ( ) ) { case SOURCE_TYPE_NETWORK : return getNetworkFetchEncodedImageProducerSequence ( ) ; case SOURCE_TYPE_LOCAL_VIDEO_FILE : case SOURCE_TYPE_LOCAL_IMAGE_FILE : return getLocalFileFetchEncodedImageProducerSequence ( ) ; default : throw new IllegalArgumentException ( "Unsupported uri scheme for encoded image fetch! Uri is: " + getShortenedUriString ( uri ) ) ; } } finally { if ( FrescoSystrace . isTracing ( ) ) { FrescoSystrace . endSection ( ) ; } } }
Returns a sequence that can be used for a request for an encoded image from either network or local files .
8,109
public Producer < CloseableReference < PooledByteBuffer > > getNetworkFetchEncodedImageProducerSequence ( ) { synchronized ( this ) { if ( FrescoSystrace . isTracing ( ) ) { FrescoSystrace . beginSection ( "ProducerSequenceFactory#getNetworkFetchEncodedImageProducerSequence" ) ; } if ( mNetworkEncodedImageProducerSequence == null ) { if ( FrescoSystrace . isTracing ( ) ) { FrescoSystrace . beginSection ( "ProducerSequenceFactory#getNetworkFetchEncodedImageProducerSequence:init" ) ; } mNetworkEncodedImageProducerSequence = new RemoveImageTransformMetaDataProducer ( getBackgroundNetworkFetchToEncodedMemorySequence ( ) ) ; if ( FrescoSystrace . isTracing ( ) ) { FrescoSystrace . endSection ( ) ; } } if ( FrescoSystrace . isTracing ( ) ) { FrescoSystrace . endSection ( ) ; } } return mNetworkEncodedImageProducerSequence ; }
Returns a sequence that can be used for a request for an encoded image from network .
8,110
public Producer < CloseableReference < PooledByteBuffer > > getLocalFileFetchEncodedImageProducerSequence ( ) { synchronized ( this ) { if ( FrescoSystrace . isTracing ( ) ) { FrescoSystrace . beginSection ( "ProducerSequenceFactory#getLocalFileFetchEncodedImageProducerSequence" ) ; } if ( mLocalFileEncodedImageProducerSequence == null ) { if ( FrescoSystrace . isTracing ( ) ) { FrescoSystrace . beginSection ( "ProducerSequenceFactory#getLocalFileFetchEncodedImageProducerSequence:init" ) ; } mLocalFileEncodedImageProducerSequence = new RemoveImageTransformMetaDataProducer ( getBackgroundLocalFileFetchToEncodeMemorySequence ( ) ) ; if ( FrescoSystrace . isTracing ( ) ) { FrescoSystrace . endSection ( ) ; } } if ( FrescoSystrace . isTracing ( ) ) { FrescoSystrace . endSection ( ) ; } } return mLocalFileEncodedImageProducerSequence ; }
Returns a sequence that can be used for a request for an encoded image from a local file .
8,111
public Producer < Void > getEncodedImagePrefetchProducerSequence ( ImageRequest imageRequest ) { validateEncodedImageRequest ( imageRequest ) ; switch ( imageRequest . getSourceUriType ( ) ) { case SOURCE_TYPE_NETWORK : return getNetworkFetchToEncodedMemoryPrefetchSequence ( ) ; case SOURCE_TYPE_LOCAL_VIDEO_FILE : case SOURCE_TYPE_LOCAL_IMAGE_FILE : return getLocalFileFetchToEncodedMemoryPrefetchSequence ( ) ; default : final Uri uri = imageRequest . getSourceUri ( ) ; throw new IllegalArgumentException ( "Unsupported uri scheme for encoded image fetch! Uri is: " + getShortenedUriString ( uri ) ) ; } }
Returns a sequence that can be used for a prefetch request for an encoded image .
8,112
public Producer < CloseableReference < CloseableImage > > getDecodedImageProducerSequence ( ImageRequest imageRequest ) { if ( FrescoSystrace . isTracing ( ) ) { FrescoSystrace . beginSection ( "ProducerSequenceFactory#getDecodedImageProducerSequence" ) ; } Producer < CloseableReference < CloseableImage > > pipelineSequence = getBasicDecodedImageSequence ( imageRequest ) ; if ( imageRequest . getPostprocessor ( ) != null ) { pipelineSequence = getPostprocessorSequence ( pipelineSequence ) ; } if ( mUseBitmapPrepareToDraw ) { pipelineSequence = getBitmapPrepareSequence ( pipelineSequence ) ; } if ( FrescoSystrace . isTracing ( ) ) { FrescoSystrace . endSection ( ) ; } return pipelineSequence ; }
Returns a sequence that can be used for a request for a decoded image .
8,113
public Producer < Void > getDecodedImagePrefetchProducerSequence ( ImageRequest imageRequest ) { Producer < CloseableReference < CloseableImage > > inputProducer = getBasicDecodedImageSequence ( imageRequest ) ; if ( mUseBitmapPrepareToDraw ) { inputProducer = getBitmapPrepareSequence ( inputProducer ) ; } return getDecodedImagePrefetchSequence ( inputProducer ) ; }
Returns a sequence that can be used for a prefetch request for a decoded image .
8,114
private synchronized Producer < CloseableReference < CloseableImage > > getLocalVideoFileFetchSequence ( ) { if ( mLocalVideoFileFetchSequence == null ) { LocalVideoThumbnailProducer localVideoThumbnailProducer = mProducerFactory . newLocalVideoThumbnailProducer ( ) ; mLocalVideoFileFetchSequence = newBitmapCacheGetToBitmapCacheSequence ( localVideoThumbnailProducer ) ; } return mLocalVideoFileFetchSequence ; }
Bitmap cache get - > thread hand off - > multiplex - > bitmap cache - > local video thumbnail
8,115
private Producer < CloseableReference < CloseableImage > > newBitmapCacheGetToBitmapCacheSequence ( Producer < CloseableReference < CloseableImage > > inputProducer ) { BitmapMemoryCacheProducer bitmapMemoryCacheProducer = mProducerFactory . newBitmapMemoryCacheProducer ( inputProducer ) ; BitmapMemoryCacheKeyMultiplexProducer bitmapKeyMultiplexProducer = mProducerFactory . newBitmapMemoryCacheKeyMultiplexProducer ( bitmapMemoryCacheProducer ) ; ThreadHandoffProducer < CloseableReference < CloseableImage > > threadHandoffProducer = mProducerFactory . newBackgroundThreadHandoffProducer ( bitmapKeyMultiplexProducer , mThreadHandoffProducerQueue ) ; return mProducerFactory . newBitmapMemoryCacheGetProducer ( threadHandoffProducer ) ; }
Bitmap cache get - > thread hand off - > multiplex - > bitmap cache
8,116
private Producer < EncodedImage > newLocalTransformationsSequence ( Producer < EncodedImage > inputProducer , ThumbnailProducer < EncodedImage > [ ] thumbnailProducers ) { Producer < EncodedImage > localImageProducer = ProducerFactory . newAddImageTransformMetaDataProducer ( inputProducer ) ; localImageProducer = mProducerFactory . newResizeAndRotateProducer ( localImageProducer , true , mImageTranscoderFactory ) ; ThrottlingProducer < EncodedImage > localImageThrottlingProducer = mProducerFactory . newThrottlingProducer ( localImageProducer ) ; return mProducerFactory . newBranchOnSeparateImagesProducer ( newLocalThumbnailProducer ( thumbnailProducers ) , localImageThrottlingProducer ) ; }
Branch on separate images - > thumbnail resize and rotate - > thumbnail producers as provided - > local image resize and rotate - > add meta data producer
8,117
private synchronized Producer < CloseableReference < CloseableImage > > getPostprocessorSequence ( Producer < CloseableReference < CloseableImage > > inputProducer ) { if ( ! mPostprocessorSequences . containsKey ( inputProducer ) ) { PostprocessorProducer postprocessorProducer = mProducerFactory . newPostprocessorProducer ( inputProducer ) ; PostprocessedBitmapMemoryCacheProducer postprocessedBitmapMemoryCacheProducer = mProducerFactory . newPostprocessorBitmapMemoryCacheProducer ( postprocessorProducer ) ; mPostprocessorSequences . put ( inputProducer , postprocessedBitmapMemoryCacheProducer ) ; } return mPostprocessorSequences . get ( inputProducer ) ; }
post - processor producer - > copy producer - > inputProducer
8,118
private synchronized Producer < Void > getDecodedImagePrefetchSequence ( Producer < CloseableReference < CloseableImage > > inputProducer ) { if ( ! mCloseableImagePrefetchSequences . containsKey ( inputProducer ) ) { SwallowResultProducer < CloseableReference < CloseableImage > > swallowResultProducer = mProducerFactory . newSwallowResultProducer ( inputProducer ) ; mCloseableImagePrefetchSequences . put ( inputProducer , swallowResultProducer ) ; } return mCloseableImagePrefetchSequences . get ( inputProducer ) ; }
swallow result producer - > inputProducer
8,119
private synchronized Producer < CloseableReference < CloseableImage > > getBitmapPrepareSequence ( Producer < CloseableReference < CloseableImage > > inputProducer ) { Producer < CloseableReference < CloseableImage > > bitmapPrepareProducer = mBitmapPrepareSequences . get ( inputProducer ) ; if ( bitmapPrepareProducer == null ) { bitmapPrepareProducer = mProducerFactory . newBitmapPrepareProducer ( inputProducer ) ; mBitmapPrepareSequences . put ( inputProducer , bitmapPrepareProducer ) ; } return bitmapPrepareProducer ; }
bitmap prepare producer - > inputProducer
8,120
private static int readHeaderFromStream ( int maxHeaderLength , final InputStream is , final byte [ ] imageHeaderBytes ) throws IOException { Preconditions . checkNotNull ( is ) ; Preconditions . checkNotNull ( imageHeaderBytes ) ; Preconditions . checkArgument ( imageHeaderBytes . length >= maxHeaderLength ) ; if ( is . markSupported ( ) ) { try { is . mark ( maxHeaderLength ) ; return ByteStreams . read ( is , imageHeaderBytes , 0 , maxHeaderLength ) ; } finally { is . reset ( ) ; } } else { return ByteStreams . read ( is , imageHeaderBytes , 0 , maxHeaderLength ) ; } }
Reads up to maxHeaderLength bytes from is InputStream . If mark is supported by is it is used to restore content of the stream after appropriate amount of data is read . Read bytes are stored in imageHeaderBytes which should be capable of storing maxHeaderLength bytes .
8,121
public void reset ( ) { FLog . v ( TAG , "reset" ) ; mGestureDetector . reset ( ) ; mPreviousTransform . reset ( ) ; mActiveTransform . reset ( ) ; onTransformChanged ( ) ; }
Rests the controller .
8,122
public void setImageBounds ( RectF imageBounds ) { if ( ! imageBounds . equals ( mImageBounds ) ) { mImageBounds . set ( imageBounds ) ; onTransformChanged ( ) ; if ( mImageBoundsListener != null ) { mImageBoundsListener . onImageBoundsSet ( mImageBounds ) ; } } }
Sets the image bounds in view - absolute coordinates .
8,123
public void getImageRelativeToViewAbsoluteTransform ( Matrix outMatrix ) { outMatrix . setRectToRect ( IDENTITY_RECT , mTransformedImageBounds , Matrix . ScaleToFit . FILL ) ; }
Gets the matrix that transforms image - relative coordinates to view - absolute coordinates . The zoomable transformation is taken into account .
8,124
public PointF mapViewToImage ( PointF viewPoint ) { float [ ] points = mTempValues ; points [ 0 ] = viewPoint . x ; points [ 1 ] = viewPoint . y ; mActiveTransform . invert ( mActiveTransformInverse ) ; mActiveTransformInverse . mapPoints ( points , 0 , points , 0 , 1 ) ; mapAbsoluteToRelative ( points , points , 1 ) ; return new PointF ( points [ 0 ] , points [ 1 ] ) ; }
Maps point from view - absolute to image - relative coordinates . This takes into account the zoomable transformation .
8,125
public PointF mapImageToView ( PointF imagePoint ) { float [ ] points = mTempValues ; points [ 0 ] = imagePoint . x ; points [ 1 ] = imagePoint . y ; mapRelativeToAbsolute ( points , points , 1 ) ; mActiveTransform . mapPoints ( points , 0 , points , 0 , 1 ) ; return new PointF ( points [ 0 ] , points [ 1 ] ) ; }
Maps point from image - relative to view - absolute coordinates . This takes into account the zoomable transformation .
8,126
public void setTransform ( Matrix newTransform ) { FLog . v ( TAG , "setTransform" ) ; mActiveTransform . set ( newTransform ) ; onTransformChanged ( ) ; }
Sets a new zoom transformation .
8,127
public boolean onTouchEvent ( MotionEvent event ) { FLog . v ( TAG , "onTouchEvent: action: " , event . getAction ( ) ) ; if ( mIsEnabled && mIsGestureZoomEnabled ) { return mGestureDetector . onTouchEvent ( event ) ; } return false ; }
Notifies controller of the received touch event .
8,128
private float limit ( float value , float min , float max ) { return Math . min ( Math . max ( min , value ) , max ) ; }
Limits the value to the given min and max range .
8,129
private boolean canScrollInAllDirection ( ) { return mTransformedImageBounds . left < mViewBounds . left - EPS && mTransformedImageBounds . top < mViewBounds . top - EPS && mTransformedImageBounds . right > mViewBounds . right + EPS && mTransformedImageBounds . bottom > mViewBounds . bottom + EPS ; }
Returns whether the scroll can happen in all directions . I . e . the image is not on any edge .
8,130
public static GenericDraweeHierarchy createDraweeHierarchy ( final Context context , final Config config ) { FrescoSystrace . beginSection ( "DraweeUtil#createDraweeHierarchy" ) ; GenericDraweeHierarchyBuilder builder = new GenericDraweeHierarchyBuilder ( context . getResources ( ) ) . setFadeDuration ( config . fadeDurationMs ) . setPlaceholderImage ( Const . PLACEHOLDER ) . setFailureImage ( Const . FAILURE ) . setActualImageScaleType ( ScalingUtils . ScaleType . FIT_CENTER ) ; applyScaleType ( builder , config ) ; if ( config . useRoundedCorners || config . drawBorder ) { final Resources res = context . getResources ( ) ; final RoundingParams roundingParams = new RoundingParams ( ) ; if ( config . useRoundedCorners ) { roundingParams . setRoundingMethod ( RoundingParams . RoundingMethod . BITMAP_ONLY ) ; roundingParams . setCornersRadius ( res . getDimensionPixelSize ( R . dimen . drawee_corner_radius ) ) ; roundingParams . setRoundAsCircle ( config . useRoundedAsCircle ) ; } if ( config . drawBorder ) { roundingParams . setBorderColor ( res . getColor ( R . color . colorPrimary ) ) ; roundingParams . setBorderWidth ( res . getDimensionPixelSize ( R . dimen . drawee_border_width ) ) ; } builder . setRoundingParams ( roundingParams ) ; } GenericDraweeHierarchy result = builder . build ( ) ; FrescoSystrace . endSection ( ) ; return result ; }
Creates the Hierarchy using the information into the Config
8,131
public static void setBgColor ( View view , final Config config ) { int [ ] colors = view . getContext ( ) . getResources ( ) . getIntArray ( R . array . bg_colors ) ; final int bgColor = colors [ config . bgColor ] ; view . setBackgroundColor ( bgColor ) ; }
Utility method which set the bgColor based on configuration values
8,132
public synchronized void put ( final CacheKey key , final EncodedImage encodedImage ) { Preconditions . checkNotNull ( key ) ; Preconditions . checkArgument ( EncodedImage . isValid ( encodedImage ) ) ; final EncodedImage oldEntry = mMap . put ( key , EncodedImage . cloneOrNull ( encodedImage ) ) ; EncodedImage . closeSafely ( oldEntry ) ; logStats ( ) ; }
Stores key - value in this StagingArea . This call overrides previous value of stored reference if
8,133
public void clearAll ( ) { final List < EncodedImage > old ; synchronized ( this ) { old = new ArrayList < > ( mMap . values ( ) ) ; mMap . clear ( ) ; } for ( int i = 0 ; i < old . size ( ) ; i ++ ) { EncodedImage encodedImage = old . get ( i ) ; if ( encodedImage != null ) { encodedImage . close ( ) ; } } }
Removes all items from the StagingArea .
8,134
public boolean remove ( final CacheKey key ) { Preconditions . checkNotNull ( key ) ; final EncodedImage encodedImage ; synchronized ( this ) { encodedImage = mMap . remove ( key ) ; } if ( encodedImage == null ) { return false ; } try { return encodedImage . isValid ( ) ; } finally { encodedImage . close ( ) ; } }
Removes item from the StagingArea .
8,135
public synchronized boolean remove ( final CacheKey key , final EncodedImage encodedImage ) { Preconditions . checkNotNull ( key ) ; Preconditions . checkNotNull ( encodedImage ) ; Preconditions . checkArgument ( EncodedImage . isValid ( encodedImage ) ) ; final EncodedImage oldValue = mMap . get ( key ) ; if ( oldValue == null ) { return false ; } CloseableReference < PooledByteBuffer > oldRef = oldValue . getByteBufferRef ( ) ; CloseableReference < PooledByteBuffer > ref = encodedImage . getByteBufferRef ( ) ; try { if ( oldRef == null || ref == null || oldRef . get ( ) != ref . get ( ) ) { return false ; } mMap . remove ( key ) ; } finally { CloseableReference . closeSafely ( ref ) ; CloseableReference . closeSafely ( oldRef ) ; EncodedImage . closeSafely ( oldValue ) ; } logStats ( ) ; return true ; }
Removes key - value from the StagingArea . Both key and value must match .
8,136
public synchronized boolean containsKey ( CacheKey key ) { Preconditions . checkNotNull ( key ) ; if ( ! mMap . containsKey ( key ) ) { return false ; } EncodedImage storedEncodedImage = mMap . get ( key ) ; synchronized ( storedEncodedImage ) { if ( ! EncodedImage . isValid ( storedEncodedImage ) ) { mMap . remove ( key ) ; FLog . w ( TAG , "Found closed reference %d for key %s (%d)" , System . identityHashCode ( storedEncodedImage ) , key . getUriString ( ) , System . identityHashCode ( key ) ) ; return false ; } return true ; } }
Determine if an valid entry for the key exists in the staging area .
8,137
public ImageUrlsRequestBuilder addImageFormat ( ImageFormat imageFormat , ImageSize imageSize ) { mRequestedImageFormats . put ( imageFormat , imageSize ) ; return this ; }
Adds imageFormat to the set of image formats you want to download . imageSize specify server - side resize options .
8,138
protected EncodedImage getByteBufferBackedEncodedImage ( InputStream inputStream , int length ) throws IOException { CloseableReference < PooledByteBuffer > ref = null ; try { if ( length <= 0 ) { ref = CloseableReference . of ( mPooledByteBufferFactory . newByteBuffer ( inputStream ) ) ; } else { ref = CloseableReference . of ( mPooledByteBufferFactory . newByteBuffer ( inputStream , length ) ) ; } return new EncodedImage ( ref ) ; } finally { Closeables . closeQuietly ( inputStream ) ; CloseableReference . closeSafely ( ref ) ; } }
Creates a memory - backed encoded image from the stream . The stream is closed .
8,139
public synchronized void dispose ( ) { CloseableReference . closeSafely ( mPreviewBitmap ) ; mPreviewBitmap = null ; CloseableReference . closeSafely ( mDecodedFrames ) ; mDecodedFrames = null ; }
Disposes the result which releases the reference to any bitmaps .
8,140
public static < K , V > ImmutableMap < K , V > copyOf ( Map < ? extends K , ? extends V > map ) { return new ImmutableMap < > ( map ) ; }
Dummy method at the moment to help us enforce types .
8,141
private int getRotationAngle ( final ExifInterface exifInterface ) { return JfifUtil . getAutoRotateAngleFromOrientation ( Integer . parseInt ( exifInterface . getAttribute ( ExifInterface . TAG_ORIENTATION ) ) ) ; }
Gets the correction angle based on the image s orientation
8,142
public static int multiplyColorAlpha ( int color , int alpha ) { if ( alpha == 255 ) { return color ; } if ( alpha == 0 ) { return color & 0x00FFFFFF ; } alpha = alpha + ( alpha >> 7 ) ; int colorAlpha = color >>> 24 ; int multipliedAlpha = colorAlpha * alpha >> 8 ; return ( multipliedAlpha << 24 ) | ( color & 0x00FFFFFF ) ; }
Multiplies the color with the given alpha .
8,143
public static int getOpacityFromColor ( int color ) { int colorAlpha = color >>> 24 ; if ( colorAlpha == 255 ) { return PixelFormat . OPAQUE ; } else if ( colorAlpha == 0 ) { return PixelFormat . TRANSPARENT ; } else { return PixelFormat . TRANSLUCENT ; } }
Gets the opacity from a color . Inspired by Android ColorDrawable .
8,144
public static PlatformDecoder buildPlatformDecoder ( PoolFactory poolFactory , boolean gingerbreadDecoderEnabled ) { if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . O ) { int maxNumThreads = poolFactory . getFlexByteArrayPoolMaxNumThreads ( ) ; return new OreoDecoder ( poolFactory . getBitmapPool ( ) , maxNumThreads , new Pools . SynchronizedPool < > ( maxNumThreads ) ) ; } else if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . LOLLIPOP ) { int maxNumThreads = poolFactory . getFlexByteArrayPoolMaxNumThreads ( ) ; return new ArtDecoder ( poolFactory . getBitmapPool ( ) , maxNumThreads , new Pools . SynchronizedPool < > ( maxNumThreads ) ) ; } else { if ( gingerbreadDecoderEnabled && Build . VERSION . SDK_INT < Build . VERSION_CODES . KITKAT ) { return new GingerbreadPurgeableDecoder ( ) ; } else { return new KitKatPurgeableDecoder ( poolFactory . getFlexByteArrayPool ( ) ) ; } } }
Provide the implementation of the PlatformDecoder for the current platform using the provided PoolFactory
8,145
private void showFragment ( ShowcaseFragment fragment ) { final FragmentTransaction fragmentTransaction = getSupportFragmentManager ( ) . beginTransaction ( ) . replace ( R . id . content_main , ( Fragment ) fragment ) ; if ( fragment . getBackstackTag ( ) != null ) { fragmentTransaction . addToBackStack ( fragment . getBackstackTag ( ) ) ; } fragmentTransaction . commit ( ) ; setTitle ( fragment . getTitleId ( ) ) ; }
Utility method to display a specific Fragment . If the tag is not null we add a backstack
8,146
public void transcodeWebpToJpeg ( InputStream inputStream , OutputStream outputStream , int quality ) throws IOException { StaticWebpNativeLoader . ensure ( ) ; nativeTranscodeWebpToJpeg ( Preconditions . checkNotNull ( inputStream ) , Preconditions . checkNotNull ( outputStream ) , quality ) ; }
Transcodes webp image given by input stream into jpeg .
8,147
public void transcodeWebpToPng ( InputStream inputStream , OutputStream outputStream ) throws IOException { StaticWebpNativeLoader . ensure ( ) ; nativeTranscodeWebpToPng ( Preconditions . checkNotNull ( inputStream ) , Preconditions . checkNotNull ( outputStream ) ) ; }
Transcodes Webp image given by input stream into png .
8,148
public void execute ( Runnable runnable ) { if ( runnable == null ) { throw new NullPointerException ( "runnable parameter is null" ) ; } if ( ! mWorkQueue . offer ( runnable ) ) { throw new RejectedExecutionException ( mName + " queue is full, size=" + mWorkQueue . size ( ) ) ; } final int queueSize = mWorkQueue . size ( ) ; final int maxSize = mMaxQueueSize . get ( ) ; if ( ( queueSize > maxSize ) && mMaxQueueSize . compareAndSet ( maxSize , queueSize ) ) { FLog . v ( TAG , "%s: max pending work in queue = %d" , mName , queueSize ) ; } startWorkerIfNeeded ( ) ; }
Submit a task to be executed in the future .
8,149
public static boolean isImageBigEnough ( int width , int height , ResizeOptions resizeOptions ) { if ( resizeOptions == null ) { return getAcceptableSize ( width ) >= BitmapUtil . MAX_BITMAP_SIZE && getAcceptableSize ( height ) >= ( int ) BitmapUtil . MAX_BITMAP_SIZE ; } else { return getAcceptableSize ( width ) >= resizeOptions . width && getAcceptableSize ( height ) >= resizeOptions . height ; } }
Checks whether the producer may be able to produce images of the specified size . This makes no promise about being able to produce images for a particular source only generally being able to produce output of the desired resolution .
8,150
private void init ( ) { mCallerContext = null ; mImageRequest = null ; mLowResImageRequest = null ; mMultiImageRequests = null ; mTryCacheOnlyFirst = true ; mControllerListener = null ; mControllerViewportVisibilityListener = null ; mTapToRetryEnabled = false ; mAutoPlayAnimations = false ; mOldController = null ; mContentDescription = null ; }
Initializes this builder .
8,151
public AbstractDraweeController build ( ) { validate ( ) ; if ( mImageRequest == null && mMultiImageRequests == null && mLowResImageRequest != null ) { mImageRequest = mLowResImageRequest ; mLowResImageRequest = null ; } return buildController ( ) ; }
Builds the specified controller .
8,152
protected void validate ( ) { Preconditions . checkState ( ( mMultiImageRequests == null ) || ( mImageRequest == null ) , "Cannot specify both ImageRequest and FirstAvailableImageRequests!" ) ; Preconditions . checkState ( ( mDataSourceSupplier == null ) || ( mMultiImageRequests == null && mImageRequest == null && mLowResImageRequest == null ) , "Cannot specify DataSourceSupplier with other ImageRequests! Use one or the other." ) ; }
Validates the parameters before building a controller .
8,153
protected AbstractDraweeController buildController ( ) { if ( FrescoSystrace . isTracing ( ) ) { FrescoSystrace . beginSection ( "AbstractDraweeControllerBuilder#buildController" ) ; } AbstractDraweeController controller = obtainController ( ) ; controller . setRetainImageOnFailure ( getRetainImageOnFailure ( ) ) ; controller . setContentDescription ( getContentDescription ( ) ) ; controller . setControllerViewportVisibilityListener ( getControllerViewportVisibilityListener ( ) ) ; maybeBuildAndSetRetryManager ( controller ) ; maybeAttachListeners ( controller ) ; if ( FrescoSystrace . isTracing ( ) ) { FrescoSystrace . endSection ( ) ; } return controller ; }
Builds a regular controller .
8,154
protected Supplier < DataSource < IMAGE > > obtainDataSourceSupplier ( final DraweeController controller , final String controllerId ) { if ( mDataSourceSupplier != null ) { return mDataSourceSupplier ; } Supplier < DataSource < IMAGE > > supplier = null ; if ( mImageRequest != null ) { supplier = getDataSourceSupplierForRequest ( controller , controllerId , mImageRequest ) ; } else if ( mMultiImageRequests != null ) { supplier = getFirstAvailableDataSourceSupplier ( controller , controllerId , mMultiImageRequests , mTryCacheOnlyFirst ) ; } if ( supplier != null && mLowResImageRequest != null ) { List < Supplier < DataSource < IMAGE > > > suppliers = new ArrayList < > ( 2 ) ; suppliers . add ( supplier ) ; suppliers . add ( getDataSourceSupplierForRequest ( controller , controllerId , mLowResImageRequest ) ) ; supplier = IncreasingQualityDataSourceSupplier . create ( suppliers , false ) ; } if ( supplier == null ) { supplier = DataSources . getFailedDataSourceSupplier ( NO_REQUEST_EXCEPTION ) ; } return supplier ; }
Gets the top - level data source supplier to be used by a controller .
8,155
protected void maybeBuildAndSetGestureDetector ( AbstractDraweeController controller ) { GestureDetector gestureDetector = controller . getGestureDetector ( ) ; if ( gestureDetector == null ) { gestureDetector = GestureDetector . newInstance ( mContext ) ; controller . setGestureDetector ( gestureDetector ) ; } }
Installs a gesture detector to the given controller .
8,156
public static boolean isLocalContactUri ( Uri uri ) { return isLocalContentUri ( uri ) && ContactsContract . AUTHORITY . equals ( uri . getAuthority ( ) ) && ! uri . getPath ( ) . startsWith ( LOCAL_CONTACT_IMAGE_URI . getPath ( ) ) ; }
Checks if the given URI is a general Contact URI and not a specific display photo .
8,157
public static boolean isLocalCameraUri ( Uri uri ) { String uriString = uri . toString ( ) ; return uriString . startsWith ( MediaStore . Images . Media . EXTERNAL_CONTENT_URI . toString ( ) ) || uriString . startsWith ( MediaStore . Images . Media . INTERNAL_CONTENT_URI . toString ( ) ) ; }
Checks if the given URI is for a photo from the device s local media store .
8,158
public static String getRealPathFromUri ( ContentResolver contentResolver , final Uri srcUri ) { String result = null ; if ( isLocalContentUri ( srcUri ) ) { Cursor cursor = null ; try { cursor = contentResolver . query ( srcUri , null , null , null , null ) ; if ( cursor != null && cursor . moveToFirst ( ) ) { int idx = cursor . getColumnIndex ( MediaStore . Images . ImageColumns . DATA ) ; if ( idx != - 1 ) { result = cursor . getString ( idx ) ; } } } finally { if ( cursor != null ) { cursor . close ( ) ; } } } else if ( isLocalFileUri ( srcUri ) ) { result = srcUri . getPath ( ) ; } return result ; }
Get the path of a file from the Uri .
8,159
public static Uri getUriForQualifiedResource ( String packageName , int resourceId ) { return new Uri . Builder ( ) . scheme ( QUALIFIED_RESOURCE_SCHEME ) . authority ( packageName ) . path ( String . valueOf ( resourceId ) ) . build ( ) ; }
Returns a URI for the given resource ID in the given package . Use this method only if you need to specify a package name different to your application s main package .
8,160
public static void transcodeJpeg ( final InputStream inputStream , final OutputStream outputStream , final int rotationAngle , final int scaleNumerator , final int quality ) throws IOException { NativeJpegTranscoderSoLoader . ensure ( ) ; Preconditions . checkArgument ( scaleNumerator >= MIN_SCALE_NUMERATOR ) ; Preconditions . checkArgument ( scaleNumerator <= MAX_SCALE_NUMERATOR ) ; Preconditions . checkArgument ( quality >= MIN_QUALITY ) ; Preconditions . checkArgument ( quality <= MAX_QUALITY ) ; Preconditions . checkArgument ( JpegTranscoderUtils . isRotationAngleAllowed ( rotationAngle ) ) ; Preconditions . checkArgument ( scaleNumerator != SCALE_DENOMINATOR || rotationAngle != 0 , "no transformation requested" ) ; nativeTranscodeJpeg ( Preconditions . checkNotNull ( inputStream ) , Preconditions . checkNotNull ( outputStream ) , rotationAngle , scaleNumerator , quality ) ; }
Transcodes an image to match the specified rotation angle and the scale factor .
8,161
public static void transcodeJpegWithExifOrientation ( final InputStream inputStream , final OutputStream outputStream , final int exifOrientation , final int scaleNumerator , final int quality ) throws IOException { NativeJpegTranscoderSoLoader . ensure ( ) ; Preconditions . checkArgument ( scaleNumerator >= MIN_SCALE_NUMERATOR ) ; Preconditions . checkArgument ( scaleNumerator <= MAX_SCALE_NUMERATOR ) ; Preconditions . checkArgument ( quality >= MIN_QUALITY ) ; Preconditions . checkArgument ( quality <= MAX_QUALITY ) ; Preconditions . checkArgument ( JpegTranscoderUtils . isExifOrientationAllowed ( exifOrientation ) ) ; Preconditions . checkArgument ( scaleNumerator != SCALE_DENOMINATOR || exifOrientation != ExifInterface . ORIENTATION_NORMAL , "no transformation requested" ) ; nativeTranscodeJpegWithExifOrientation ( Preconditions . checkNotNull ( inputStream ) , Preconditions . checkNotNull ( outputStream ) , exifOrientation , scaleNumerator , quality ) ; }
Transcodes an image to match the specified exif orientation and the scale factor .
8,162
private static int getSourceUriType ( final Uri uri ) { if ( uri == null ) { return SOURCE_TYPE_UNKNOWN ; } if ( UriUtil . isNetworkUri ( uri ) ) { return SOURCE_TYPE_NETWORK ; } else if ( UriUtil . isLocalFileUri ( uri ) ) { if ( MediaUtils . isVideo ( MediaUtils . extractMime ( uri . getPath ( ) ) ) ) { return SOURCE_TYPE_LOCAL_VIDEO_FILE ; } else { return SOURCE_TYPE_LOCAL_IMAGE_FILE ; } } else if ( UriUtil . isLocalContentUri ( uri ) ) { return SOURCE_TYPE_LOCAL_CONTENT ; } else if ( UriUtil . isLocalAssetUri ( uri ) ) { return SOURCE_TYPE_LOCAL_ASSET ; } else if ( UriUtil . isLocalResourceUri ( uri ) ) { return SOURCE_TYPE_LOCAL_RESOURCE ; } else if ( UriUtil . isDataUri ( uri ) ) { return SOURCE_TYPE_DATA ; } else if ( UriUtil . isQualifiedResourceUri ( uri ) ) { return SOURCE_TYPE_QUALIFIED_RESOURCE ; } else { return SOURCE_TYPE_UNKNOWN ; } }
This is a utility method which returns the type of Uri
8,163
public synchronized K getFirstKey ( ) { return mMap . isEmpty ( ) ? null : mMap . keySet ( ) . iterator ( ) . next ( ) ; }
Gets the key of the first element in the map .
8,164
public synchronized V put ( K key , V value ) { V oldValue = mMap . remove ( key ) ; mSizeInBytes -= getValueSizeInBytes ( oldValue ) ; mMap . put ( key , value ) ; mSizeInBytes += getValueSizeInBytes ( value ) ; return oldValue ; }
Adds the element to the map and removes the old element with the same key if any .
8,165
public synchronized V remove ( K key ) { V oldValue = mMap . remove ( key ) ; mSizeInBytes -= getValueSizeInBytes ( oldValue ) ; return oldValue ; }
Removes the element from the map .
8,166
public synchronized ArrayList < V > clear ( ) { ArrayList < V > oldValues = new ArrayList < > ( mMap . values ( ) ) ; mMap . clear ( ) ; mSizeInBytes = 0 ; return oldValues ; }
Clears the map .
8,167
private String getSubdirectoryPath ( String resourceId ) { String subdirectory = String . valueOf ( Math . abs ( resourceId . hashCode ( ) % SHARDING_BUCKET_COUNT ) ) ; return mVersionDirectory + File . separator + subdirectory ; }
Gets the directory to use to store the given key
8,168
public void jumpToFrame ( int targetFrameNumber ) { if ( mAnimationBackend == null || mFrameScheduler == null ) { return ; } mLastFrameAnimationTimeMs = mFrameScheduler . getTargetRenderTimeMs ( targetFrameNumber ) ; mStartTimeMs = now ( ) - mLastFrameAnimationTimeMs ; mExpectedRenderTimeMs = mStartTimeMs ; invalidateSelf ( ) ; }
Jump immediately to the given frame number . The animation will not be paused if it is running . If the animation is not running the animation will not be started .
8,169
public long getLoopDurationMs ( ) { if ( mAnimationBackend == null ) { return 0 ; } if ( mFrameScheduler != null ) { return mFrameScheduler . getLoopDurationMs ( ) ; } int loopDurationMs = 0 ; for ( int i = 0 ; i < mAnimationBackend . getFrameCount ( ) ; i ++ ) { loopDurationMs += mAnimationBackend . getFrameDurationMs ( i ) ; } return loopDurationMs ; }
Get the animation duration for 1 loop by summing all frame durations .
8,170
protected boolean onLevelChange ( int level ) { if ( mIsRunning ) { return false ; } if ( mLastFrameAnimationTimeMs != level ) { mLastFrameAnimationTimeMs = level ; invalidateSelf ( ) ; return true ; } return false ; }
Set the animation to the given level . The level represents the animation time in ms . If the animation time is greater than the last frame time for the last loop the last frame will be displayed .
8,171
public static String encodeHex ( byte [ ] array , boolean zeroTerminated ) { char [ ] cArray = new char [ array . length * 2 ] ; int j = 0 ; for ( int i = 0 ; i < array . length ; i ++ ) { int index = array [ i ] & 0xFF ; if ( index == 0 && zeroTerminated ) { break ; } cArray [ j ++ ] = FIRST_CHAR [ index ] ; cArray [ j ++ ] = SECOND_CHAR [ index ] ; } return new String ( cArray , 0 , j ) ; }
Quickly converts a byte array to a hexadecimal string representation .
8,172
public static byte [ ] decodeHex ( String hexString ) { int length = hexString . length ( ) ; if ( ( length & 0x01 ) != 0 ) { throw new IllegalArgumentException ( "Odd number of characters." ) ; } boolean badHex = false ; byte [ ] out = new byte [ length >> 1 ] ; for ( int i = 0 , j = 0 ; j < length ; i ++ ) { int c1 = hexString . charAt ( j ++ ) ; if ( c1 > 'f' ) { badHex = true ; break ; } final byte d1 = DIGITS [ c1 ] ; if ( d1 == - 1 ) { badHex = true ; break ; } int c2 = hexString . charAt ( j ++ ) ; if ( c2 > 'f' ) { badHex = true ; break ; } final byte d2 = DIGITS [ c2 ] ; if ( d2 == - 1 ) { badHex = true ; break ; } out [ i ] = ( byte ) ( d1 << 4 | d2 ) ; } if ( badHex ) { throw new IllegalArgumentException ( "Invalid hexadecimal digit: " + hexString ) ; } return out ; }
Quickly converts a hexadecimal string to a byte array .
8,173
private void handleException ( final Call call , final Exception e , final Callback callback ) { if ( call . isCanceled ( ) ) { callback . onCancellation ( ) ; } else { callback . onFailure ( e ) ; } }
Handles exceptions .
8,174
protected void initialize ( String id , Object callerContext ) { init ( id , callerContext ) ; mJustConstructed = false ; }
Initializes this controller with the new id and caller context . This allows for reusing of the existing controller instead of instantiating a new one . This method should be called when the controller is in detached state .
8,175
public void addControllerListener ( ControllerListener < ? super INFO > controllerListener ) { Preconditions . checkNotNull ( controllerListener ) ; if ( mControllerListener instanceof InternalForwardingListener ) { ( ( InternalForwardingListener < INFO > ) mControllerListener ) . addListener ( controllerListener ) ; return ; } if ( mControllerListener != null ) { mControllerListener = InternalForwardingListener . createInternal ( mControllerListener , controllerListener ) ; return ; } mControllerListener = ( ControllerListener < INFO > ) controllerListener ; }
Adds controller listener .
8,176
public void removeControllerListener ( ControllerListener < ? super INFO > controllerListener ) { Preconditions . checkNotNull ( controllerListener ) ; if ( mControllerListener instanceof InternalForwardingListener ) { ( ( InternalForwardingListener < INFO > ) mControllerListener ) . removeListener ( controllerListener ) ; return ; } if ( mControllerListener == controllerListener ) { mControllerListener = null ; } }
Removes controller listener .
8,177
public Drawable getDrawable ( int index ) { Preconditions . checkArgument ( index >= 0 ) ; Preconditions . checkArgument ( index < mLayers . length ) ; return mLayers [ index ] ; }
Gets the drawable at the specified index .
8,178
private EncodedImage getThumbnail ( ResizeOptions resizeOptions , int imageId ) throws IOException { int thumbnailKind = getThumbnailKind ( resizeOptions ) ; if ( thumbnailKind == NO_THUMBNAIL ) { return null ; } Cursor thumbnailCursor = null ; try { thumbnailCursor = MediaStore . Images . Thumbnails . queryMiniThumbnail ( mContentResolver , imageId , thumbnailKind , THUMBNAIL_PROJECTION ) ; if ( thumbnailCursor == null ) { return null ; } thumbnailCursor . moveToFirst ( ) ; if ( thumbnailCursor . getCount ( ) > 0 ) { final String thumbnailUri = thumbnailCursor . getString ( thumbnailCursor . getColumnIndex ( MediaStore . Images . Thumbnails . DATA ) ) ; if ( new File ( thumbnailUri ) . exists ( ) ) { return getEncodedImage ( new FileInputStream ( thumbnailUri ) , getLength ( thumbnailUri ) ) ; } } } finally { if ( thumbnailCursor != null ) { thumbnailCursor . close ( ) ; } } return null ; }
stored thumbnails .
8,179
private static int getThumbnailKind ( ResizeOptions resizeOptions ) { if ( ThumbnailSizeChecker . isImageBigEnough ( MICRO_THUMBNAIL_DIMENSIONS . width ( ) , MICRO_THUMBNAIL_DIMENSIONS . height ( ) , resizeOptions ) ) { return MediaStore . Images . Thumbnails . MICRO_KIND ; } else if ( ThumbnailSizeChecker . isImageBigEnough ( MINI_THUMBNAIL_DIMENSIONS . width ( ) , MINI_THUMBNAIL_DIMENSIONS . height ( ) , resizeOptions ) ) { return MediaStore . Images . Thumbnails . MINI_KIND ; } else { return NO_THUMBNAIL ; } }
when scaling it to fit a view will not be significant .
8,180
public static ContentProviderSimpleAdapter getInternalPhotoSimpleAdapter ( Context context ) { return new ContentProviderSimpleAdapter ( MediaStore . Images . Media . INTERNAL_CONTENT_URI , context ) ; }
Creates and returns a SimpleAdapter for Internal Photos
8,181
public static ContentProviderSimpleAdapter getExternalPhotoSimpleAdapter ( Context context ) { return new ContentProviderSimpleAdapter ( MediaStore . Images . Media . EXTERNAL_CONTENT_URI , context ) ; }
Creates and returns a SimpleAdapter for External Photos
8,182
public int getDisplayHeight ( ) { Display display = getWindowManager ( ) . getDefaultDisplay ( ) ; if ( Build . VERSION . SDK_INT < Build . VERSION_CODES . HONEYCOMB_MR2 ) { return display . getHeight ( ) ; } else { final Point size = new Point ( ) ; display . getSize ( size ) ; return size . y ; } }
Determines display s height .
8,183
public static byte [ ] asciiBytes ( String value ) { Preconditions . checkNotNull ( value ) ; try { return value . getBytes ( "ASCII" ) ; } catch ( UnsupportedEncodingException uee ) { throw new RuntimeException ( "ASCII not found!" , uee ) ; } }
Helper method that transforms provided string into it s byte representation using ASCII encoding .
8,184
public static boolean startsWithPattern ( final byte [ ] byteArray , final byte [ ] pattern ) { Preconditions . checkNotNull ( byteArray ) ; Preconditions . checkNotNull ( pattern ) ; if ( pattern . length > byteArray . length ) { return false ; } for ( int i = 0 ; i < pattern . length ; ++ i ) { if ( byteArray [ i ] != pattern [ i ] ) { return false ; } } return true ; }
Checks if byteArray interpreted as sequence of bytes starts with pattern starting at position equal to offset .
8,185
public static int indexOfPattern ( final byte [ ] byteArray , final int byteArrayLen , final byte [ ] pattern , final int patternLen ) { Preconditions . checkNotNull ( byteArray ) ; Preconditions . checkNotNull ( pattern ) ; if ( patternLen > byteArrayLen ) { return - 1 ; } byte first = pattern [ 0 ] ; int max = byteArrayLen - patternLen ; for ( int i = 0 ; i <= max ; i ++ ) { if ( byteArray [ i ] != first ) { while ( ++ i <= max && byteArray [ i ] != first ) { } } if ( i <= max ) { int j = i + 1 ; int end = j + patternLen - 1 ; for ( int k = 1 ; j < end && byteArray [ j ] == pattern [ k ] ; j ++ , k ++ ) { } if ( j == end ) { return i ; } } } return - 1 ; }
Checks if byteArray interpreted as sequence of bytes contains the pattern .
8,186
public void onDraw ( final Canvas canvas ) { mPaint . setColor ( 0xC0000000 ) ; mTextRect . set ( 0 , 0 , mView . getWidth ( ) , 35 ) ; canvas . drawRect ( mTextRect , mPaint ) ; mPaint . setColor ( Color . WHITE ) ; canvas . drawText ( "[" + mTag + "]" , 10 , 15 , mPaint ) ; String message = "Not started" ; switch ( mState ) { case STARTED : message = "Loading..." ; break ; case SUCCESS : message = "Loaded after " + ( mFinishTime - mStartTime ) + "ms" ; break ; case FAILURE : message = "Failed after " + ( mFinishTime - mStartTime ) + "ms" ; break ; case CANCELLATION : message = "Cancelled after " + ( mFinishTime - mStartTime ) + "ms" ; break ; } canvas . drawText ( message , 10 , 30 , mPaint ) ; }
Draws overlay with request state for easier visual inspection .
8,187
private static Pair < Integer , Integer > getVP8Dimension ( final InputStream is ) throws IOException { is . skip ( 7 ) ; final short sign1 = getShort ( is ) ; final short sign2 = getShort ( is ) ; final short sign3 = getShort ( is ) ; if ( sign1 != 0x9D || sign2 != 0x01 || sign3 != 0x2A ) { return null ; } return new Pair < > ( get2BytesAsInt ( is ) , get2BytesAsInt ( is ) ) ; }
We manage the Simple WebP case
8,188
private static Pair < Integer , Integer > getVP8LDimension ( final InputStream is ) throws IOException { getInt ( is ) ; final byte check = getByte ( is ) ; if ( check != 0x2F ) { return null ; } int data1 = ( ( byte ) is . read ( ) ) & 0xFF ; int data2 = ( ( byte ) is . read ( ) ) & 0xFF ; int data3 = ( ( byte ) is . read ( ) ) & 0xFF ; int data4 = ( ( byte ) is . read ( ) ) & 0xFF ; final int width = ( ( data2 & 0x3F ) << 8 | data1 ) + 1 ; final int height = ( ( data4 & 0x0F ) << 10 | data3 << 2 | ( data2 & 0xC0 ) >> 6 ) + 1 ; return new Pair < > ( width , height ) ; }
We manage the Lossless WebP case
8,189
private static Pair < Integer , Integer > getVP8XDimension ( final InputStream is ) throws IOException { is . skip ( 8 ) ; return new Pair < > ( read3Bytes ( is ) + 1 , read3Bytes ( is ) + 1 ) ; }
We manage the Extended WebP case
8,190
private static boolean compare ( byte [ ] what , String with ) { if ( what . length != with . length ( ) ) { return false ; } for ( int i = 0 ; i < what . length ; i ++ ) { if ( with . charAt ( i ) != what [ i ] ) { return false ; } } return true ; }
Compares some bytes with the text we re expecting
8,191
protected Bitmap alloc ( int size ) { return Bitmap . createBitmap ( 1 , ( int ) Math . ceil ( size / ( double ) BitmapUtil . RGB_565_BYTES_PER_PIXEL ) , Bitmap . Config . RGB_565 ) ; }
Allocate a bitmap that has a backing memory allocation of size bytes . This is configuration agnostic so the size is the actual size in bytes of the bitmap .
8,192
public void setRadius ( float radius ) { Preconditions . checkState ( radius >= 0 ) ; Arrays . fill ( mCornerRadii , radius ) ; mRadiiNonZero = ( radius != 0 ) ; mIsPathDirty = true ; invalidateSelf ( ) ; }
Specify radius for the corners of the rectangle . If this is > 0 then the drawable is drawn in a round - rectangle rather than a rectangle .
8,193
public void setPadding ( float padding ) { if ( mPadding != padding ) { mPadding = padding ; mIsPathDirty = true ; invalidateSelf ( ) ; } }
Sets the padding for the bitmap .
8,194
public void setScaleDownInsideBorders ( boolean scaleDownInsideBorders ) { if ( mScaleDownInsideBorders != scaleDownInsideBorders ) { mScaleDownInsideBorders = scaleDownInsideBorders ; mIsPathDirty = true ; invalidateSelf ( ) ; } }
Sets whether image should be scaled down inside borders .
8,195
private CloseableReference < Bitmap > createRainbowBitmap ( ) { final int w = 256 ; final int h = 256 ; mOriginalBitmap = mPlatformBitmapFactory . createBitmap ( w , h , Bitmap . Config . ARGB_8888 ) ; final int [ ] colors = new int [ w * h ] ; for ( int i = 0 ; i < w ; i ++ ) { for ( int j = 0 ; j < h ; j ++ ) { final float hue = 360f * j / ( float ) w ; final float saturation = 2f * ( h - i ) / ( float ) h ; final float value = 1 ; colors [ i * h + j ] = Color . HSVToColor ( 255 , new float [ ] { hue , saturation , value } ) ; } } mOriginalBitmap . get ( ) . setPixels ( colors , 0 , w , 0 , 0 , w , h ) ; return mOriginalBitmap ; }
Creates a new bitmap with a HSV map at value = 1
8,196
public static AnimationBackend wrapAnimationBackendWithInactivityCheck ( final Context context , final AnimationBackend animationBackend ) { AnimationBackendDelegateWithInactivityCheck . InactivityListener inactivityListener = new AnimationBackendDelegateWithInactivityCheck . InactivityListener ( ) { public void onInactive ( ) { 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 ( ) ) ; }
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 .
8,197
private static String readAsString ( InputStream stream ) throws IOException { StringWriter writer = new StringWriter ( ) ; Reader reader = new BufferedReader ( new InputStreamReader ( stream , "UTF-8" ) ) ; while ( true ) { int c = reader . read ( ) ; if ( c < 0 ) { break ; } writer . write ( c ) ; } return writer . toString ( ) ; }
Reads an InputStream and converts it to a String .
8,198
public CloseableReference < byte [ ] > get ( int size ) { Preconditions . checkArgument ( size > 0 , "Size must be greater than zero" ) ; Preconditions . checkArgument ( size <= mMaxByteArraySize , "Requested size is too big" ) ; mSemaphore . acquireUninterruptibly ( ) ; try { byte [ ] byteArray = getByteArray ( size ) ; return CloseableReference . of ( byteArray , mResourceReleaser ) ; } catch ( Throwable t ) { mSemaphore . release ( ) ; throw Throwables . propagate ( t ) ; } }
Get exclusive access to the byte array of size greater or equal to the passed one .
8,199
public void trim ( MemoryTrimType trimType ) { if ( ! mSemaphore . tryAcquire ( ) ) { return ; } try { mByteArraySoftRef . clear ( ) ; } finally { mSemaphore . release ( ) ; } }
Responds to memory pressure by simply discarding the local byte array if it is not used at the moment .