-
Notifications
You must be signed in to change notification settings - Fork 637
/
RealImageLoader.kt
287 lines (260 loc) · 10.3 KB
/
RealImageLoader.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
package coil
import android.content.Context
import android.util.Log
import androidx.annotation.MainThread
import coil.decode.BitmapFactoryDecoder
import coil.disk.DiskCache
import coil.fetch.AssetUriFetcher
import coil.fetch.BitmapFetcher
import coil.fetch.ByteBufferFetcher
import coil.fetch.ContentUriFetcher
import coil.fetch.DrawableFetcher
import coil.fetch.FileFetcher
import coil.fetch.HttpUriFetcher
import coil.fetch.ResourceUriFetcher
import coil.intercept.EngineInterceptor
import coil.intercept.RealInterceptorChain
import coil.key.FileKeyer
import coil.key.UriKeyer
import coil.map.ByteArrayMapper
import coil.map.FileUriMapper
import coil.map.HttpUrlMapper
import coil.map.ResourceIntMapper
import coil.map.ResourceUriMapper
import coil.map.StringMapper
import coil.memory.MemoryCache
import coil.request.DefaultRequestOptions
import coil.request.Disposable
import coil.request.ErrorResult
import coil.request.ImageRequest
import coil.request.ImageResult
import coil.request.NullRequestData
import coil.request.NullRequestDataException
import coil.request.OneShotDisposable
import coil.request.RequestService
import coil.request.SuccessResult
import coil.target.Target
import coil.target.ViewTarget
import coil.transition.NoneTransition
import coil.transition.TransitionTarget
import coil.util.Emoji
import coil.util.ImageLoaderOptions
import coil.util.Logger
import coil.util.SystemCallbacks
import coil.util.awaitStarted
import coil.util.emoji
import coil.util.get
import coil.util.log
import coil.util.requestManager
import coil.util.toDrawable
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.cancel
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.job
import kotlinx.coroutines.withContext
import okhttp3.Call
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.coroutines.coroutineContext
internal class RealImageLoader(
val context: Context,
override val defaults: DefaultRequestOptions,
val memoryCacheLazy: Lazy<MemoryCache?>,
val diskCacheLazy: Lazy<DiskCache?>,
val callFactoryLazy: Lazy<Call.Factory>,
val eventListenerFactory: EventListener.Factory,
val componentRegistry: ComponentRegistry,
val options: ImageLoaderOptions,
val logger: Logger?,
) : ImageLoader {
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate +
CoroutineExceptionHandler { _, throwable -> logger?.log(TAG, throwable) })
private val systemCallbacks = SystemCallbacks(this, context, options.networkObserverEnabled)
private val requestService = RequestService(this, systemCallbacks, logger)
override val memoryCache by memoryCacheLazy
override val diskCache by diskCacheLazy
override val components = componentRegistry.newBuilder()
// Mappers
.add(HttpUrlMapper())
.add(StringMapper())
.add(FileUriMapper())
.add(ResourceUriMapper())
.add(ResourceIntMapper())
.add(ByteArrayMapper())
// Keyers
.add(UriKeyer())
.add(FileKeyer(options.addLastModifiedToFileCacheKey))
// Fetchers
.add(HttpUriFetcher.Factory(callFactoryLazy, diskCacheLazy, options.respectCacheHeaders))
.add(FileFetcher.Factory())
.add(AssetUriFetcher.Factory())
.add(ContentUriFetcher.Factory())
.add(ResourceUriFetcher.Factory())
.add(DrawableFetcher.Factory())
.add(BitmapFetcher.Factory())
.add(ByteBufferFetcher.Factory())
// Decoders
.add(BitmapFactoryDecoder.Factory(options.bitmapFactoryMaxParallelism))
.build()
private val interceptors = components.interceptors +
EngineInterceptor(this, requestService, logger)
private val isShutdown = AtomicBoolean(false)
override fun enqueue(request: ImageRequest): Disposable {
// Start executing the request on the main thread.
val job = scope.async {
executeMain(request, REQUEST_TYPE_ENQUEUE).also { result ->
if (result is ErrorResult) logger?.log(TAG, result.throwable)
}
}
// Update the current request attached to the view and return a new disposable.
return if (request.target is ViewTarget<*>) {
request.target.view.requestManager.getDisposable(job)
} else {
OneShotDisposable(job)
}
}
override suspend fun execute(request: ImageRequest) = coroutineScope {
// Start executing the request on the main thread.
val job = async(Dispatchers.Main.immediate) {
executeMain(request, REQUEST_TYPE_EXECUTE)
}
// Update the current request attached to the view and await the result.
if (request.target is ViewTarget<*>) {
request.target.view.requestManager.getDisposable(job)
}
return@coroutineScope job.await()
}
@MainThread
private suspend fun executeMain(initialRequest: ImageRequest, type: Int): ImageResult {
// Wrap the request to manage its lifecycle.
val requestDelegate = requestService.requestDelegate(initialRequest, coroutineContext.job)
.apply { assertActive() }
// Apply this image loader's defaults to this request.
val request = initialRequest.newBuilder().defaults(defaults).build()
// Create a new event listener.
val eventListener = eventListenerFactory.create(request)
try {
// Fail before starting if data is null.
if (request.data == NullRequestData) throw NullRequestDataException()
// Set up the request's lifecycle observers.
requestDelegate.start()
// Enqueued requests suspend until the lifecycle is started.
if (type == REQUEST_TYPE_ENQUEUE) request.lifecycle.awaitStarted()
// Set the placeholder on the target.
val placeholderBitmap = memoryCache?.get(request.placeholderMemoryCacheKey)?.bitmap
val placeholder = placeholderBitmap?.toDrawable(request.context) ?: request.placeholder
request.target?.onStart(placeholder)
eventListener.onStart(request)
request.listener?.onStart(request)
// Resolve the size.
eventListener.resolveSizeStart(request)
val size = request.sizeResolver.size()
eventListener.resolveSizeEnd(request, size)
// Execute the interceptor chain.
val result = withContext(request.interceptorDispatcher) {
RealInterceptorChain(
initialRequest = request,
interceptors = interceptors,
index = 0,
request = request,
size = size,
eventListener = eventListener,
isPlaceholderCached = placeholderBitmap != null
).proceed(request)
}
// Set the result on the target.
when (result) {
is SuccessResult -> onSuccess(result, request.target, eventListener)
is ErrorResult -> onError(result, request.target, eventListener)
}
return result
} catch (throwable: Throwable) {
if (throwable is CancellationException) {
onCancel(request, eventListener)
throw throwable
} else {
// Create the default error result if there's an uncaught exception.
val result = requestService.errorResult(request, throwable)
onError(result, request.target, eventListener)
return result
}
} finally {
requestDelegate.complete()
}
}
/** Called by [SystemCallbacks.onTrimMemory]. */
@Suppress("SAFE_CALL_WILL_CHANGE_NULLABILITY", "UNNECESSARY_SAFE_CALL")
internal fun onTrimMemory(level: Int) {
// https://github.com/coil-kt/coil/issues/1211
memoryCacheLazy?.value?.trimMemory(level)
}
override fun shutdown() {
if (isShutdown.getAndSet(true)) return
scope.cancel()
systemCallbacks.shutdown()
memoryCache?.clear()
}
override fun newBuilder() = ImageLoader.Builder(this)
private fun onSuccess(
result: SuccessResult,
target: Target?,
eventListener: EventListener
) {
val request = result.request
val dataSource = result.dataSource
logger?.log(TAG, Log.INFO) {
"${dataSource.emoji} Successful (${dataSource.name}) - ${request.data}"
}
transition(result, target, eventListener) { target?.onSuccess(result.drawable) }
eventListener.onSuccess(request, result)
request.listener?.onSuccess(request, result)
}
private fun onError(
result: ErrorResult,
target: Target?,
eventListener: EventListener
) {
val request = result.request
logger?.log(TAG, Log.INFO) {
"${Emoji.SIREN} Failed - ${request.data} - ${result.throwable}"
}
transition(result, target, eventListener) { target?.onError(result.drawable) }
eventListener.onError(request, result)
request.listener?.onError(request, result)
}
private fun onCancel(request: ImageRequest, eventListener: EventListener) {
logger?.log(TAG, Log.INFO) {
"${Emoji.CONSTRUCTION} Cancelled - ${request.data}"
}
eventListener.onCancel(request)
request.listener?.onCancel(request)
}
private inline fun transition(
result: ImageResult,
target: Target?,
eventListener: EventListener,
setDrawable: () -> Unit
) {
if (target !is TransitionTarget) {
setDrawable()
return
}
val transition = result.request.transitionFactory.create(target, result)
if (transition is NoneTransition) {
setDrawable()
return
}
eventListener.transitionStart(result.request, transition)
transition.transition()
eventListener.transitionEnd(result.request, transition)
}
companion object {
private const val TAG = "RealImageLoader"
private const val REQUEST_TYPE_ENQUEUE = 0
private const val REQUEST_TYPE_EXECUTE = 1
}
}