-
Notifications
You must be signed in to change notification settings - Fork 637
/
ImageRequest.kt
1055 lines (933 loc) · 37.6 KB
/
ImageRequest.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
@file:Suppress("UNUSED_PARAMETER")
package coil.request
import android.content.Context
import android.graphics.Bitmap
import android.graphics.ColorSpace
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Build.VERSION.SDK_INT
import android.widget.ImageView
import android.widget.ImageView.ScaleType.CENTER
import android.widget.ImageView.ScaleType.MATRIX
import androidx.annotation.DrawableRes
import androidx.annotation.MainThread
import androidx.annotation.Px
import androidx.annotation.RequiresApi
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import coil.ComponentRegistry
import coil.ImageLoader
import coil.decode.Decoder
import coil.drawable.CrossfadeDrawable
import coil.fetch.Fetcher
import coil.memory.MemoryCache
import coil.request.ImageRequest.Builder
import coil.size.Dimension
import coil.size.DisplaySizeResolver
import coil.size.Precision
import coil.size.Scale
import coil.size.Size
import coil.size.SizeResolver
import coil.size.ViewSizeResolver
import coil.target.ImageViewTarget
import coil.target.Target
import coil.target.ViewTarget
import coil.transform.Transformation
import coil.transition.CrossfadeTransition
import coil.transition.Transition
import coil.util.DEFAULT_REQUEST_OPTIONS
import coil.util.allowInexactSize
import coil.util.getDrawableCompat
import coil.util.getLifecycle
import coil.util.orEmpty
import coil.util.scale
import coil.util.toImmutableList
import coil.util.unsupported
import kotlinx.coroutines.CoroutineDispatcher
import okhttp3.Headers
import okhttp3.HttpUrl
import java.io.File
import java.nio.ByteBuffer
/**
* An immutable value object that represents a request for an image.
*
* @see ImageLoader.enqueue
* @see ImageLoader.execute
*/
class ImageRequest private constructor(
val context: Context,
/** @see Builder.data */
val data: Any,
/** @see Builder.target */
val target: Target?,
/** @see Builder.listener */
val listener: Listener?,
/** @see Builder.memoryCacheKey */
val memoryCacheKey: MemoryCache.Key?,
/** @see Builder.diskCacheKey */
val diskCacheKey: String?,
/** @see Builder.bitmapConfig */
val bitmapConfig: Bitmap.Config,
/** @see Builder.colorSpace */
val colorSpace: ColorSpace?,
/** @see Builder.precision */
val precision: Precision,
/** @see Builder.fetcherFactory */
val fetcherFactory: Pair<Fetcher.Factory<*>, Class<*>>?,
/** @see Builder.decoderFactory */
val decoderFactory: Decoder.Factory?,
/** @see Builder.transformations */
val transformations: List<Transformation>,
/** @see Builder.transitionFactory */
val transitionFactory: Transition.Factory,
/** @see Builder.headers */
val headers: Headers,
/** @see Builder.tags */
val tags: Tags,
/** @see Builder.allowConversionToBitmap */
val allowConversionToBitmap: Boolean,
/** @see Builder.allowHardware */
val allowHardware: Boolean,
/** @see Builder.allowRgb565 */
val allowRgb565: Boolean,
/** @see Builder.premultipliedAlpha */
val premultipliedAlpha: Boolean,
/** @see Builder.memoryCachePolicy */
val memoryCachePolicy: CachePolicy,
/** @see Builder.diskCachePolicy */
val diskCachePolicy: CachePolicy,
/** @see Builder.networkCachePolicy */
val networkCachePolicy: CachePolicy,
/** @see Builder.interceptorDispatcher */
val interceptorDispatcher: CoroutineDispatcher,
/** @see Builder.fetcherDispatcher */
val fetcherDispatcher: CoroutineDispatcher,
/** @see Builder.decoderDispatcher */
val decoderDispatcher: CoroutineDispatcher,
/** @see Builder.transformationDispatcher */
val transformationDispatcher: CoroutineDispatcher,
/** @see Builder.lifecycle */
val lifecycle: Lifecycle,
/** @see Builder.size */
val sizeResolver: SizeResolver,
/** @see Builder.scale */
val scale: Scale,
/** @see Builder.parameters */
val parameters: Parameters,
/** @see Builder.placeholderMemoryCacheKey */
val placeholderMemoryCacheKey: MemoryCache.Key?,
private val placeholderResId: Int?,
private val placeholderDrawable: Drawable?,
private val errorResId: Int?,
private val errorDrawable: Drawable?,
private val fallbackResId: Int?,
private val fallbackDrawable: Drawable?,
/** The raw values set on [Builder]. */
val defined: DefinedRequestOptions,
/** The defaults used to fill unset values. */
val defaults: DefaultRequestOptions,
) {
/** @see Builder.placeholder */
val placeholder: Drawable?
get() = getDrawableCompat(placeholderDrawable, placeholderResId, defaults.placeholder)
/** @see Builder.error */
val error: Drawable?
get() = getDrawableCompat(errorDrawable, errorResId, defaults.error)
/** @see Builder.fallback */
val fallback: Drawable?
get() = getDrawableCompat(fallbackDrawable, fallbackResId, defaults.fallback)
@JvmOverloads
fun newBuilder(context: Context = this.context) = Builder(this, context)
override fun equals(other: Any?): Boolean {
if (this === other) return true
return other is ImageRequest &&
context == other.context &&
data == other.data &&
target == other.target &&
listener == other.listener &&
memoryCacheKey == other.memoryCacheKey &&
diskCacheKey == other.diskCacheKey &&
bitmapConfig == other.bitmapConfig &&
(SDK_INT < 26 || colorSpace == other.colorSpace) &&
precision == other.precision &&
fetcherFactory == other.fetcherFactory &&
decoderFactory == other.decoderFactory &&
transformations == other.transformations &&
transitionFactory == other.transitionFactory &&
headers == other.headers &&
tags == other.tags &&
allowConversionToBitmap == other.allowConversionToBitmap &&
allowHardware == other.allowHardware &&
allowRgb565 == other.allowRgb565 &&
premultipliedAlpha == other.premultipliedAlpha &&
memoryCachePolicy == other.memoryCachePolicy &&
diskCachePolicy == other.diskCachePolicy &&
networkCachePolicy == other.networkCachePolicy &&
interceptorDispatcher == other.interceptorDispatcher &&
fetcherDispatcher == other.fetcherDispatcher &&
decoderDispatcher == other.decoderDispatcher &&
transformationDispatcher == other.transformationDispatcher &&
placeholderMemoryCacheKey == other.placeholderMemoryCacheKey &&
placeholderResId == other.placeholderResId &&
placeholderDrawable == other.placeholderDrawable &&
errorResId == other.errorResId &&
errorDrawable == other.errorDrawable &&
fallbackResId == other.fallbackResId &&
fallbackDrawable == other.fallbackDrawable &&
lifecycle == other.lifecycle &&
sizeResolver == other.sizeResolver &&
scale == other.scale &&
parameters == other.parameters &&
defined == other.defined &&
defaults == other.defaults
}
override fun hashCode(): Int {
var result = context.hashCode()
result = 31 * result + data.hashCode()
result = 31 * result + target.hashCode()
result = 31 * result + listener.hashCode()
result = 31 * result + memoryCacheKey.hashCode()
result = 31 * result + diskCacheKey.hashCode()
result = 31 * result + bitmapConfig.hashCode()
result = 31 * result + colorSpace.hashCode()
result = 31 * result + precision.hashCode()
result = 31 * result + fetcherFactory.hashCode()
result = 31 * result + decoderFactory.hashCode()
result = 31 * result + transformations.hashCode()
result = 31 * result + transitionFactory.hashCode()
result = 31 * result + headers.hashCode()
result = 31 * result + tags.hashCode()
result = 31 * result + allowConversionToBitmap.hashCode()
result = 31 * result + allowHardware.hashCode()
result = 31 * result + allowRgb565.hashCode()
result = 31 * result + premultipliedAlpha.hashCode()
result = 31 * result + memoryCachePolicy.hashCode()
result = 31 * result + diskCachePolicy.hashCode()
result = 31 * result + networkCachePolicy.hashCode()
result = 31 * result + interceptorDispatcher.hashCode()
result = 31 * result + fetcherDispatcher.hashCode()
result = 31 * result + decoderDispatcher.hashCode()
result = 31 * result + transformationDispatcher.hashCode()
result = 31 * result + lifecycle.hashCode()
result = 31 * result + sizeResolver.hashCode()
result = 31 * result + scale.hashCode()
result = 31 * result + parameters.hashCode()
result = 31 * result + placeholderMemoryCacheKey.hashCode()
result = 31 * result + placeholderResId.hashCode()
result = 31 * result + placeholderDrawable.hashCode()
result = 31 * result + errorResId.hashCode()
result = 31 * result + errorDrawable.hashCode()
result = 31 * result + fallbackResId.hashCode()
result = 31 * result + fallbackDrawable.hashCode()
result = 31 * result + defined.hashCode()
result = 31 * result + defaults.hashCode()
return result
}
/**
* A set of callbacks for an [ImageRequest].
*/
interface Listener {
/**
* Called immediately after [Target.onStart].
*/
@MainThread
fun onStart(request: ImageRequest) {}
/**
* Called if the request is cancelled.
*/
@MainThread
fun onCancel(request: ImageRequest) {}
/**
* Called if an error occurs while executing the request.
*/
@MainThread
fun onError(request: ImageRequest, result: ErrorResult) {}
/**
* Called if the request completes successfully.
*/
@MainThread
fun onSuccess(request: ImageRequest, result: SuccessResult) {}
}
class Builder {
private val context: Context
private var defaults: DefaultRequestOptions
private var data: Any?
private var target: Target?
private var listener: Listener?
private var memoryCacheKey: MemoryCache.Key?
private var diskCacheKey: String?
private var bitmapConfig: Bitmap.Config?
private var colorSpace: ColorSpace? = null
private var precision: Precision?
private var fetcherFactory: Pair<Fetcher.Factory<*>, Class<*>>?
private var decoderFactory: Decoder.Factory?
private var transformations: List<Transformation>
private var transitionFactory: Transition.Factory?
private var headers: Headers.Builder?
private var tags: MutableMap<Class<*>, Any>?
private var allowConversionToBitmap: Boolean
private var allowHardware: Boolean?
private var allowRgb565: Boolean?
private var premultipliedAlpha: Boolean
private var memoryCachePolicy: CachePolicy?
private var diskCachePolicy: CachePolicy?
private var networkCachePolicy: CachePolicy?
private var interceptorDispatcher: CoroutineDispatcher?
private var fetcherDispatcher: CoroutineDispatcher?
private var decoderDispatcher: CoroutineDispatcher?
private var transformationDispatcher: CoroutineDispatcher?
private var parameters: Parameters.Builder?
private var placeholderMemoryCacheKey: MemoryCache.Key?
@DrawableRes private var placeholderResId: Int?
private var placeholderDrawable: Drawable?
@DrawableRes private var errorResId: Int?
private var errorDrawable: Drawable?
@DrawableRes private var fallbackResId: Int?
private var fallbackDrawable: Drawable?
private var lifecycle: Lifecycle?
private var sizeResolver: SizeResolver?
private var scale: Scale?
private var resolvedLifecycle: Lifecycle?
private var resolvedSizeResolver: SizeResolver?
private var resolvedScale: Scale?
constructor(context: Context) {
this.context = context
defaults = DEFAULT_REQUEST_OPTIONS
data = null
target = null
listener = null
memoryCacheKey = null
diskCacheKey = null
bitmapConfig = null
if (SDK_INT >= 26) colorSpace = null
precision = null
fetcherFactory = null
decoderFactory = null
transformations = emptyList()
transitionFactory = null
headers = null
tags = null
allowConversionToBitmap = true
allowHardware = null
allowRgb565 = null
premultipliedAlpha = true
memoryCachePolicy = null
diskCachePolicy = null
networkCachePolicy = null
interceptorDispatcher = null
fetcherDispatcher = null
decoderDispatcher = null
transformationDispatcher = null
parameters = null
placeholderMemoryCacheKey = null
placeholderResId = null
placeholderDrawable = null
errorResId = null
errorDrawable = null
fallbackResId = null
fallbackDrawable = null
lifecycle = null
sizeResolver = null
scale = null
resolvedLifecycle = null
resolvedSizeResolver = null
resolvedScale = null
}
@JvmOverloads
constructor(request: ImageRequest, context: Context = request.context) {
this.context = context
defaults = request.defaults
data = request.data
target = request.target
listener = request.listener
memoryCacheKey = request.memoryCacheKey
diskCacheKey = request.diskCacheKey
bitmapConfig = request.defined.bitmapConfig
if (SDK_INT >= 26) colorSpace = request.colorSpace
precision = request.defined.precision
fetcherFactory = request.fetcherFactory
decoderFactory = request.decoderFactory
transformations = request.transformations
transitionFactory = request.defined.transitionFactory
headers = request.headers.newBuilder()
tags = request.tags.asMap().toMutableMap()
allowConversionToBitmap = request.allowConversionToBitmap
allowHardware = request.defined.allowHardware
allowRgb565 = request.defined.allowRgb565
premultipliedAlpha = request.premultipliedAlpha
memoryCachePolicy = request.defined.memoryCachePolicy
diskCachePolicy = request.defined.diskCachePolicy
networkCachePolicy = request.defined.networkCachePolicy
interceptorDispatcher = request.defined.interceptorDispatcher
fetcherDispatcher = request.defined.fetcherDispatcher
decoderDispatcher = request.defined.decoderDispatcher
transformationDispatcher = request.defined.transformationDispatcher
parameters = request.parameters.newBuilder()
placeholderMemoryCacheKey = request.placeholderMemoryCacheKey
placeholderResId = request.placeholderResId
placeholderDrawable = request.placeholderDrawable
errorResId = request.errorResId
errorDrawable = request.errorDrawable
fallbackResId = request.fallbackResId
fallbackDrawable = request.fallbackDrawable
lifecycle = request.defined.lifecycle
sizeResolver = request.defined.sizeResolver
scale = request.defined.scale
// If the context changes, recompute the resolved values.
if (request.context === context) {
resolvedLifecycle = request.lifecycle
resolvedSizeResolver = request.sizeResolver
resolvedScale = request.scale
} else {
resolvedLifecycle = null
resolvedSizeResolver = null
resolvedScale = null
}
}
/**
* Set the data to load.
*
* The default supported data types are:
* - [String] (mapped to a [Uri])
* - [Uri] ("android.resource", "content", "file", "http", and "https" schemes only)
* - [HttpUrl]
* - [File]
* - [DrawableRes]
* - [Drawable]
* - [Bitmap]
* - [ByteArray]
* - [ByteBuffer]
*/
fun data(data: Any?) = apply {
this.data = data
}
/**
* Set the memory cache key for this request.
*
* If this is null or is not set, the [ImageLoader] will compute a memory cache key.
*/
fun memoryCacheKey(key: String?) = memoryCacheKey(key?.let { MemoryCache.Key(it) })
/**
* Set the memory cache key for this request.
*
* If this is null or is not set, the [ImageLoader] will compute a memory cache key.
*/
fun memoryCacheKey(key: MemoryCache.Key?) = apply {
this.memoryCacheKey = key
}
/**
* Set the disk cache key for this request.
*
* If this is null or is not set, the [ImageLoader] will compute a disk cache key.
*/
fun diskCacheKey(key: String?) = apply {
this.diskCacheKey = key
}
/**
* Convenience function to create and set the [Listener].
*/
inline fun listener(
crossinline onStart: (request: ImageRequest) -> Unit = {},
crossinline onCancel: (request: ImageRequest) -> Unit = {},
crossinline onError: (request: ImageRequest, result: ErrorResult) -> Unit = { _, _ -> },
crossinline onSuccess: (request: ImageRequest, result: SuccessResult) -> Unit = { _, _ -> }
) = listener(object : Listener {
override fun onStart(request: ImageRequest) = onStart(request)
override fun onCancel(request: ImageRequest) = onCancel(request)
override fun onError(request: ImageRequest, result: ErrorResult) = onError(request, result)
override fun onSuccess(request: ImageRequest, result: SuccessResult) = onSuccess(request, result)
})
/**
* Set the [Listener].
*/
fun listener(listener: Listener?) = apply {
this.listener = listener
}
/**
* @see ImageLoader.Builder.dispatcher
*/
fun dispatcher(dispatcher: CoroutineDispatcher) = apply {
this.fetcherDispatcher = dispatcher
this.decoderDispatcher = dispatcher
this.transformationDispatcher = dispatcher
}
/**
* @see ImageLoader.Builder.interceptorDispatcher
*/
fun interceptorDispatcher(dispatcher: CoroutineDispatcher) = apply {
this.interceptorDispatcher = dispatcher
}
/**
* @see ImageLoader.Builder.fetcherDispatcher
*/
fun fetcherDispatcher(dispatcher: CoroutineDispatcher) = apply {
this.fetcherDispatcher = dispatcher
}
/**
* @see ImageLoader.Builder.decoderDispatcher
*/
fun decoderDispatcher(dispatcher: CoroutineDispatcher) = apply {
this.decoderDispatcher = dispatcher
}
/**
* @see ImageLoader.Builder.transformationDispatcher
*/
fun transformationDispatcher(dispatcher: CoroutineDispatcher) = apply {
this.transformationDispatcher = dispatcher
}
/**
* Set the list of [Transformation]s to be applied to this request.
*/
fun transformations(vararg transformations: Transformation) =
transformations(transformations.toList())
/**
* Set the list of [Transformation]s to be applied to this request.
*/
fun transformations(transformations: List<Transformation>) = apply {
this.transformations = transformations.toImmutableList()
}
/**
* @see ImageLoader.Builder.bitmapConfig
*/
fun bitmapConfig(config: Bitmap.Config) = apply {
this.bitmapConfig = config
}
/**
* Set the preferred [ColorSpace].
*
* This is not guaranteed and a different color space may be used in some situations.
*/
@RequiresApi(26)
fun colorSpace(colorSpace: ColorSpace) = apply {
this.colorSpace = colorSpace
}
/**
* Set the requested width/height.
*/
fun size(@Px size: Int) = size(size, size)
/**
* Set the requested width/height.
*/
fun size(@Px width: Int, @Px height: Int) = size(Size(width, height))
/**
* Set the requested width/height.
*/
fun size(width: Dimension, height: Dimension) = size(Size(width, height))
/**
* Set the requested width/height.
*/
fun size(size: Size) = size(SizeResolver(size))
/**
* Set the [SizeResolver] to resolve the requested width/height.
*/
fun size(resolver: SizeResolver) = apply {
this.sizeResolver = resolver
resetResolvedValues()
}
/**
* Set the scaling algorithm that will be used to fit/fill the image into the size provided
* by [sizeResolver].
*
* NOTE: If [scale] is not set, it is automatically computed for [ImageView] targets.
*/
fun scale(scale: Scale) = apply {
this.scale = scale
}
/**
* Set the precision for the size of the loaded image.
*
* The default value is [Precision.AUTOMATIC], which uses the logic in [allowInexactSize]
* to determine if output image's dimensions must match the input [size] and [scale] exactly.
*
* NOTE: If [size] is [Size.ORIGINAL], the returned image's size will always be equal to or
* greater than the image's original size.
*
* @see Precision
*/
fun precision(precision: Precision) = apply {
this.precision = precision
}
/**
* Use [factory] to handle fetching any image data.
*
* If this is null or is not set the [ImageLoader] will find an applicable fetcher in its
* [ComponentRegistry].
*/
inline fun <reified T : Any> fetcherFactory(factory: Fetcher.Factory<T>) =
fetcherFactory(factory, T::class.java)
/**
* Use [factory] to handle fetching any image data.
*
* If this is null or is not set the [ImageLoader] will find an applicable fetcher in its
* [ComponentRegistry].
*/
fun <T : Any> fetcherFactory(factory: Fetcher.Factory<T>, type: Class<T>) = apply {
this.fetcherFactory = factory to type
}
/**
* Use [factory] to handle decoding any image data.
*
* If this is null or is not set the [ImageLoader] will find an applicable decoder in its
* [ComponentRegistry].
*/
fun decoderFactory(factory: Decoder.Factory) = apply {
this.decoderFactory = factory
}
/**
* Allow converting the result drawable to a bitmap to apply any [transformations].
*
* If false and the result drawable is not a [BitmapDrawable] any [transformations] will
* be ignored.
*/
fun allowConversionToBitmap(enable: Boolean) = apply {
this.allowConversionToBitmap = enable
}
/**
* @see ImageLoader.Builder.allowHardware
*/
fun allowHardware(enable: Boolean) = apply {
this.allowHardware = enable
}
/**
* @see ImageLoader.Builder.allowRgb565
*/
fun allowRgb565(enable: Boolean) = apply {
this.allowRgb565 = enable
}
/**
* Enable/disable pre-multiplication of the color (RGB) channels of the decoded image by
* the alpha channel.
*
* The default behavior is to enable pre-multiplication but in some environments it can be
* necessary to disable this feature to leave the source pixels unmodified.
*/
fun premultipliedAlpha(enable: Boolean) = apply {
this.premultipliedAlpha = enable
}
/**
* Enable/disable reading/writing from/to the memory cache.
*/
fun memoryCachePolicy(policy: CachePolicy) = apply {
this.memoryCachePolicy = policy
}
/**
* Enable/disable reading/writing from/to the disk cache.
*/
fun diskCachePolicy(policy: CachePolicy) = apply {
this.diskCachePolicy = policy
}
/**
* Enable/disable reading from the network.
*
* NOTE: Disabling writes has no effect.
*/
fun networkCachePolicy(policy: CachePolicy) = apply {
this.networkCachePolicy = policy
}
/**
* Set the [Headers] for any network operations performed by this request.
*/
fun headers(headers: Headers) = apply {
this.headers = headers.newBuilder()
}
/**
* Add a header for any network operations performed by this request.
*
* @see Headers.Builder.add
*/
fun addHeader(name: String, value: String) = apply {
(this.headers ?: Headers.Builder().also { this.headers = it }).add(name, value)
}
/**
* Set a header for any network operations performed by this request.
*
* @see Headers.Builder.set
*/
fun setHeader(name: String, value: String) = apply {
(this.headers ?: Headers.Builder().also { this.headers = it })[name] = value
}
/**
* Remove all network headers with the key [name].
*/
fun removeHeader(name: String) = apply {
this.headers?.removeAll(name)
}
/**
* Attach [tag] to this request using [T] as the key.
*/
inline fun <reified T : Any> tag(tag: T?) = tag(T::class.java, tag)
/**
* Attach [tag] to this request using [type] as the key.
*/
fun <T : Any> tag(type: Class<in T>, tag: T?) = apply {
if (tag == null) {
this.tags?.remove(type)
} else {
val tags = this.tags ?: mutableMapOf<Class<*>, Any>().also { this.tags = it }
tags[type] = type.cast(tag)!!
}
}
/**
* Set the tags for this request.
*/
fun tags(tags: Tags) = apply {
this.tags = tags.asMap().toMutableMap()
}
/**
* Set the memory cache [key] whose value will be used as the placeholder drawable.
*
* If there is no value in the memory cache for [key], fall back to [placeholder].
*/
fun placeholderMemoryCacheKey(key: String?) =
placeholderMemoryCacheKey(key?.let { MemoryCache.Key(it) })
/**
* Set the memory cache [key] whose value will be used as the placeholder drawable.
*
* If there is no value in the memory cache for [key], fall back to [placeholder].
*/
fun placeholderMemoryCacheKey(key: MemoryCache.Key?) = apply {
this.placeholderMemoryCacheKey = key
}
/**
* Set the placeholder drawable to use when the request starts.
*/
fun placeholder(@DrawableRes drawableResId: Int) = apply {
this.placeholderResId = drawableResId
this.placeholderDrawable = null
}
/**
* Set the placeholder drawable to use when the request starts.
*/
fun placeholder(drawable: Drawable?) = apply {
this.placeholderDrawable = drawable
this.placeholderResId = 0
}
/**
* Set the error drawable to use if the request fails.
*/
fun error(@DrawableRes drawableResId: Int) = apply {
this.errorResId = drawableResId
this.errorDrawable = null
}
/**
* Set the error drawable to use if the request fails.
*/
fun error(drawable: Drawable?) = apply {
this.errorDrawable = drawable
this.errorResId = 0
}
/**
* Set the fallback drawable to use if [data] is null.
*/
fun fallback(@DrawableRes drawableResId: Int) = apply {
this.fallbackResId = drawableResId
this.fallbackDrawable = null
}
/**
* Set the fallback drawable to use if [data] is null.
*/
fun fallback(drawable: Drawable?) = apply {
this.fallbackDrawable = drawable
this.fallbackResId = 0
}
/**
* Convenience function to set [imageView] as the [Target].
*/
fun target(imageView: ImageView) = target(ImageViewTarget(imageView))
/**
* Convenience function to create and set the [Target].
*/
inline fun target(
crossinline onStart: (placeholder: Drawable?) -> Unit = {},
crossinline onError: (error: Drawable?) -> Unit = {},
crossinline onSuccess: (result: Drawable) -> Unit = {}
) = target(object : Target {
override fun onStart(placeholder: Drawable?) = onStart(placeholder)
override fun onError(error: Drawable?) = onError(error)
override fun onSuccess(result: Drawable) = onSuccess(result)
})
/**
* Set the [Target].
*/
fun target(target: Target?) = apply {
this.target = target
resetResolvedValues()
}
/**
* @see ImageLoader.Builder.crossfade
*/
fun crossfade(enable: Boolean) =
crossfade(if (enable) CrossfadeDrawable.DEFAULT_DURATION else 0)
/**
* @see ImageLoader.Builder.crossfade
*/
fun crossfade(durationMillis: Int) = apply {
val factory = if (durationMillis > 0) {
CrossfadeTransition.Factory(durationMillis)
} else {
Transition.Factory.NONE
}
transitionFactory(factory)
}
/**
* @see ImageLoader.Builder.transitionFactory
*/
fun transitionFactory(transition: Transition.Factory) = apply {
this.transitionFactory = transition
}
/**
* Set the [Lifecycle] for this request.
*/
fun lifecycle(owner: LifecycleOwner?) = lifecycle(owner?.lifecycle)
/**
* Set the [Lifecycle] for this request.
*
* Requests are queued while the lifecycle is not at least [Lifecycle.State.STARTED].
* Requests are cancelled when the lifecycle reaches [Lifecycle.State.DESTROYED].
*
* If this is null or is not set the [ImageLoader] will attempt to find the lifecycle
* for this request through its [context].
*/
fun lifecycle(lifecycle: Lifecycle?) = apply {
this.lifecycle = lifecycle
}
/**
* Set a parameter for this request.
*
* @see Parameters.Builder.set
*/
@JvmOverloads
fun setParameter(key: String, value: Any?, memoryCacheKey: String? = value?.toString()) = apply {
val parameters = this.parameters ?: Parameters.Builder().also { this.parameters = it }
parameters.set(key, value, memoryCacheKey)
}
/**
* Remove a parameter from this request.
*
* @see Parameters.Builder.remove
*/
fun removeParameter(key: String) = apply {
this.parameters?.remove(key)
}
/**
* Set the parameters for this request.
*/
fun parameters(parameters: Parameters) = apply {
this.parameters = parameters.newBuilder()
}
/**
* Set the defaults for any unset request values.
*/
fun defaults(defaults: DefaultRequestOptions) = apply {
this.defaults = defaults
resetResolvedScale()
}
/**
* Create a new [ImageRequest].
*/
fun build(): ImageRequest {
return ImageRequest(
context = context,
data = data ?: NullRequestData,
target = target,
listener = listener,
memoryCacheKey = memoryCacheKey,
diskCacheKey = diskCacheKey,
bitmapConfig = bitmapConfig ?: defaults.bitmapConfig,
colorSpace = colorSpace,
precision = precision ?: defaults.precision,
fetcherFactory = fetcherFactory,
decoderFactory = decoderFactory,
transformations = transformations,
transitionFactory = transitionFactory ?: defaults.transitionFactory,
headers = headers?.build().orEmpty(),
tags = tags?.let(Tags::from).orEmpty(),
allowConversionToBitmap = allowConversionToBitmap,
allowHardware = allowHardware ?: defaults.allowHardware,
allowRgb565 = allowRgb565 ?: defaults.allowRgb565,
premultipliedAlpha = premultipliedAlpha,
memoryCachePolicy = memoryCachePolicy ?: defaults.memoryCachePolicy,
diskCachePolicy = diskCachePolicy ?: defaults.diskCachePolicy,
networkCachePolicy = networkCachePolicy ?: defaults.networkCachePolicy,
interceptorDispatcher = interceptorDispatcher ?: defaults.interceptorDispatcher,
fetcherDispatcher = fetcherDispatcher ?: defaults.fetcherDispatcher,
decoderDispatcher = decoderDispatcher ?: defaults.decoderDispatcher,
transformationDispatcher = transformationDispatcher ?: defaults.transformationDispatcher,
lifecycle = lifecycle ?: resolvedLifecycle ?: resolveLifecycle(),
sizeResolver = sizeResolver ?: resolvedSizeResolver ?: resolveSizeResolver(),
scale = scale ?: resolvedScale ?: resolveScale(),
parameters = parameters?.build().orEmpty(),
placeholderMemoryCacheKey = placeholderMemoryCacheKey,
placeholderResId = placeholderResId,
placeholderDrawable = placeholderDrawable,
errorResId = errorResId,
errorDrawable = errorDrawable,
fallbackResId = fallbackResId,
fallbackDrawable = fallbackDrawable,
defined = DefinedRequestOptions(lifecycle, sizeResolver, scale,
interceptorDispatcher, fetcherDispatcher, decoderDispatcher,
transformationDispatcher, transitionFactory, precision, bitmapConfig,
allowHardware, allowRgb565, memoryCachePolicy, diskCachePolicy,
networkCachePolicy),
defaults = defaults,
)
}
/** Ensure these values will be recomputed when [build] is called. */
private fun resetResolvedValues() {
resolvedLifecycle = null
resolvedSizeResolver = null
resolvedScale = null
}
/** Ensure the scale will be recomputed when [build] is called. */
private fun resetResolvedScale() {
resolvedScale = null