idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
8,300
private static void setPropertyFromSourceBitmap ( Bitmap source , Bitmap destination ) { destination . setDensity ( source . getDensity ( ) ) ; if ( Build . VERSION . SDK_INT >= 12 ) { destination . setHasAlpha ( source . hasAlpha ( ) ) ; } if ( Build . VERSION . SDK_INT >= 19 ) { destination . setPremultiplied ( source . isPremultiplied ( ) ) ; } }
Set some property of the source bitmap to the destination bitmap
8,301
public static Pair < Integer , Integer > decodeDimensions ( Uri uri ) { Preconditions . checkNotNull ( uri ) ; BitmapFactory . Options options = new BitmapFactory . Options ( ) ; options . inJustDecodeBounds = true ; BitmapFactory . decodeFile ( uri . getPath ( ) , options ) ; return ( options . outWidth == - 1 || options . outHeight == - 1 ) ? null : new Pair < > ( options . outWidth , options . outHeight ) ; }
Decodes the bounds of an image from its Uri and returns a pair of the dimensions
8,302
public static Pair < Integer , Integer > decodeDimensions ( InputStream is ) { Preconditions . checkNotNull ( is ) ; ByteBuffer byteBuffer = DECODE_BUFFERS . acquire ( ) ; if ( byteBuffer == null ) { byteBuffer = ByteBuffer . allocate ( DECODE_BUFFER_SIZE ) ; } BitmapFactory . Options options = new BitmapFactory . Options ( ) ; options . inJustDecodeBounds = true ; try { options . inTempStorage = byteBuffer . array ( ) ; BitmapFactory . decodeStream ( is , null , options ) ; return ( options . outWidth == - 1 || options . outHeight == - 1 ) ? null : new Pair < > ( options . outWidth , options . outHeight ) ; } finally { DECODE_BUFFERS . release ( byteBuffer ) ; } }
Decodes the bounds of an image and returns its width and height or null if the size can t be determined
8,303
public static ImageMetaData decodeDimensionsAndColorSpace ( InputStream is ) { Preconditions . checkNotNull ( is ) ; ByteBuffer byteBuffer = DECODE_BUFFERS . acquire ( ) ; if ( byteBuffer == null ) { byteBuffer = ByteBuffer . allocate ( DECODE_BUFFER_SIZE ) ; } BitmapFactory . Options options = new BitmapFactory . Options ( ) ; options . inJustDecodeBounds = true ; try { options . inTempStorage = byteBuffer . array ( ) ; BitmapFactory . decodeStream ( is , null , options ) ; ColorSpace colorSpace = null ; if ( android . os . Build . VERSION . SDK_INT >= android . os . Build . VERSION_CODES . O ) { colorSpace = options . outColorSpace ; } return new ImageMetaData ( options . outWidth , options . outHeight , colorSpace ) ; } finally { DECODE_BUFFERS . release ( byteBuffer ) ; } }
Decodes the bounds of an image and returns its width and height or null if the size can t be determined . It also recovers the color space of the image or null if it can t be determined .
8,304
public static List < String > getResourceIds ( final CacheKey key ) { try { final List < String > ids ; if ( key instanceof MultiCacheKey ) { List < CacheKey > keys = ( ( MultiCacheKey ) key ) . getCacheKeys ( ) ; ids = new ArrayList < > ( keys . size ( ) ) ; for ( int i = 0 ; i < keys . size ( ) ; i ++ ) { ids . add ( secureHashKey ( keys . get ( i ) ) ) ; } } else { ids = new ArrayList < > ( 1 ) ; ids . add ( secureHashKey ( key ) ) ; } return ids ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } }
Get a list of possible resourceIds from MultiCacheKey or get single resourceId from CacheKey .
8,305
public static String getFirstResourceId ( final CacheKey key ) { try { if ( key instanceof MultiCacheKey ) { List < CacheKey > keys = ( ( MultiCacheKey ) key ) . getCacheKeys ( ) ; return secureHashKey ( keys . get ( 0 ) ) ; } else { return secureHashKey ( key ) ; } } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } }
Get the resourceId from the first key in MultiCacheKey or get single resourceId from CacheKey .
8,306
public DataSource < CloseableReference < CloseableImage > > fetchImageFromBitmapCache ( ImageRequest imageRequest , Object callerContext ) { return fetchDecodedImage ( imageRequest , callerContext , ImageRequest . RequestLevel . BITMAP_MEMORY_CACHE ) ; }
Submits a request for bitmap cache lookup .
8,307
public DataSource < Void > prefetchToBitmapCache ( ImageRequest imageRequest , Object callerContext ) { if ( ! mIsPrefetchEnabledSupplier . get ( ) ) { return DataSources . immediateFailedDataSource ( PREFETCH_EXCEPTION ) ; } try { final Boolean shouldDecodePrefetches = imageRequest . shouldDecodePrefetches ( ) ; final boolean skipBitmapCache = shouldDecodePrefetches != null ? ! shouldDecodePrefetches : mSuppressBitmapPrefetchingSupplier . get ( ) ; Producer < Void > producerSequence = skipBitmapCache ? mProducerSequenceFactory . getEncodedImagePrefetchProducerSequence ( imageRequest ) : mProducerSequenceFactory . getDecodedImagePrefetchProducerSequence ( imageRequest ) ; return submitPrefetchRequest ( producerSequence , imageRequest , ImageRequest . RequestLevel . FULL_FETCH , callerContext , Priority . MEDIUM ) ; } catch ( Exception exception ) { return DataSources . immediateFailedDataSource ( exception ) ; } }
Submits a request for prefetching to the bitmap cache .
8,308
public DataSource < Void > prefetchToDiskCache ( ImageRequest imageRequest , Object callerContext ) { return prefetchToDiskCache ( imageRequest , callerContext , Priority . MEDIUM ) ; }
Submits a request for prefetching to the disk cache with a default priority .
8,309
public DataSource < Void > prefetchToDiskCache ( ImageRequest imageRequest , Object callerContext , Priority priority ) { if ( ! mIsPrefetchEnabledSupplier . get ( ) ) { return DataSources . immediateFailedDataSource ( PREFETCH_EXCEPTION ) ; } try { Producer < Void > producerSequence = mProducerSequenceFactory . getEncodedImagePrefetchProducerSequence ( imageRequest ) ; return submitPrefetchRequest ( producerSequence , imageRequest , ImageRequest . RequestLevel . FULL_FETCH , callerContext , priority ) ; } catch ( Exception exception ) { return DataSources . immediateFailedDataSource ( exception ) ; } }
Submits a request for prefetching to the disk cache .
8,310
public void clearMemoryCaches ( ) { Predicate < CacheKey > allPredicate = new Predicate < CacheKey > ( ) { public boolean apply ( CacheKey key ) { return true ; } } ; mBitmapMemoryCache . removeAll ( allPredicate ) ; mEncodedMemoryCache . removeAll ( allPredicate ) ; }
Clear the memory caches
8,311
public boolean isInDiskCacheSync ( final ImageRequest imageRequest ) { final CacheKey cacheKey = mCacheKeyFactory . getEncodedCacheKey ( imageRequest , null ) ; final ImageRequest . CacheChoice cacheChoice = imageRequest . getCacheChoice ( ) ; switch ( cacheChoice ) { case DEFAULT : return mMainBufferedDiskCache . diskCheckSync ( cacheKey ) ; case SMALL : return mSmallImageBufferedDiskCache . diskCheckSync ( cacheKey ) ; default : return false ; } }
Performs disk cache check synchronously . It is not recommended to use this unless you know what exactly you are doing . Disk cache check is a costly operation the call will block the caller thread until the cache check is completed .
8,312
public DataSource < Boolean > isInDiskCache ( final ImageRequest imageRequest ) { final CacheKey cacheKey = mCacheKeyFactory . getEncodedCacheKey ( imageRequest , null ) ; final SimpleDataSource < Boolean > dataSource = SimpleDataSource . create ( ) ; mMainBufferedDiskCache . contains ( cacheKey ) . continueWithTask ( new Continuation < Boolean , Task < Boolean > > ( ) { public Task < Boolean > then ( Task < Boolean > task ) throws Exception { if ( ! task . isCancelled ( ) && ! task . isFaulted ( ) && task . getResult ( ) ) { return Task . forResult ( true ) ; } return mSmallImageBufferedDiskCache . contains ( cacheKey ) ; } } ) . continueWith ( new Continuation < Boolean , Void > ( ) { public Void then ( Task < Boolean > task ) throws Exception { dataSource . setResult ( ! task . isCancelled ( ) && ! task . isFaulted ( ) && task . getResult ( ) ) ; return null ; } } ) ; return dataSource ; }
Returns whether the image is stored in the disk cache .
8,313
private DrawableParent getParentDrawableAtIndex ( int index ) { DrawableParent parent = mFadeDrawable . getDrawableParentForIndex ( index ) ; if ( parent . getDrawable ( ) instanceof MatrixDrawable ) { parent = ( MatrixDrawable ) parent . getDrawable ( ) ; } if ( parent . getDrawable ( ) instanceof ScaleTypeDrawable ) { parent = ( ScaleTypeDrawable ) parent . getDrawable ( ) ; } return parent ; }
Gets the lowest parent drawable for the layer at the specified index .
8,314
private ScaleTypeDrawable getScaleTypeDrawableAtIndex ( int index ) { DrawableParent parent = getParentDrawableAtIndex ( index ) ; if ( parent instanceof ScaleTypeDrawable ) { return ( ScaleTypeDrawable ) parent ; } else { return WrappingUtils . wrapChildWithScaleType ( parent , ScalingUtils . ScaleType . FIT_XY ) ; } }
Gets the ScaleTypeDrawable at the specified index . In case there is no child at the specified index a NullPointerException is thrown . In case there is a child but the ScaleTypeDrawable does not exist the child will be wrapped with a new ScaleTypeDrawable .
8,315
public void setActualImageFocusPoint ( PointF focusPoint ) { Preconditions . checkNotNull ( focusPoint ) ; getScaleTypeDrawableAtIndex ( ACTUAL_IMAGE_INDEX ) . setFocusPoint ( focusPoint ) ; }
Sets the actual image focus point .
8,316
public void setActualImageScaleType ( ScalingUtils . ScaleType scaleType ) { Preconditions . checkNotNull ( scaleType ) ; getScaleTypeDrawableAtIndex ( ACTUAL_IMAGE_INDEX ) . setScaleType ( scaleType ) ; }
Sets the actual image scale type .
8,317
public void setPlaceholderImageFocusPoint ( PointF focusPoint ) { Preconditions . checkNotNull ( focusPoint ) ; getScaleTypeDrawableAtIndex ( PLACEHOLDER_IMAGE_INDEX ) . setFocusPoint ( focusPoint ) ; }
Sets the placeholder image focus point .
8,318
public void release ( V value ) { Preconditions . checkNotNull ( value ) ; final int bucketedSize = getBucketedSizeForValue ( value ) ; final int sizeInBytes = getSizeInBytes ( bucketedSize ) ; synchronized ( this ) { final Bucket < V > bucket = getBucketIfPresent ( bucketedSize ) ; if ( ! mInUseValues . remove ( value ) ) { FLog . e ( TAG , "release (free, value unrecognized) (object, size) = (%x, %s)" , System . identityHashCode ( value ) , bucketedSize ) ; free ( value ) ; mPoolStatsTracker . onFree ( sizeInBytes ) ; } else { if ( bucket == null || bucket . isMaxLengthExceeded ( ) || isMaxSizeSoftCapExceeded ( ) || ! isReusable ( value ) ) { if ( bucket != null ) { bucket . decrementInUseCount ( ) ; } if ( FLog . isLoggable ( FLog . VERBOSE ) ) { FLog . v ( TAG , "release (free) (object, size) = (%x, %s)" , System . identityHashCode ( value ) , bucketedSize ) ; } free ( value ) ; mUsed . decrement ( sizeInBytes ) ; mPoolStatsTracker . onFree ( sizeInBytes ) ; } else { bucket . release ( value ) ; mFree . increment ( sizeInBytes ) ; mUsed . decrement ( sizeInBytes ) ; mPoolStatsTracker . onValueRelease ( sizeInBytes ) ; if ( FLog . isLoggable ( FLog . VERBOSE ) ) { FLog . v ( TAG , "release (reuse) (object, size) = (%x, %s)" , System . identityHashCode ( value ) , bucketedSize ) ; } } } logStats ( ) ; } }
Releases the given value to the pool . In a few cases the value is freed instead of being released to the pool . If - the pool currently exceeds its max size OR - if the value does not map to a bucket that s currently maintained by the pool OR - if the bucket for the value exceeds its maxLength OR - if the value is not recognized by the pool then the value is freed .
8,319
synchronized Bucket < V > getBucket ( int bucketedSize ) { Bucket < V > bucket = mBuckets . get ( bucketedSize ) ; if ( bucket != null || ! mAllowNewBuckets ) { return bucket ; } if ( FLog . isLoggable ( FLog . VERBOSE ) ) { FLog . v ( TAG , "creating new bucket %s" , bucketedSize ) ; } Bucket < V > newBucket = newBucket ( bucketedSize ) ; mBuckets . put ( bucketedSize , newBucket ) ; return newBucket ; }
Gets the freelist for the specified bucket . Create the freelist if there isn t one
8,320
synchronized boolean canAllocate ( int sizeInBytes ) { int hardCap = mPoolParams . maxSizeHardCap ; if ( sizeInBytes > hardCap - mUsed . mNumBytes ) { mPoolStatsTracker . onHardCapReached ( ) ; return false ; } int softCap = mPoolParams . maxSizeSoftCap ; if ( sizeInBytes > softCap - ( mUsed . mNumBytes + mFree . mNumBytes ) ) { trimToSize ( softCap - sizeInBytes ) ; } if ( sizeInBytes > hardCap - ( mUsed . mNumBytes + mFree . mNumBytes ) ) { mPoolStatsTracker . onHardCapReached ( ) ; return false ; } return true ; }
Can we allocate a value of size sizeInBytes without exceeding the hard cap on the pool size? If allocating this value will take the pool over the hard cap we will first trim the pool down to its soft cap and then check again . If the current used bytes + this new value will take us above the hard cap then we return false immediately - there is no point freeing up anything .
8,321
public synchronized Map < String , Integer > getStats ( ) { Map < String , Integer > stats = new HashMap < String , Integer > ( ) ; for ( int i = 0 ; i < mBuckets . size ( ) ; ++ i ) { final int bucketedSize = mBuckets . keyAt ( i ) ; final Bucket < V > bucket = mBuckets . valueAt ( i ) ; final String BUCKET_USED_KEY = PoolStatsTracker . BUCKETS_USED_PREFIX + getSizeInBytes ( bucketedSize ) ; stats . put ( BUCKET_USED_KEY , bucket . getInUseCount ( ) ) ; } stats . put ( PoolStatsTracker . SOFT_CAP , mPoolParams . maxSizeSoftCap ) ; stats . put ( PoolStatsTracker . HARD_CAP , mPoolParams . maxSizeHardCap ) ; stats . put ( PoolStatsTracker . USED_COUNT , mUsed . mCount ) ; stats . put ( PoolStatsTracker . USED_BYTES , mUsed . mNumBytes ) ; stats . put ( PoolStatsTracker . FREE_COUNT , mFree . mCount ) ; stats . put ( PoolStatsTracker . FREE_BYTES , mFree . mNumBytes ) ; return stats ; }
Export memory stats regarding buckets used memory caps reused values .
8,322
public CloseableImage decode ( final EncodedImage encodedImage , final int length , final QualityInfo qualityInfo , final ImageDecodeOptions options ) { if ( options . customImageDecoder != null ) { return options . customImageDecoder . decode ( encodedImage , length , qualityInfo , options ) ; } ImageFormat imageFormat = encodedImage . getImageFormat ( ) ; if ( imageFormat == null || imageFormat == ImageFormat . UNKNOWN ) { imageFormat = ImageFormatChecker . getImageFormat_WrapIOException ( encodedImage . getInputStream ( ) ) ; encodedImage . setImageFormat ( imageFormat ) ; } if ( mCustomDecoders != null ) { ImageDecoder decoder = mCustomDecoders . get ( imageFormat ) ; if ( decoder != null ) { return decoder . decode ( encodedImage , length , qualityInfo , options ) ; } } return mDefaultDecoder . decode ( encodedImage , length , qualityInfo , options ) ; }
Decodes image .
8,323
public CloseableImage decodeGif ( final EncodedImage encodedImage , final int length , final QualityInfo qualityInfo , final ImageDecodeOptions options ) { if ( ! options . forceStaticImage && mAnimatedGifDecoder != null ) { return mAnimatedGifDecoder . decode ( encodedImage , length , qualityInfo , options ) ; } return decodeStaticImage ( encodedImage , options ) ; }
Decodes gif into CloseableImage .
8,324
public CloseableStaticBitmap decodeJpeg ( final EncodedImage encodedImage , int length , QualityInfo qualityInfo , ImageDecodeOptions options ) { CloseableReference < Bitmap > bitmapReference = mPlatformDecoder . decodeJPEGFromEncodedImageWithColorSpace ( encodedImage , options . bitmapConfig , null , length , options . colorSpace ) ; try { maybeApplyTransformation ( options . bitmapTransformation , bitmapReference ) ; return new CloseableStaticBitmap ( bitmapReference , qualityInfo , encodedImage . getRotationAngle ( ) , encodedImage . getExifOrientation ( ) ) ; } finally { bitmapReference . close ( ) ; } }
Decodes a partial jpeg .
8,325
public CloseableImage decodeAnimatedWebp ( final EncodedImage encodedImage , final int length , final QualityInfo qualityInfo , final ImageDecodeOptions options ) { return mAnimatedWebPDecoder . decode ( encodedImage , length , qualityInfo , options ) ; }
Decode a webp animated image into a CloseableImage .
8,326
public static PlatformBitmapFactory buildPlatformBitmapFactory ( PoolFactory poolFactory , PlatformDecoder platformDecoder ) { if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . LOLLIPOP ) { return new ArtBitmapFactory ( poolFactory . getBitmapPool ( ) ) ; } else if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . HONEYCOMB ) { return new HoneycombBitmapFactory ( new EmptyJpegGenerator ( poolFactory . getPooledByteBufferFactory ( ) ) , platformDecoder ) ; } else { return new GingerbreadBitmapFactory ( ) ; } }
Provide the implementation of the PlatformBitmapFactory for the current platform using the provided PoolFactory
8,327
public BinaryResource getResource ( final CacheKey key ) { String resourceId = null ; SettableCacheEvent cacheEvent = SettableCacheEvent . obtain ( ) . setCacheKey ( key ) ; try { synchronized ( mLock ) { BinaryResource resource = null ; List < String > resourceIds = CacheKeyUtil . getResourceIds ( key ) ; for ( int i = 0 ; i < resourceIds . size ( ) ; i ++ ) { resourceId = resourceIds . get ( i ) ; cacheEvent . setResourceId ( resourceId ) ; resource = mStorage . getResource ( resourceId , key ) ; if ( resource != null ) { break ; } } if ( resource == null ) { mCacheEventListener . onMiss ( cacheEvent ) ; mResourceIndex . remove ( resourceId ) ; } else { mCacheEventListener . onHit ( cacheEvent ) ; mResourceIndex . add ( resourceId ) ; } return resource ; } } catch ( IOException ioe ) { mCacheErrorLogger . logError ( CacheErrorLogger . CacheErrorCategory . GENERIC_IO , TAG , "getResource" , ioe ) ; cacheEvent . setException ( ioe ) ; mCacheEventListener . onReadException ( cacheEvent ) ; return null ; } finally { cacheEvent . recycle ( ) ; } }
Retrieves the file corresponding to the mKey if it is in the cache . Also touches the item thus changing its LRU timestamp . If the file is not present in the file cache returns null .
8,328
private DiskStorage . Inserter startInsert ( final String resourceId , final CacheKey key ) throws IOException { maybeEvictFilesInCacheDir ( ) ; return mStorage . insert ( resourceId , key ) ; }
Creates a temp file for writing outside the session lock
8,329
private BinaryResource endInsert ( final DiskStorage . Inserter inserter , final CacheKey key , String resourceId ) throws IOException { synchronized ( mLock ) { BinaryResource resource = inserter . commit ( key ) ; mResourceIndex . add ( resourceId ) ; mCacheStats . increment ( resource . size ( ) , 1 ) ; return resource ; } }
Commits the provided temp file to the cache renaming it to match the cache s hashing convention .
8,330
public long clearOldEntries ( long cacheExpirationMs ) { long oldestRemainingEntryAgeMs = 0L ; synchronized ( mLock ) { try { long now = mClock . now ( ) ; Collection < DiskStorage . Entry > allEntries = mStorage . getEntries ( ) ; final long cacheSizeBeforeClearance = mCacheStats . getSize ( ) ; int itemsRemovedCount = 0 ; long itemsRemovedSize = 0L ; for ( DiskStorage . Entry entry : allEntries ) { long entryAgeMs = Math . max ( 1 , Math . abs ( now - entry . getTimestamp ( ) ) ) ; if ( entryAgeMs >= cacheExpirationMs ) { long entryRemovedSize = mStorage . remove ( entry ) ; mResourceIndex . remove ( entry . getId ( ) ) ; if ( entryRemovedSize > 0 ) { itemsRemovedCount ++ ; itemsRemovedSize += entryRemovedSize ; SettableCacheEvent cacheEvent = SettableCacheEvent . obtain ( ) . setResourceId ( entry . getId ( ) ) . setEvictionReason ( CacheEventListener . EvictionReason . CONTENT_STALE ) . setItemSize ( entryRemovedSize ) . setCacheSize ( cacheSizeBeforeClearance - itemsRemovedSize ) ; mCacheEventListener . onEviction ( cacheEvent ) ; cacheEvent . recycle ( ) ; } } else { oldestRemainingEntryAgeMs = Math . max ( oldestRemainingEntryAgeMs , entryAgeMs ) ; } } mStorage . purgeUnexpectedResources ( ) ; if ( itemsRemovedCount > 0 ) { maybeUpdateFileCacheSize ( ) ; mCacheStats . increment ( - itemsRemovedSize , - itemsRemovedCount ) ; } } catch ( IOException ioe ) { mCacheErrorLogger . logError ( CacheErrorLogger . CacheErrorCategory . EVICTION , TAG , "clearOldEntries: " + ioe . getMessage ( ) , ioe ) ; } } return oldestRemainingEntryAgeMs ; }
Deletes old cache files .
8,331
private void maybeEvictFilesInCacheDir ( ) throws IOException { synchronized ( mLock ) { boolean calculatedRightNow = maybeUpdateFileCacheSize ( ) ; updateFileCacheSizeLimit ( ) ; long cacheSize = mCacheStats . getSize ( ) ; if ( cacheSize > mCacheSizeLimit && ! calculatedRightNow ) { mCacheStats . reset ( ) ; maybeUpdateFileCacheSize ( ) ; } if ( cacheSize > mCacheSizeLimit ) { evictAboveSize ( mCacheSizeLimit * 9 / 10 , CacheEventListener . EvictionReason . CACHE_FULL ) ; } } }
Test if the cache size has exceeded its limits and if so evict some files . It also calls maybeUpdateFileCacheSize
8,332
@ GuardedBy ( "mLock" ) private void updateFileCacheSizeLimit ( ) { boolean isAvailableSpaceLowerThanHighLimit ; StatFsHelper . StorageType storageType = mStorage . isExternal ( ) ? StatFsHelper . StorageType . EXTERNAL : StatFsHelper . StorageType . INTERNAL ; isAvailableSpaceLowerThanHighLimit = mStatFsHelper . testLowDiskSpace ( storageType , mDefaultCacheSizeLimit - mCacheStats . getSize ( ) ) ; if ( isAvailableSpaceLowerThanHighLimit ) { mCacheSizeLimit = mLowDiskSpaceCacheSizeLimit ; } else { mCacheSizeLimit = mDefaultCacheSizeLimit ; } }
Helper method that sets the cache size limit to be either a high or a low limit . If there is not enough free space to satisfy the high limit it is set to the low limit .
8,333
public static RoundingParams fromCornersRadii ( float topLeft , float topRight , float bottomRight , float bottomLeft ) { return ( new RoundingParams ( ) ) . setCornersRadii ( topLeft , topRight , bottomRight , bottomLeft ) ; }
Factory method that creates new RoundingParams with the specified corners radii .
8,334
public static int calcDesiredSize ( Context context , int parentWidth , int parentHeight ) { int orientation = context . getResources ( ) . getConfiguration ( ) . orientation ; int desiredSize = ( orientation == Configuration . ORIENTATION_LANDSCAPE ) ? parentWidth : parentHeight ; return Math . min ( desiredSize , parentWidth ) ; }
Calculate desired size for the given View based on device orientation
8,335
public static void setConfiguredSize ( final View parentView , final View draweeView , final Config config ) { if ( parentView != null ) { if ( config . overrideSize ) { SizeUtil . updateViewLayoutParams ( draweeView , config . overridenWidth , config . overridenHeight ) ; } else { int size = SizeUtil . calcDesiredSize ( parentView . getContext ( ) , parentView . getWidth ( ) , parentView . getHeight ( ) ) ; SizeUtil . updateViewLayoutParams ( draweeView , size , ( int ) ( size / Const . RATIO ) ) ; } } }
Utility method which set the size based on the parent and configurations
8,336
public static void initSizeData ( Activity activity ) { DisplayMetrics metrics = new DisplayMetrics ( ) ; activity . getWindowManager ( ) . getDefaultDisplay ( ) . getMetrics ( metrics ) ; DISPLAY_WIDTH = metrics . widthPixels ; DISPLAY_HEIGHT = metrics . heightPixels ; }
Invoke one into the Activity to get info about the Display size
8,337
private void configureBounds ( ) { Drawable underlyingDrawable = getCurrent ( ) ; Rect bounds = getBounds ( ) ; int underlyingWidth = mUnderlyingWidth = underlyingDrawable . getIntrinsicWidth ( ) ; int underlyingHeight = mUnderlyingHeight = underlyingDrawable . getIntrinsicHeight ( ) ; if ( underlyingWidth <= 0 || underlyingHeight <= 0 ) { underlyingDrawable . setBounds ( bounds ) ; mDrawMatrix = null ; } else { underlyingDrawable . setBounds ( 0 , 0 , underlyingWidth , underlyingHeight ) ; mDrawMatrix = mMatrix ; } }
Determines bounds for the underlying drawable and a matrix that should be applied on it .
8,338
public final ImageFormat determineFormat ( byte [ ] headerBytes , int headerSize ) { Preconditions . checkNotNull ( headerBytes ) ; if ( WebpSupportStatus . isWebpHeader ( headerBytes , 0 , headerSize ) ) { return getWebpFormat ( headerBytes , headerSize ) ; } if ( isJpegHeader ( headerBytes , headerSize ) ) { return DefaultImageFormats . JPEG ; } if ( isPngHeader ( headerBytes , headerSize ) ) { return DefaultImageFormats . PNG ; } if ( isGifHeader ( headerBytes , headerSize ) ) { return DefaultImageFormats . GIF ; } if ( isBmpHeader ( headerBytes , headerSize ) ) { return DefaultImageFormats . BMP ; } if ( isIcoHeader ( headerBytes , headerSize ) ) { return DefaultImageFormats . ICO ; } if ( isHeifHeader ( headerBytes , headerSize ) ) { return DefaultImageFormats . HEIF ; } return ImageFormat . UNKNOWN ; }
Tries to match imageHeaderByte and headerSize against every known image format . If any match succeeds corresponding ImageFormat is returned .
8,339
private static ImageFormat getWebpFormat ( final byte [ ] imageHeaderBytes , final int headerSize ) { Preconditions . checkArgument ( WebpSupportStatus . isWebpHeader ( imageHeaderBytes , 0 , headerSize ) ) ; if ( WebpSupportStatus . isSimpleWebpHeader ( imageHeaderBytes , 0 ) ) { return DefaultImageFormats . WEBP_SIMPLE ; } if ( WebpSupportStatus . isLosslessWebpHeader ( imageHeaderBytes , 0 ) ) { return DefaultImageFormats . WEBP_LOSSLESS ; } if ( WebpSupportStatus . isExtendedWebpHeader ( imageHeaderBytes , 0 , headerSize ) ) { if ( WebpSupportStatus . isAnimatedWebpHeader ( imageHeaderBytes , 0 ) ) { return DefaultImageFormats . WEBP_ANIMATED ; } if ( WebpSupportStatus . isExtendedWebpHeaderWithAlpha ( imageHeaderBytes , 0 ) ) { return DefaultImageFormats . WEBP_EXTENDED_WITH_ALPHA ; } return DefaultImageFormats . WEBP_EXTENDED ; } return ImageFormat . UNKNOWN ; }
Determines type of WebP image . imageHeaderBytes has to be header of a WebP image
8,340
public static void register ( ActivityListener activityListener , Context context ) { ListenableActivity activity = getListenableActivity ( context ) ; if ( activity != null ) { Listener listener = new Listener ( activityListener ) ; activity . addActivityListener ( listener ) ; } }
If given context is an instance of ListenableActivity then creates new instance of WeakReferenceActivityListenerAdapter and adds it to activity s listeners
8,341
public static EncodedImage cloneOrNull ( EncodedImage encodedImage ) { return encodedImage != null ? encodedImage . cloneOrNull ( ) : null ; }
Returns the cloned encoded image if the parameter received is not null null otherwise .
8,342
public InputStream getInputStream ( ) { if ( mInputStreamSupplier != null ) { return mInputStreamSupplier . get ( ) ; } CloseableReference < PooledByteBuffer > pooledByteBufferRef = CloseableReference . cloneOrNull ( mPooledByteBufferRef ) ; if ( pooledByteBufferRef != null ) { try { return new PooledByteBufferInputStream ( pooledByteBufferRef . get ( ) ) ; } finally { CloseableReference . closeSafely ( pooledByteBufferRef ) ; } } return null ; }
Returns an InputStream from the internal InputStream Supplier if it s not null . Otherwise returns an InputStream for the internal buffer reference if valid and null otherwise .
8,343
public boolean isCompleteAt ( int length ) { if ( mImageFormat != DefaultImageFormats . JPEG ) { return true ; } if ( mInputStreamSupplier != null ) { return true ; } Preconditions . checkNotNull ( mPooledByteBufferRef ) ; PooledByteBuffer buf = mPooledByteBufferRef . get ( ) ; return ( buf . read ( length - 2 ) == ( byte ) JfifUtil . MARKER_FIRST_BYTE ) && ( buf . read ( length - 1 ) == ( byte ) JfifUtil . MARKER_EOI ) ; }
Returns true if the image is a JPEG and its data is already complete at the specified length false otherwise .
8,344
public int getSize ( ) { if ( mPooledByteBufferRef != null && mPooledByteBufferRef . get ( ) != null ) { return mPooledByteBufferRef . get ( ) . size ( ) ; } return mStreamSize ; }
Returns the size of the backing structure .
8,345
public String getFirstBytesAsHexString ( int length ) { CloseableReference < PooledByteBuffer > imageBuffer = getByteBufferRef ( ) ; if ( imageBuffer == null ) { return "" ; } int imageSize = getSize ( ) ; int resultSampleSize = Math . min ( imageSize , length ) ; byte [ ] bytesBuffer = new byte [ resultSampleSize ] ; try { PooledByteBuffer pooledByteBuffer = imageBuffer . get ( ) ; if ( pooledByteBuffer == null ) { return "" ; } pooledByteBuffer . read ( 0 , bytesBuffer , 0 , resultSampleSize ) ; } finally { imageBuffer . close ( ) ; } StringBuilder stringBuilder = new StringBuilder ( bytesBuffer . length * 2 ) ; for ( byte b : bytesBuffer ) { stringBuilder . append ( String . format ( "%02X" , b ) ) ; } return stringBuilder . toString ( ) ; }
Returns first n bytes of encoded image as hexbytes
8,346
public void parseMetaData ( ) { final ImageFormat imageFormat = ImageFormatChecker . getImageFormat_WrapIOException ( getInputStream ( ) ) ; mImageFormat = imageFormat ; final Pair < Integer , Integer > dimensions ; if ( DefaultImageFormats . isWebpFormat ( imageFormat ) ) { dimensions = readWebPImageSize ( ) ; } else { dimensions = readImageMetaData ( ) . getDimensions ( ) ; } if ( imageFormat == DefaultImageFormats . JPEG && mRotationAngle == UNKNOWN_ROTATION_ANGLE ) { if ( dimensions != null ) { mExifOrientation = JfifUtil . getOrientation ( getInputStream ( ) ) ; mRotationAngle = JfifUtil . getAutoRotateAngleFromOrientation ( mExifOrientation ) ; } } else if ( imageFormat == DefaultImageFormats . HEIF && mRotationAngle == UNKNOWN_ROTATION_ANGLE ) { mExifOrientation = HeifExifUtil . getOrientation ( getInputStream ( ) ) ; mRotationAngle = JfifUtil . getAutoRotateAngleFromOrientation ( mExifOrientation ) ; } else { mRotationAngle = 0 ; } }
Sets the encoded image meta data .
8,347
private Pair < Integer , Integer > readWebPImageSize ( ) { final Pair < Integer , Integer > dimensions = WebpUtil . getSize ( getInputStream ( ) ) ; if ( dimensions != null ) { mWidth = dimensions . first ; mHeight = dimensions . second ; } return dimensions ; }
We get the size from a WebP image
8,348
private ImageMetaData readImageMetaData ( ) { InputStream inputStream = null ; ImageMetaData metaData = null ; try { inputStream = getInputStream ( ) ; metaData = BitmapUtil . decodeDimensionsAndColorSpace ( inputStream ) ; mColorSpace = metaData . getColorSpace ( ) ; Pair < Integer , Integer > dimensions = metaData . getDimensions ( ) ; if ( dimensions != null ) { mWidth = dimensions . first ; mHeight = dimensions . second ; } } finally { if ( inputStream != null ) { try { inputStream . close ( ) ; } catch ( IOException e ) { } } } return metaData ; }
We get the size from a generic image
8,349
public void copyMetaDataFrom ( EncodedImage encodedImage ) { mImageFormat = encodedImage . getImageFormat ( ) ; mWidth = encodedImage . getWidth ( ) ; mHeight = encodedImage . getHeight ( ) ; mRotationAngle = encodedImage . getRotationAngle ( ) ; mExifOrientation = encodedImage . getExifOrientation ( ) ; mSampleSize = encodedImage . getSampleSize ( ) ; mStreamSize = encodedImage . getSize ( ) ; mBytesRange = encodedImage . getBytesRange ( ) ; mColorSpace = encodedImage . getColorSpace ( ) ; }
Copy the meta data from another EncodedImage .
8,350
public void fixFrameDurations ( int [ ] frameDurationMs ) { for ( int i = 0 ; i < frameDurationMs . length ; i ++ ) { if ( frameDurationMs [ i ] < MIN_FRAME_DURATION_MS ) { frameDurationMs [ i ] = FRAME_DURATION_MS_FOR_MIN ; } } }
Adjusts the frame duration array to respect logic for minimum frame duration time .
8,351
public int getTotalDurationFromFrameDurations ( int [ ] frameDurationMs ) { int totalMs = 0 ; for ( int i = 0 ; i < frameDurationMs . length ; i ++ ) { totalMs += frameDurationMs [ i ] ; } return totalMs ; }
Gets the total duration of an image by summing up the duration of the frames .
8,352
public int [ ] getFrameTimeStampsFromDurations ( int [ ] frameDurationsMs ) { int [ ] frameTimestampsMs = new int [ frameDurationsMs . length ] ; int accumulatedDurationMs = 0 ; for ( int i = 0 ; i < frameDurationsMs . length ; i ++ ) { frameTimestampsMs [ i ] = accumulatedDurationMs ; accumulatedDurationMs += frameDurationsMs [ i ] ; } return frameTimestampsMs ; }
Given an array of frame durations generate an array of timestamps corresponding to when each frame beings .
8,353
public int getFrameForTimestampMs ( int frameTimestampsMs [ ] , int timestampMs ) { int index = Arrays . binarySearch ( frameTimestampsMs , timestampMs ) ; if ( index < 0 ) { return - index - 1 - 1 ; } else { return index ; } }
Gets the frame index for specified timestamp .
8,354
public void setImageRequest ( ImageRequest request ) { AbstractDraweeControllerBuilder controllerBuilder = mControllerBuilder ; DraweeController controller = controllerBuilder . setImageRequest ( request ) . setOldController ( getController ( ) ) . build ( ) ; setController ( controller ) ; }
Sets the image request
8,355
public static ImageRequestBuilder fromRequest ( ImageRequest imageRequest ) { return ImageRequestBuilder . newBuilderWithSource ( imageRequest . getSourceUri ( ) ) . setImageDecodeOptions ( imageRequest . getImageDecodeOptions ( ) ) . setBytesRange ( imageRequest . getBytesRange ( ) ) . setCacheChoice ( imageRequest . getCacheChoice ( ) ) . setLocalThumbnailPreviewsEnabled ( imageRequest . getLocalThumbnailPreviewsEnabled ( ) ) . setLowestPermittedRequestLevel ( imageRequest . getLowestPermittedRequestLevel ( ) ) . setPostprocessor ( imageRequest . getPostprocessor ( ) ) . setProgressiveRenderingEnabled ( imageRequest . getProgressiveRenderingEnabled ( ) ) . setRequestPriority ( imageRequest . getPriority ( ) ) . setResizeOptions ( imageRequest . getResizeOptions ( ) ) . setRequestListener ( imageRequest . getRequestListener ( ) ) . setRotationOptions ( imageRequest . getRotationOptions ( ) ) . setShouldDecodePrefetches ( imageRequest . shouldDecodePrefetches ( ) ) ; }
Creates a new request builder instance with the same parameters as the imageRequest passed in .
8,356
public ImageRequestBuilder setAutoRotateEnabled ( boolean enabled ) { if ( enabled ) { return setRotationOptions ( RotationOptions . autoRotate ( ) ) ; } else { return setRotationOptions ( RotationOptions . disableRotation ( ) ) ; } }
Enables or disables auto - rotate for the image in case image has orientation .
8,357
protected void validate ( ) { if ( mSourceUri == null ) { throw new BuilderException ( "Source must be set!" ) ; } if ( UriUtil . isLocalResourceUri ( mSourceUri ) ) { if ( ! mSourceUri . isAbsolute ( ) ) { throw new BuilderException ( "Resource URI path must be absolute." ) ; } if ( mSourceUri . getPath ( ) . isEmpty ( ) ) { throw new BuilderException ( "Resource URI must not be empty" ) ; } try { Integer . parseInt ( mSourceUri . getPath ( ) . substring ( 1 ) ) ; } catch ( NumberFormatException ignored ) { throw new BuilderException ( "Resource URI path must be a resource id." ) ; } } if ( UriUtil . isLocalAssetUri ( mSourceUri ) && ! mSourceUri . isAbsolute ( ) ) { throw new BuilderException ( "Asset URI path must be absolute." ) ; } }
Performs validation .
8,358
private static boolean isExtendedWebpSupported ( ) { if ( Build . VERSION . SDK_INT < Build . VERSION_CODES . JELLY_BEAN_MR1 ) { return false ; } if ( Build . VERSION . SDK_INT == Build . VERSION_CODES . JELLY_BEAN_MR1 ) { byte [ ] decodedBytes = Base64 . decode ( VP8X_WEBP_BASE64 , Base64 . DEFAULT ) ; BitmapFactory . Options opts = new BitmapFactory . Options ( ) ; opts . inJustDecodeBounds = true ; BitmapFactory . decodeByteArray ( decodedBytes , 0 , decodedBytes . length , opts ) ; if ( opts . outHeight != 1 || opts . outWidth != 1 ) { return false ; } } return true ; }
Checks whether underlying platform supports extended WebPs
8,359
public static int getAutoRotateAngleFromOrientation ( int orientation ) { switch ( orientation ) { case ExifInterface . ORIENTATION_NORMAL : case ExifInterface . ORIENTATION_UNDEFINED : return 0 ; case ExifInterface . ORIENTATION_ROTATE_180 : return 180 ; case ExifInterface . ORIENTATION_ROTATE_90 : return 90 ; case ExifInterface . ORIENTATION_ROTATE_270 : return 270 ; } return 0 ; }
Determines auto - rotate angle based on orientation information .
8,360
public static int readOrientationFromTIFF ( InputStream is , int length ) throws IOException { TiffHeader tiffHeader = new TiffHeader ( ) ; length = readTiffHeader ( is , length , tiffHeader ) ; int toSkip = tiffHeader . firstIfdOffset - 8 ; if ( length == 0 || toSkip > length ) { return 0 ; } is . skip ( toSkip ) ; length -= toSkip ; length = moveToTiffEntryWithTag ( is , length , tiffHeader . isLittleEndian , TIFF_TAG_ORIENTATION ) ; return getOrientationFromTiffEntry ( is , length , tiffHeader . isLittleEndian ) ; }
Reads orientation information from TIFF data .
8,361
private static int readTiffHeader ( InputStream is , int length , TiffHeader tiffHeader ) throws IOException { if ( length <= 8 ) { return 0 ; } tiffHeader . byteOrder = StreamProcessor . readPackedInt ( is , 4 , false ) ; length -= 4 ; if ( tiffHeader . byteOrder != TIFF_BYTE_ORDER_LITTLE_END && tiffHeader . byteOrder != TIFF_BYTE_ORDER_BIG_END ) { FLog . e ( TAG , "Invalid TIFF header" ) ; return 0 ; } tiffHeader . isLittleEndian = ( tiffHeader . byteOrder == TIFF_BYTE_ORDER_LITTLE_END ) ; tiffHeader . firstIfdOffset = StreamProcessor . readPackedInt ( is , 4 , tiffHeader . isLittleEndian ) ; length -= 4 ; if ( tiffHeader . firstIfdOffset < 8 || tiffHeader . firstIfdOffset - 8 > length ) { FLog . e ( TAG , "Invalid offset" ) ; return 0 ; } return length ; }
Reads the TIFF header to the provided structure .
8,362
private static int moveToTiffEntryWithTag ( InputStream is , int length , boolean isLittleEndian , int tagToFind ) throws IOException { if ( length < 14 ) { return 0 ; } int numEntries = StreamProcessor . readPackedInt ( is , 2 , isLittleEndian ) ; length -= 2 ; while ( numEntries -- > 0 && length >= 12 ) { int tag = StreamProcessor . readPackedInt ( is , 2 , isLittleEndian ) ; length -= 2 ; if ( tag == tagToFind ) { return length ; } is . skip ( 10 ) ; length -= 10 ; } return 0 ; }
Positions the given input stream to the entry that has a specified tag . Tag will be consumed .
8,363
private static int getOrientationFromTiffEntry ( InputStream is , int length , boolean isLittleEndian ) throws IOException { if ( length < 10 ) { return 0 ; } int type = StreamProcessor . readPackedInt ( is , 2 , isLittleEndian ) ; if ( type != TIFF_TYPE_SHORT ) { return 0 ; } int count = StreamProcessor . readPackedInt ( is , 4 , isLittleEndian ) ; if ( count != 1 ) { return 0 ; } int value = StreamProcessor . readPackedInt ( is , 2 , isLittleEndian ) ; int padding = StreamProcessor . readPackedInt ( is , 2 , isLittleEndian ) ; return value ; }
Reads the orientation information from the TIFF entry . It is assumed that the entry has a TIFF orientation tag and that tag has already been consumed .
8,364
public static AnimationBackend createSampleColorAnimationBackend ( Resources resources ) { int frameDurationMs = resources . getInteger ( android . R . integer . config_mediumAnimTime ) ; return new ExampleColorBackend ( SampleData . COLORS , frameDurationMs ) ; }
Creates a simple animation backend that cycles through a list of colors .
8,365
public CloseableReference < CloseableImage > cache ( int frameIndex , CloseableReference < CloseableImage > imageRef ) { return mBackingCache . cache ( keyFor ( frameIndex ) , imageRef , mEntryStateObserver ) ; }
Caches the image for the given frame index .
8,366
public CloseableReference < CloseableImage > getForReuse ( ) { while ( true ) { CacheKey key = popFirstFreeItemKey ( ) ; if ( key == null ) { return null ; } CloseableReference < CloseableImage > imageRef = mBackingCache . reuse ( key ) ; if ( imageRef != null ) { return imageRef ; } } }
Gets the image to be reused or null if there is no such image .
8,367
public static Matrix getTransformationMatrix ( final EncodedImage encodedImage , final RotationOptions rotationOptions ) { Matrix transformationMatrix = null ; if ( JpegTranscoderUtils . INVERTED_EXIF_ORIENTATIONS . contains ( encodedImage . getExifOrientation ( ) ) ) { final int exifOrientation = getForceRotatedInvertedExifOrientation ( rotationOptions , encodedImage ) ; transformationMatrix = getTransformationMatrixFromInvertedExif ( exifOrientation ) ; } else { final int rotationAngle = getRotationAngle ( rotationOptions , encodedImage ) ; if ( rotationAngle != 0 ) { transformationMatrix = new Matrix ( ) ; transformationMatrix . setRotate ( rotationAngle ) ; } } return transformationMatrix ; }
Compute the transformation matrix needed to rotate the image . If no transformation is needed it returns null .
8,368
public CloseableImage decodeGif ( final EncodedImage encodedImage , final ImageDecodeOptions options , final Bitmap . Config bitmapConfig ) { if ( sGifAnimatedImageDecoder == null ) { throw new UnsupportedOperationException ( "To encode animated gif please add the dependency " + "to the animated-gif module" ) ; } final CloseableReference < PooledByteBuffer > bytesRef = encodedImage . getByteBufferRef ( ) ; Preconditions . checkNotNull ( bytesRef ) ; try { final PooledByteBuffer input = bytesRef . get ( ) ; AnimatedImage gifImage ; if ( input . getByteBuffer ( ) != null ) { gifImage = sGifAnimatedImageDecoder . decode ( input . getByteBuffer ( ) ) ; } else { gifImage = sGifAnimatedImageDecoder . decode ( input . getNativePtr ( ) , input . size ( ) ) ; } return getCloseableImage ( options , gifImage , bitmapConfig ) ; } finally { CloseableReference . closeSafely ( bytesRef ) ; } }
Decodes a GIF into a CloseableImage .
8,369
private boolean ensureDataInBuffer ( ) throws IOException { if ( mBufferOffset < mBufferedSize ) { return true ; } final int readData = mInputStream . read ( mByteArray ) ; if ( readData <= 0 ) { return false ; } mBufferedSize = readData ; mBufferOffset = 0 ; return true ; }
Checks if there is some data left in the buffer . If not but buffered stream still has some data to be read then more data is buffered .
8,370
public void setDraweeSpanStringBuilder ( DraweeSpanStringBuilder draweeSpanStringBuilder ) { setText ( draweeSpanStringBuilder , BufferType . SPANNABLE ) ; mDraweeStringBuilder = draweeSpanStringBuilder ; if ( mDraweeStringBuilder != null && mIsAttached ) { mDraweeStringBuilder . onAttachToView ( this ) ; } }
Bind the given string builder to this view .
8,371
static ExecutableType getExecutableElementAsMemberOf ( Types types , ExecutableElement executableElement , TypeElement subTypeElement ) { checkNotNull ( types ) ; checkNotNull ( executableElement ) ; checkNotNull ( subTypeElement ) ; TypeMirror subTypeMirror = subTypeElement . asType ( ) ; if ( ! subTypeMirror . getKind ( ) . equals ( TypeKind . DECLARED ) ) { throw new IllegalStateException ( "Expected subTypeElement.asType() to return a class/interface type." ) ; } TypeMirror subExecutableTypeMirror = types . asMemberOf ( ( DeclaredType ) subTypeMirror , executableElement ) ; if ( ! subExecutableTypeMirror . getKind ( ) . equals ( TypeKind . EXECUTABLE ) ) { throw new IllegalStateException ( "Expected subExecutableTypeMirror to be an executable type." ) ; } return ( ExecutableType ) subExecutableTypeMirror ; }
Given an executable element in a supertype returns its ExecutableType when it is viewed as a member of a subtype .
8,372
private ImmutableMap < String , Optional < ? extends Element > > deferredElements ( ) { ImmutableMap . Builder < String , Optional < ? extends Element > > deferredElements = ImmutableMap . builder ( ) ; for ( ElementName elementName : deferredElementNames ) { deferredElements . put ( elementName . name ( ) , elementName . getElement ( elements ) ) ; } return deferredElements . build ( ) ; }
Returns the previously deferred elements .
8,373
private ImmutableSetMultimap < Class < ? extends Annotation > , Element > validElements ( ImmutableMap < String , Optional < ? extends Element > > deferredElements , RoundEnvironment roundEnv ) { ImmutableSetMultimap . Builder < Class < ? extends Annotation > , Element > deferredElementsByAnnotationBuilder = ImmutableSetMultimap . builder ( ) ; for ( Entry < String , Optional < ? extends Element > > deferredTypeElementEntry : deferredElements . entrySet ( ) ) { Optional < ? extends Element > deferredElement = deferredTypeElementEntry . getValue ( ) ; if ( deferredElement . isPresent ( ) ) { findAnnotatedElements ( deferredElement . get ( ) , getSupportedAnnotationClasses ( ) , deferredElementsByAnnotationBuilder ) ; } else { deferredElementNames . add ( ElementName . forTypeName ( deferredTypeElementEntry . getKey ( ) ) ) ; } } ImmutableSetMultimap < Class < ? extends Annotation > , Element > deferredElementsByAnnotation = deferredElementsByAnnotationBuilder . build ( ) ; ImmutableSetMultimap . Builder < Class < ? extends Annotation > , Element > validElements = ImmutableSetMultimap . builder ( ) ; Set < ElementName > validElementNames = new LinkedHashSet < ElementName > ( ) ; for ( Class < ? extends Annotation > annotationClass : getSupportedAnnotationClasses ( ) ) { TypeElement annotationType = elements . getTypeElement ( annotationClass . getCanonicalName ( ) ) ; Set < ? extends Element > elementsAnnotatedWith = ( annotationType == null ) ? ImmutableSet . < Element > of ( ) : roundEnv . getElementsAnnotatedWith ( annotationType ) ; for ( Element annotatedElement : Sets . union ( elementsAnnotatedWith , deferredElementsByAnnotation . get ( annotationClass ) ) ) { if ( annotatedElement . getKind ( ) . equals ( PACKAGE ) ) { PackageElement annotatedPackageElement = ( PackageElement ) annotatedElement ; ElementName annotatedPackageName = ElementName . forPackageName ( annotatedPackageElement . getQualifiedName ( ) . toString ( ) ) ; boolean validPackage = validElementNames . contains ( annotatedPackageName ) || ( ! deferredElementNames . contains ( annotatedPackageName ) && validateElement ( annotatedPackageElement ) ) ; if ( validPackage ) { validElements . put ( annotationClass , annotatedPackageElement ) ; validElementNames . add ( annotatedPackageName ) ; } else { deferredElementNames . add ( annotatedPackageName ) ; } } else { TypeElement enclosingType = getEnclosingType ( annotatedElement ) ; ElementName enclosingTypeName = ElementName . forTypeName ( enclosingType . getQualifiedName ( ) . toString ( ) ) ; boolean validEnclosingType = validElementNames . contains ( enclosingTypeName ) || ( ! deferredElementNames . contains ( enclosingTypeName ) && validateElement ( enclosingType ) ) ; if ( validEnclosingType ) { validElements . put ( annotationClass , annotatedElement ) ; validElementNames . add ( enclosingTypeName ) ; } else { deferredElementNames . add ( enclosingTypeName ) ; } } } } return validElements . build ( ) ; }
Returns the valid annotated elements contained in all of the deferred elements . If none are found for a deferred element defers it again .
8,374
private void process ( ImmutableSetMultimap < Class < ? extends Annotation > , Element > validElements ) { for ( ProcessingStep step : steps ) { ImmutableSetMultimap < Class < ? extends Annotation > , Element > stepElements = new ImmutableSetMultimap . Builder < Class < ? extends Annotation > , Element > ( ) . putAll ( indexByAnnotation ( elementsDeferredBySteps . get ( step ) , step . annotations ( ) ) ) . putAll ( filterKeys ( validElements , Predicates . < Object > in ( step . annotations ( ) ) ) ) . build ( ) ; if ( stepElements . isEmpty ( ) ) { elementsDeferredBySteps . removeAll ( step ) ; } else { Set < ? extends Element > rejectedElements = step . process ( stepElements ) ; elementsDeferredBySteps . replaceValues ( step , transform ( rejectedElements , new Function < Element , ElementName > ( ) { public ElementName apply ( Element element ) { return ElementName . forAnnotatedElement ( element ) ; } } ) ) ; } } }
Processes the valid elements including those previously deferred by each step .
8,375
private static TypeName annotatedReturnType ( ExecutableElement method ) { TypeMirror returnType = method . getReturnType ( ) ; List < AnnotationSpec > annotations = returnType . getAnnotationMirrors ( ) . stream ( ) . map ( AnnotationSpec :: get ) . collect ( toList ( ) ) ; return TypeName . get ( returnType ) . annotated ( annotations ) ; }
The return type of the given method including type annotations .
8,376
private Set < ExecutableElement > abstractMethods ( TypeElement typeElement ) { Set < ExecutableElement > methods = getLocalAndInheritedMethods ( typeElement , processingEnv . getTypeUtils ( ) , processingEnv . getElementUtils ( ) ) ; ImmutableSet . Builder < ExecutableElement > abstractMethods = ImmutableSet . builder ( ) ; for ( ExecutableElement method : methods ) { if ( method . getModifiers ( ) . contains ( Modifier . ABSTRACT ) ) { abstractMethods . add ( method ) ; } } return abstractMethods . build ( ) ; }
Return a set of all abstract methods in the given TypeElement or inherited from ancestors .
8,377
static Set < String > readServiceFile ( InputStream input ) throws IOException { HashSet < String > serviceClasses = new HashSet < String > ( ) ; Closer closer = Closer . create ( ) ; try { BufferedReader r = closer . register ( new BufferedReader ( new InputStreamReader ( input , UTF_8 ) ) ) ; String line ; while ( ( line = r . readLine ( ) ) != null ) { int commentStart = line . indexOf ( '#' ) ; if ( commentStart >= 0 ) { line = line . substring ( 0 , commentStart ) ; } line = line . trim ( ) ; if ( ! line . isEmpty ( ) ) { serviceClasses . add ( line ) ; } } return serviceClasses ; } catch ( Throwable t ) { throw closer . rethrow ( t ) ; } finally { closer . close ( ) ; } }
Reads the set of service classes from a service file .
8,378
static void writeServiceFile ( Collection < String > services , OutputStream output ) throws IOException { BufferedWriter writer = new BufferedWriter ( new OutputStreamWriter ( output , UTF_8 ) ) ; for ( String service : services ) { writer . write ( service ) ; writer . newLine ( ) ; } writer . flush ( ) ; }
Writes the set of service class names to a service file .
8,379
static Optional < BuilderMethodClassifier > classify ( Iterable < ExecutableElement > methods , ErrorReporter errorReporter , ProcessingEnvironment processingEnv , TypeElement autoValueClass , TypeElement builderType , ImmutableBiMap < ExecutableElement , String > getterToPropertyName , ImmutableMap < ExecutableElement , TypeMirror > getterToPropertyType , boolean autoValueHasToBuilder ) { BuilderMethodClassifier classifier = new BuilderMethodClassifier ( errorReporter , processingEnv , autoValueClass , builderType , getterToPropertyName , getterToPropertyType ) ; if ( classifier . classifyMethods ( methods , autoValueHasToBuilder ) ) { return Optional . of ( classifier ) ; } else { return Optional . empty ( ) ; } }
Classifies the given methods from a builder type and its ancestors .
8,380
private boolean classifyMethods ( Iterable < ExecutableElement > methods , boolean autoValueHasToBuilder ) { int startErrorCount = errorReporter . errorCount ( ) ; for ( ExecutableElement method : methods ) { classifyMethod ( method ) ; } if ( errorReporter . errorCount ( ) > startErrorCount ) { return false ; } Multimap < String , ExecutableElement > propertyNameToSetter ; if ( propertyNameToPrefixedSetters . isEmpty ( ) ) { propertyNameToSetter = propertyNameToUnprefixedSetters ; this . settersPrefixed = false ; } else if ( propertyNameToUnprefixedSetters . isEmpty ( ) ) { propertyNameToSetter = propertyNameToPrefixedSetters ; this . settersPrefixed = true ; } else { errorReporter . reportError ( "If any setter methods use the setFoo convention then all must" , propertyNameToUnprefixedSetters . values ( ) . iterator ( ) . next ( ) ) ; return false ; } getterToPropertyName . forEach ( ( getter , property ) -> { TypeMirror propertyType = getterToPropertyType . get ( getter ) ; boolean hasSetter = propertyNameToSetter . containsKey ( property ) ; PropertyBuilder propertyBuilder = propertyNameToPropertyBuilder . get ( property ) ; boolean hasBuilder = propertyBuilder != null ; if ( hasBuilder ) { boolean canMakeBarBuilder = ( propertyBuilder . getBuiltToBuilder ( ) != null || propertyBuilder . getCopyAll ( ) != null ) ; boolean needToMakeBarBuilder = ( autoValueHasToBuilder || hasSetter ) ; if ( needToMakeBarBuilder && ! canMakeBarBuilder ) { String error = String . format ( "Property builder method returns %1$s but there is no way to make that type" + " from %2$s: %2$s does not have a non-static toBuilder() method that" + " returns %1$s" , propertyBuilder . getBuilderTypeMirror ( ) , propertyType ) ; errorReporter . reportError ( error , propertyBuilder . getPropertyBuilderMethod ( ) ) ; } } else if ( ! hasSetter ) { String setterName = settersPrefixed ? prefixWithSet ( property ) : property ; String error = String . format ( "Expected a method with this signature: %s%s %s(%s), or a %sBuilder() method" , builderType , typeParamsString ( ) , setterName , propertyType , property ) ; errorReporter . reportError ( error , builderType ) ; } } ) ; return errorReporter . errorCount ( ) == startErrorCount ; }
Classifies the given methods and sets the state of this object based on what is found .
8,381
private void classifyMethod ( ExecutableElement method ) { switch ( method . getParameters ( ) . size ( ) ) { case 0 : classifyMethodNoArgs ( method ) ; break ; case 1 : classifyMethodOneArg ( method ) ; break ; default : errorReporter . reportError ( "Builder methods must have 0 or 1 parameters" , method ) ; } }
Classifies a method and update the state of this object based on what is found .
8,382
private void checkForFailedJavaBean ( ExecutableElement rejectedSetter ) { ImmutableSet < ExecutableElement > allGetters = getterToPropertyName . keySet ( ) ; ImmutableSet < ExecutableElement > prefixedGetters = AutoValueProcessor . prefixedGettersIn ( allGetters ) ; if ( prefixedGetters . size ( ) < allGetters . size ( ) && prefixedGetters . size ( ) >= allGetters . size ( ) / 2 ) { String note = "This might be because you are using the getFoo() convention" + " for some but not all methods. These methods don't follow the convention: " + difference ( allGetters , prefixedGetters ) ; errorReporter . reportNote ( note , rejectedSetter ) ; } }
setGetFoo ) .
8,383
ImmutableSortedSet < String > typesToImport ( ) { ImmutableSortedSet . Builder < String > typesToImport = ImmutableSortedSet . naturalOrder ( ) ; for ( Map . Entry < String , Spelling > entry : imports . entrySet ( ) ) { if ( entry . getValue ( ) . importIt ) { typesToImport . add ( entry . getKey ( ) ) ; } } return typesToImport . build ( ) ; }
Returns the set of types to import . We import every type that is neither in java . lang nor in the package containing the AutoValue class provided that the result refers to the type unambiguously . For example if there is a property of type java . util . Map . Entry then we will import java . util . Map . Entry and refer to the property as Entry . We could also import just java . util . Map in this case and refer to Map . Entry but currently we never do that .
8,384
static String classNameOf ( TypeElement type ) { String name = type . getQualifiedName ( ) . toString ( ) ; String pkgName = packageNameOf ( type ) ; return pkgName . isEmpty ( ) ? name : name . substring ( pkgName . length ( ) + 1 ) ; }
Returns the name of the given type including any enclosing types but not the package .
8,385
private static Map < String , Spelling > findImports ( Elements elementUtils , Types typeUtils , String codePackageName , Set < TypeMirror > referenced , Set < TypeMirror > defined ) { Map < String , Spelling > imports = new HashMap < > ( ) ; Set < TypeMirror > typesInScope = new TypeMirrorSet ( ) ; typesInScope . addAll ( referenced ) ; typesInScope . addAll ( defined ) ; Set < String > ambiguous = ambiguousNames ( typeUtils , typesInScope ) ; for ( TypeMirror type : referenced ) { TypeElement typeElement = ( TypeElement ) typeUtils . asElement ( type ) ; String fullName = typeElement . getQualifiedName ( ) . toString ( ) ; String simpleName = typeElement . getSimpleName ( ) . toString ( ) ; String pkg = packageNameOf ( typeElement ) ; boolean importIt ; String spelling ; if ( ambiguous . contains ( simpleName ) ) { importIt = false ; spelling = fullName ; } else if ( pkg . equals ( "java.lang" ) ) { importIt = false ; spelling = javaLangSpelling ( elementUtils , codePackageName , typeElement ) ; } else if ( pkg . equals ( codePackageName ) ) { importIt = false ; spelling = fullName . substring ( pkg . isEmpty ( ) ? 0 : pkg . length ( ) + 1 ) ; } else { importIt = true ; spelling = simpleName ; } imports . put ( fullName , new Spelling ( spelling , importIt ) ) ; } return imports ; }
Given a set of referenced types works out which of them should be imported and what the resulting spelling of each one is .
8,386
final void defineSharedVarsForType ( TypeElement type , ImmutableSet < ExecutableElement > methods , AutoValueOrOneOfTemplateVars vars ) { vars . pkg = TypeSimplifier . packageNameOf ( type ) ; vars . origClass = TypeSimplifier . classNameOf ( type ) ; vars . simpleClassName = TypeSimplifier . simpleNameOf ( vars . origClass ) ; vars . generated = generatedAnnotation ( elementUtils ( ) , processingEnv . getSourceVersion ( ) ) . map ( annotation -> TypeEncoder . encode ( annotation . asType ( ) ) ) . orElse ( "" ) ; vars . formalTypes = TypeEncoder . formalTypeParametersString ( type ) ; vars . actualTypes = TypeSimplifier . actualTypeParametersString ( type ) ; vars . wildcardTypes = wildcardTypeParametersString ( type ) ; vars . annotations = copiedClassAnnotations ( type ) ; Map < ObjectMethod , ExecutableElement > methodsToGenerate = determineObjectMethodsToGenerate ( methods ) ; vars . toString = methodsToGenerate . containsKey ( ObjectMethod . TO_STRING ) ; vars . equals = methodsToGenerate . containsKey ( ObjectMethod . EQUALS ) ; vars . hashCode = methodsToGenerate . containsKey ( ObjectMethod . HASH_CODE ) ; vars . equalsParameterType = equalsParameterType ( methodsToGenerate ) ; }
Defines the template variables that are shared by AutoValue and AutoOneOf .
8,387
static ImmutableList < String > annotationStrings ( List < ? extends AnnotationMirror > annotations ) { return ImmutableList . copyOf ( annotations . stream ( ) . map ( AnnotationOutput :: sourceFormForAnnotation ) . collect ( toList ( ) ) ) ; }
Returns the spelling to be used in the generated code for the given list of annotations .
8,388
final ImmutableBiMap < String , ExecutableElement > propertyNameToMethodMap ( Set < ExecutableElement > propertyMethods ) { Map < String , ExecutableElement > map = new LinkedHashMap < > ( ) ; Set < String > reportedDups = new HashSet < > ( ) ; boolean allPrefixed = gettersAllPrefixed ( propertyMethods ) ; for ( ExecutableElement method : propertyMethods ) { String methodName = method . getSimpleName ( ) . toString ( ) ; String name = allPrefixed ? nameWithoutPrefix ( methodName ) : methodName ; ExecutableElement old = map . put ( name , method ) ; if ( old != null ) { String message = "More than one @" + simpleAnnotationName + " property called " + name ; errorReporter . reportError ( message , method ) ; if ( reportedDups . add ( name ) ) { errorReporter . reportError ( message , old ) ; } } } return ImmutableBiMap . copyOf ( map ) ; }
Returns a bi - map between property names and the corresponding abstract property methods .
8,389
static ImmutableSet < ExecutableElement > abstractMethodsIn ( ImmutableSet < ExecutableElement > methods ) { Set < Name > noArgMethods = new HashSet < > ( ) ; ImmutableSet . Builder < ExecutableElement > abstracts = ImmutableSet . builder ( ) ; for ( ExecutableElement method : methods ) { if ( method . getModifiers ( ) . contains ( Modifier . ABSTRACT ) ) { boolean hasArgs = ! method . getParameters ( ) . isEmpty ( ) ; if ( hasArgs || noArgMethods . add ( method . getSimpleName ( ) ) ) { abstracts . add ( method ) ; } } } return abstracts . build ( ) ; }
Returns the subset of all abstract methods in the given set of methods . A given method signature is only mentioned once even if it is inherited on more than one path .
8,390
final void checkReturnType ( TypeElement autoValueClass , ExecutableElement getter ) { TypeMirror type = getter . getReturnType ( ) ; if ( type . getKind ( ) == TypeKind . ARRAY ) { TypeMirror componentType = ( ( ArrayType ) type ) . getComponentType ( ) ; if ( componentType . getKind ( ) . isPrimitive ( ) ) { warnAboutPrimitiveArrays ( autoValueClass , getter ) ; } else { errorReporter . reportError ( "An @" + simpleAnnotationName + " class cannot define an array-valued property unless it is a primitive array" , getter ) ; } } }
Checks that the return type of the given property method is allowed . Currently this means that it cannot be an array unless it is a primitive array .
8,391
static Optionalish createIfOptional ( TypeMirror type ) { if ( isOptional ( type ) ) { return new Optionalish ( MoreTypes . asDeclared ( type ) ) ; } else { return null ; } }
Returns an instance wrapping the given TypeMirror or null if it is not any kind of Optional .
8,392
void reportNote ( String msg , Element e ) { messager . printMessage ( Diagnostic . Kind . NOTE , msg , e ) ; }
Issue a compilation note .
8,393
void reportWarning ( String msg , Element e ) { messager . printMessage ( Diagnostic . Kind . WARNING , msg , e ) ; }
Issue a compilation warning .
8,394
static String sourceFormForInitializer ( AnnotationValue annotationValue , ProcessingEnvironment processingEnv , String memberName , Element context ) { SourceFormVisitor visitor = new InitializerSourceFormVisitor ( processingEnv , memberName , context ) ; StringBuilder sb = new StringBuilder ( ) ; visitor . visit ( annotationValue , sb ) ; return sb . toString ( ) ; }
Returns a string representation of the given annotation value suitable for inclusion in a Java source file as the initializer of a variable of the appropriate type .
8,395
static String sourceFormForAnnotation ( AnnotationMirror annotationMirror ) { StringBuilder sb = new StringBuilder ( ) ; new AnnotationSourceFormVisitor ( ) . visitAnnotation ( annotationMirror , sb ) ; return sb . toString ( ) ; }
Returns a string representation of the given annotation mirror suitable for inclusion in a Java source file to reproduce the annotation in source form .
8,396
public static Optional < DeclaredType > nonObjectSuperclass ( final Types types , Elements elements , DeclaredType type ) { checkNotNull ( types ) ; checkNotNull ( elements ) ; checkNotNull ( type ) ; final TypeMirror objectType = elements . getTypeElement ( Object . class . getCanonicalName ( ) ) . asType ( ) ; TypeMirror superclass = getOnlyElement ( FluentIterable . from ( types . directSupertypes ( type ) ) . filter ( new Predicate < TypeMirror > ( ) { public boolean apply ( TypeMirror input ) { return input . getKind ( ) . equals ( TypeKind . DECLARED ) && ( MoreElements . asType ( MoreTypes . asDeclared ( input ) . asElement ( ) ) ) . getKind ( ) . equals ( ElementKind . CLASS ) && ! types . isSameType ( objectType , input ) ; } } ) , null ) ; return superclass != null ? Optional . of ( MoreTypes . asDeclared ( superclass ) ) : Optional . < DeclaredType > absent ( ) ; }
Returns the non - object superclass of the type with the proper type parameters . An absent Optional is returned if there is no non - Object superclass .
8,397
private static Reader readerFromUrl ( String resourceName ) throws IOException { URL resourceUrl = TemplateVars . class . getResource ( resourceName ) ; InputStream in ; try { if ( resourceUrl . getProtocol ( ) . equalsIgnoreCase ( "file" ) ) { in = inputStreamFromFile ( resourceUrl ) ; } else if ( resourceUrl . getProtocol ( ) . equalsIgnoreCase ( "jar" ) ) { in = inputStreamFromJar ( resourceUrl ) ; } else { throw new AssertionError ( "Template fallback logic fails for: " + resourceUrl ) ; } } catch ( URISyntaxException e ) { throw new IOException ( e ) ; } return new InputStreamReader ( in , StandardCharsets . UTF_8 ) ; }
through the getResourceAsStream should be a lot more efficient than reopening the jar .
8,398
private static InputStream inputStreamFromFile ( URL resourceUrl ) throws IOException , URISyntaxException { File resourceFile = new File ( resourceUrl . toURI ( ) ) ; return new FileInputStream ( resourceFile ) ; }
system does run it using a jar so we do have coverage .
8,399
public static boolean overrides ( ExecutableElement overrider , ExecutableElement overridden , TypeElement type , Types typeUtils ) { return new ExplicitOverrides ( typeUtils ) . overrides ( overrider , overridden , type ) ; }
Tests whether one method as a member of a given type overrides another method .