DataFetcherGenerator
數(shù)據(jù)提取器生成器,雖然名字是這樣叫,但是實際上在實現(xiàn)類你是看不到它生成數(shù)據(jù)提取器的。它只有兩個方法逝段,有三個類實現(xiàn)了它,分別為 ResourceCacheGenerator割捅、DataCacheGenerator奶躯、SourceGenerator。
interface DataFetcherGenerator {
/**
* 數(shù)據(jù)提取器執(zhí)行工作則返回true亿驾,否則返回false
*/
boolean startNext();
/**
* 取消數(shù)據(jù)提取器的執(zhí)行
*/
void cancel();
}
ResourceCacheGenerator
資源緩存生成器嘹黔,主要是從磁盤緩存中獲取經(jīng)過轉(zhuǎn)化過的資源。因為磁盤緩存不僅可以緩存原圖莫瞬,也可以緩存轉(zhuǎn)化過的圖片儡蔓,原圖的獲取則是由 DataCacheGenerator 實現(xiàn),由于 DataCacheGenerator 的獲取和這個類差不多就不再另寫一篇了疼邀。
首先會去磁盤緩存中獲取圖片喂江,如果有則獲取 File 類型的 ModelLoader ,并由它生成對應(yīng)的 LoadData 旁振, LoadData 又包含了 DataFetcher 获询,最終的數(shù)據(jù)提取操作就交給它。
該類使用的數(shù)據(jù)大多數(shù)由DecodeHelper提供拐袜,要是不熟悉的可以看下 Glide 源碼解析之 DecodeHelper
class ResourceCacheGenerator implements DataFetcherGenerator,
DataFetcher.DataCallback<Object> {
private final FetcherReadyCallback cb;
private final DecodeHelper<?> helper;
private int sourceIdIndex;
private int resourceClassIndex = -1;
private Key sourceKey;
private List<ModelLoader<File, ?>> modelLoaders; //默認(rèn)為 null
@Override
public boolean startNext() {
List<Key> sourceIds = helper.getCacheKeys(); //至少會有一個 GlideUrl 的 key
if (sourceIds.isEmpty()) {
return false;
}
List<Class<?>> resourceClasses = helper.getRegisteredResourceClasses();
if (resourceClasses.isEmpty()) {
// helper.getTranscodeClass() 是 Drawable.class
if (File.class.equals(helper.getTranscodeClass())) {
return false;
}
throw new IllegalStateException(
"Failed to find any load path from " + helper.getModelClass() + " to "
+ helper.getTranscodeClass());
}
//一開始 modelLoaders 是null的吉嚣,所以會進入循環(huán)
while (modelLoaders == null || !hasNextModelLoader()) {
resourceClassIndex++;
if (resourceClassIndex >= resourceClasses.size()) {
sourceIdIndex++;
if (sourceIdIndex >= sourceIds.size()) {
return false;
}
resourceClassIndex = 0;
}
Key sourceId = sourceIds.get(sourceIdIndex);
Class<?> resourceClass = resourceClasses.get(resourceClassIndex);
Transformation<?> transformation = helper.getTransformation(resourceClass); // DrawableTransformation
//根據(jù)當(dāng)前配置生成一個 key
currentKey =
new ResourceCacheKey(
helper.getArrayPool(),
sourceId,
helper.getSignature(),
helper.getWidth(),
helper.getHeight(),
transformation,
resourceClass,
helper.getOptions());
//獲取磁盤緩存文件
cacheFile = helper.getDiskCache().get(currentKey);
if (cacheFile != null) {
sourceKey = sourceId;
//獲取 File 類型的 ModelLoaders ,有 ByteBufferFileLoader蹬铺、FileLoader尝哆、UnitModelLoader
modelLoaders = helper.getModelLoaders(cacheFile);
modelLoaderIndex = 0;
}
}
loadData = null;
boolean started = false;
//上面對 modelLoaders 進行了賦值,所以會進入循環(huán)
while (!started && hasNextModelLoader()) {
ModelLoader<File, ?> modelLoader = modelLoaders.get(modelLoaderIndex++);
//第一次循環(huán)由 ByteBufferFileLoader 生成的 LoadData 為 LoadData<>(new ObjectKey(file), new ByteBufferFetcher(file))
loadData = modelLoader.buildLoadData(cacheFile,
helper.getWidth(), helper.getHeight(), helper.getOptions());
if (loadData != null && helper.hasLoadPath(loadData.fetcher.getDataClass())) {
started = true; //結(jié)束循環(huán)的標(biāo)志
//所以這里調(diào)用的是 ByteBufferFetcher
loadData.fetcher.loadData(helper.getPriority(), this);
}
}
return started;
}
}
DataFetcher 的生成
首先對應(yīng) File 類型的 ModelLoader 有幾個甜攀,這里我們只看第一個 ByteBufferFileLoader 秋泄,它由 ByteBufferFileLoader 的內(nèi)部類 Factory 用工廠模式生成。接著又會調(diào)用它的 buildLoadData 方法生成參數(shù)為 ObjectKey 和 ByteBufferFetcher 的 LoadData 赴邻,所以上面最終調(diào)用的 DataFetcher 為 ByteBufferFetcher 印衔。
// ModelLoader 是由 Factory 去 builde 出來的
Glide(){
registry
.append(File.class, ByteBuffer.class, new ByteBufferFileLoader.Factory())
.append(File.class, InputStream.class, new FileLoader.StreamFactory())
.append(File.class, ParcelFileDescriptor.class, new FileLoader.FileDescriptorFactory())
.append(File.class, File.class, UnitModelLoader.Factory.<File>getInstance())
}
// ByteBufferFileLoader.Factory()
public static class Factory implements ModelLoaderFactory<File, ByteBuffer> {
@NonNull
@Override
public ModelLoader<File, ByteBuffer> build(@NonNull MultiModelLoaderFactory multiFactory) {
return new ByteBufferFileLoader();
}
}
public class ByteBufferFileLoader implements ModelLoader<File, ByteBuffer> {
@Override
public LoadData<ByteBuffer> buildLoadData(@NonNull File file, int width, int height,
@NonNull Options options) {
return new LoadData<>(new ObjectKey(file), new ByteBufferFetcher(file));
}
}
資源的提取
在 LoadData() 中調(diào)用了 ByteBufferUtil.fromFile(file) 啡捶,里面使用 NIO 的類 FileChannel 以只讀的形式進行內(nèi)存映射姥敛,這樣能加速讀取的速度。
最后就會把結(jié)果回調(diào)給 callback 了瞎暑,這個 callback 是由 ResourceCacheGenerator 來實現(xiàn)的彤敛,也就是加載完后會通知到 ResourceCacheGenerator 与帆。
private static final class ByteBufferFetcher implements DataFetcher<ByteBuffer> {
private final File file;
@Synthetic
@SuppressWarnings("WeakerAccess")
ByteBufferFetcher(File file) {
this.file = file;
}
@Override
public void loadData(@NonNull Priority priority,
@NonNull DataCallback<? super ByteBuffer> callback) {
ByteBuffer result;
try {
result = ByteBufferUtil.fromFile(file);
} catch (IOException e) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Failed to obtain ByteBuffer for file", e);
}
callback.onLoadFailed(e);
return;
}
callback.onDataReady(result);
}
}
//ByteBufferUtil
@NonNull
public static ByteBuffer fromFile(@NonNull File file) throws IOException {
RandomAccessFile raf = null;
FileChannel channel = null;
try {
long fileLength = file.length();
if (fileLength > Integer.MAX_VALUE) {
throw new IOException("File too large to map into memory");
}
if (fileLength == 0) {
throw new IOException("File unsuitable for memory mapping");
}
raf = new RandomAccessFile(file, "r");
channel = raf.getChannel();
return channel.map(FileChannel.MapMode.READ_ONLY, 0, fileLength).load();
} finally {
if (channel != null) {
try {
channel.close();
} catch (IOException e) {
// Ignored.
}
}
if (raf != null) {
try {
raf.close();
} catch (IOException e) {
// Ignored.
}
}
}
}
資源加載完成
在 ResourceCacheGenerator 的回調(diào)中實際上調(diào)用的是 DecodeJob 實現(xiàn)的 FetcherReadyCallback 接口,這樣資源最終會交給 DecodeJob 來處理墨榄。
@Override
public void onDataReady(Object data) {
cb.onDataFetcherReady(sourceKey, data, loadData.fetcher, DataSource.RESOURCE_DISK_CACHE,
currentKey);
}