Glide4.x源码浅析(三)Glide流程之图片的获取

上篇文章说到了RequestBuilder创建了请求,会调用RequestManager的track方法,请求的创建的调用链很长但是跟踪下去会发现最终创建了一个SingleRequest对象

  void track(@NonNull Target target, @NonNull Request request) {
    targetTracker.track(target);
    requestTracker.runRequest(request);
  }

其中track是将请求保存起来

  public void runRequest(@NonNull Request request) {
    requests.add(request);
    if (!isPaused) {
      request.begin();
    } else {
      pendingRequests.add(request);
    }
  }

如果当前不是暂停状态则调用begin方法处理请求,如果是暂停状态则加入到pendingRequests集合中

  @Override
  public void begin() {
    assertNotCallingCallbacks();
    stateVerifier.throwIfRecycled();
    startTime = LogTime.getLogTime();
    if (model == null) {
      if (Util.isValidDimensions(overrideWidth, overrideHeight)) {
        width = overrideWidth;
        height = overrideHeight;
      }
      // Only log at more verbose log levels if the user has set a fallback drawable, because
      // fallback Drawables indicate the user expects null models occasionally.
      int logLevel = getFallbackDrawable() == null ? Log.WARN : Log.DEBUG;
      onLoadFailed(new GlideException("Received null model"), logLevel);
      return;
    }

    if (status == Status.RUNNING) {
      throw new IllegalArgumentException("Cannot restart a running request");
    }

    // If we're restarted after we're complete (usually via something like a notifyDataSetChanged
    // that starts an identical request into the same Target or View), we can simply use the
    // resource and size we retrieved the last time around and skip obtaining a new size, starting a
    // new load etc. This does mean that users who want to restart a load because they expect that
    // the view size has changed will need to explicitly clear the View or Target before starting
    // the new load.
    if (status == Status.COMPLETE) {
      onResourceReady(resource, DataSource.MEMORY_CACHE);
      return;
    }

    // Restarts for requests that are neither complete nor running can be treated as new requests
    // and can run again from the beginning.

    status = Status.WAITING_FOR_SIZE;
    if (Util.isValidDimensions(overrideWidth, overrideHeight)) {
      onSizeReady(overrideWidth, overrideHeight);
    } else {
      target.getSize(this);
    }

    if ((status == Status.RUNNING || status == Status.WAITING_FOR_SIZE)
        && canNotifyStatusChanged()) {
      target.onLoadStarted(getPlaceholderDrawable());
    }
    if (IS_VERBOSE_LOGGABLE) {
      logV("finished run method in " + LogTime.getElapsedMillis(startTime));
    }
  }

根据请求的状态进行相应的处理

  • 如果传入的路径为空则抛出异常
  • 如果当前请求的状态使运行状态 同样抛出异常,请求不能重复提交
  • 如果当前请求的状态使完成状态,则直接返回相应的资源

然后将请求状态修改为WAITING_FOR_SIZE,以目标view的宽高属性传入到onSizeReady中,修改状态值为RUNNING然后调用Engine.load对请求进行处理

  @Override
  public void onSizeReady(int width, int height) {
    stateVerifier.throwIfRecycled();
    if (IS_VERBOSE_LOGGABLE) {
      logV("Got onSizeReady in " + LogTime.getElapsedMillis(startTime));
    }
    if (status != Status.WAITING_FOR_SIZE) {
      return;
    }
    status = Status.RUNNING;

    float sizeMultiplier = requestOptions.getSizeMultiplier();
    this.width = maybeApplySizeMultiplier(width, sizeMultiplier);
    this.height = maybeApplySizeMultiplier(height, sizeMultiplier);

    if (IS_VERBOSE_LOGGABLE) {
      logV("finished setup for calling load in " + LogTime.getElapsedMillis(startTime));
    }
    loadStatus = engine.load(
        glideContext,
        model,
        requestOptions.getSignature(),
        this.width,
        this.height,
        requestOptions.getResourceClass(),
        transcodeClass,
        priority,
        requestOptions.getDiskCacheStrategy(),
        requestOptions.getTransformations(),
        requestOptions.isTransformationRequired(),
        requestOptions.isScaleOnlyOrNoTransform(),
        requestOptions.getOptions(),
        requestOptions.isMemoryCacheable(),
        requestOptions.getUseUnlimitedSourceGeneratorsPool(),
        requestOptions.getUseAnimationPool(),
        requestOptions.getOnlyRetrieveFromCache(),
        this);

    // This is a hack that's only useful for testing right now where loads complete synchronously
    // even though under any executor running on any thread but the main thread, the load would
    // have completed asynchronously.
    if (status != Status.RUNNING) {
      loadStatus = null;
    }
    if (IS_VERBOSE_LOGGABLE) {
      logV("finished onSizeReady in " + LogTime.getElapsedMillis(startTime));
    }
  }

额外补充一些,SingleRequest实现了上面的几个接口

  • SizeReadyCallback 里面只有一个onSizeReady方法,上面我们已经说过了,这个方法对于SingleReuqest的意义可以说请求的开始
  • ResourceCallBack 里面有两个方法 void onResourceReady(Resource resource, DataSource dataSource) void onLoadFailed(GlideException e) 从字面也可以看出是请求成功的回调,拿到资源之后对资源的解码都是在这个方法的逻辑里面
public final class SingleRequest implements Request,
    SizeReadyCallback,
    ResourceCallback,
    FactoryPools.Poolable

来看load方法
Engine#load():

  public  LoadStatus load(
      GlideContext glideContext,
      Object model,
      Key signature,
      int width,
      int height,
      Class resourceClass,
      Class transcodeClass,
      Priority priority,
      DiskCacheStrategy diskCacheStrategy,
      Map, Transformation> transformations,
      boolean isTransformationRequired,
      boolean isScaleOnlyOrNoTransform,
      Options options,
      boolean isMemoryCacheable,
      boolean useUnlimitedSourceExecutorPool,
      boolean useAnimationPool,
      boolean onlyRetrieveFromCache,
      ResourceCallback cb) {
    Util.assertMainThread();
    long startTime = LogTime.getLogTime();

    EngineKey key = keyFactory.buildKey(model, signature, width, height, transformations,
        resourceClass, transcodeClass, options);

    EngineResource active = loadFromActiveResources(key, isMemoryCacheable);
    if (active != null) {
      cb.onResourceReady(active, DataSource.MEMORY_CACHE);
      if (Log.isLoggable(TAG, Log.VERBOSE)) {
        logWithTimeAndKey("Loaded resource from active resources", startTime, key);
      }
      return null;
    }

    EngineResource cached = loadFromCache(key, isMemoryCacheable);
    if (cached != null) {
      cb.onResourceReady(cached, DataSource.MEMORY_CACHE);
      if (Log.isLoggable(TAG, Log.VERBOSE)) {
        logWithTimeAndKey("Loaded resource from cache", startTime, key);
      }
      return null;
    }

    EngineJob current = jobs.get(key, onlyRetrieveFromCache);
    if (current != null) {
      current.addCallback(cb);
      if (Log.isLoggable(TAG, Log.VERBOSE)) {
        logWithTimeAndKey("Added to existing load", startTime, key);
      }
      return new LoadStatus(cb, current);
    }

    EngineJob engineJob =
        engineJobFactory.build(
            key,
            isMemoryCacheable,
            useUnlimitedSourceExecutorPool,
            useAnimationPool,
            onlyRetrieveFromCache);

    DecodeJob decodeJob =
        decodeJobFactory.build(
            glideContext,
            model,
            key,
            signature,
            width,
            height,
            resourceClass,
            transcodeClass,
            priority,
            diskCacheStrategy,
            transformations,
            isTransformationRequired,
            isScaleOnlyOrNoTransform,
            onlyRetrieveFromCache,
            options,
            engineJob);

    jobs.put(key, engineJob);

    engineJob.addCallback(cb);
    engineJob.start(decodeJob);

    if (Log.isLoggable(TAG, Log.VERBOSE)) {
      logWithTimeAndKey("Started new load", startTime, key);
    }
    return new LoadStatus(cb, engineJob);
  }

缓存
关于缓存我会再单独开一篇来说,前几篇仅仅是以Glie的流程为主线来说的
首先根据图片源的路径指定view的宽高以及配置属性等得到一个key值,然后loadFromActiveResources首先去获取缓存中的图片资源

  @Nullable
  private EngineResource loadFromActiveResources(Key key, boolean isMemoryCacheable) {
    if (!isMemoryCacheable) {
      return null;
    }
    EngineResource active = activeResources.get(key);
    if (active != null) {
      active.acquire();
    }
    return active;
  }

activeResources中维护着一个HashMap,key为前面我们得的key,value为一个弱引用,里面有我们的图片资源,通过get获取到资源,如果不为空,调用acquire对对象的引用数量进行加一操作,内存缓存是通过计数散列算法来进行相应的操作的,如果对象的计数树为0,则说明暂无其他对象引用此资源,那么此资源可以被释放了,如果不为>0 则说明还有其他对象引用此资源,那么就不释放此资源,这样的话就可以保证图片资源在Lru中不存在但是需要引用的情况。最后通过ResourceCallback.onResourceReady将图片返回回去,这里的cb即SingleRequest
如果activeResources中没有,那么通过Lru进行获取


  private EngineResource loadFromCache(Key key, boolean isMemoryCacheable) {
    if (!isMemoryCacheable) {
      return null;
    }

    EngineResource cached = getEngineResourceFromCache(key);
    if (cached != null) {
      cached.acquire();
      activeResources.activate(key, cached);
    }
    return cached;
  }

  private EngineResource getEngineResourceFromCache(Key key) {
    Resource cached = cache.remove(key);

    final EngineResource result;
    if (cached == null) {
      result = null;
    } else if (cached instanceof EngineResource) {
      // Save an object allocation if we've cached an EngineResource (the typical case).
      result = (EngineResource) cached;
    } else {
      result = new EngineResource<>(cached, true /*isMemoryCacheable*/, true /*isRecyclable*/);
    }
    return result;
  }

其中的cached就是我们在GlideBuilder中进行初始化的Lru对象,下面有源码这里不再多说,
GlideBuilder#build():

    if (memoryCache == null) {
      memoryCache = new LruResourceCache(memorySizeCalculator.getMemoryCacheSize());
    }

对于Lru的数据获取是通过删除的方式来获取,并且如果获取成功的话会,放入到activiteResources中,这样的话就可以对资源再次进行缓存了,最后如果成功的话也是通过ResourceCallback.onResourceReady将图片返回回去。

最后一种则是通过Jobs根据key获取EngineJob对象,然后将自身的 EngineResource和DataSource对象传入到ResourceCallback中,Jobs中维护着一个Map集合,Key为我们图片的key,value为EngineJob,onlyRetrieveFromCache默认为true,可以在RequestQoptions中设置。Jobs则是在Engine创建的时候新创建的。如果集合中有EngineJob对象,那么新建一个LoadStatus并返回,如果没有,那就新建一个EngineJob对象以及DecodeJob对象,并将新建的EngineJob加入大Jobs中,然后返回
最后调用EngineJob.Start()开启线程获取图片

  public void start(DecodeJob decodeJob) {
    this.decodeJob = decodeJob;
    GlideExecutor executor = decodeJob.willDecodeFromCache()
        ? diskCacheExecutor
        : getActiveSourceExecutor();
    executor.execute(decodeJob);
  }

首先判断是否需要磁盘缓存,是则使用磁盘线程池,否则使用内存缓存线程池

  boolean willDecodeFromCache() {
    Stage firstStage = getNextStage(Stage.INITIALIZE);
    return firstStage == Stage.RESOURCE_CACHE || firstStage == Stage.DATA_CACHE;
  }
  
  private Stage getNextStage(Stage current) {
    switch (current) {
      case INITIALIZE:
        return diskCacheStrategy.decodeCachedResource()
            ? Stage.RESOURCE_CACHE : getNextStage(Stage.RESOURCE_CACHE);
      case RESOURCE_CACHE:
        return diskCacheStrategy.decodeCachedData()
            ? Stage.DATA_CACHE : getNextStage(Stage.DATA_CACHE);
      case DATA_CACHE:
        // Skip loading from source if the user opted to only retrieve the resource from cache.
        return onlyRetrieveFromCache ? Stage.FINISHED : Stage.SOURCE;
      case SOURCE:
      case FINISHED:
        return Stage.FINISHED;
      default:
        throw new IllegalArgumentException("Unrecognized stage: " + current);
    }
  }  

diskCacheStrategy是在ReuqestOption中设置的,对应

  public static final DiskCacheStrategy AUTOMATIC = new DiskCacheStrategy() {
    @Override
    public boolean isDataCacheable(DataSource dataSource) {
      return dataSource == DataSource.REMOTE;
    }

    @Override
    public boolean isResourceCacheable(boolean isFromAlternateCacheKey, DataSource dataSource,
        EncodeStrategy encodeStrategy) {
      return ((isFromAlternateCacheKey && dataSource == DataSource.DATA_DISK_CACHE)
          || dataSource == DataSource.LOCAL)
          && encodeStrategy == EncodeStrategy.TRANSFORMED;
    }
// 是否允许几码缓存中的图片资源
    @Override
    public boolean decodeCachedResource() {
      return true;
    }

// 是否允许解码缓存中的源数据
    @Override
    public boolean decodeCachedData() {
      return true;
    }
  };

当然了 不管是磁盘缓存还是内存最终都会调用DecodeJob的run(),接着会调用runWrapped()


  private void runWrapped() {
    switch (runReason) {
      case INITIALIZE:
        stage = getNextStage(Stage.INITIALIZE);
        currentGenerator = getNextGenerator();
        runGenerators();
        break;
      case SWITCH_TO_SOURCE_SERVICE:
        runGenerators();
        break;
      case DECODE_DATA:
        decodeFromRetrievedData();
        break;
      default:
        throw new IllegalStateException("Unrecognized run reason: " + runReason);
    }
  }

runReason在初始化DecodeJob的时候设置初始为INITIALIZE,getNextStage()上面有说,最后stage则是设置为了RESOURCE_CACHE
调用getNextGenerator()返回了一个ResourceCacheGenerator对象,

  private DataFetcherGenerator getNextGenerator() {
    switch (stage) {
      case RESOURCE_CACHE:
        return new ResourceCacheGenerator(decodeHelper, this);
      case DATA_CACHE:
        return new DataCacheGenerator(decodeHelper, this);
      case SOURCE:
        return new SourceGenerator(decodeHelper, this);
      case FINISHED:
        return null;
      default:
        throw new IllegalStateException("Unrecognized stage: " + stage);
    }
  }

注意实例化ResourceCacheGenerator第二个参数,是DecodeJob本身,而DecodeJob本身实现了下面几个接口,有个简单的印象就可以了

class DecodeJob implements DataFetcherGenerator.FetcherReadyCallback,
    Runnable,
    Comparable>,
    Poolable 

最后调用了runGenerators方法

 private void runGenerators() {
    currentThread = Thread.currentThread();
    startFetchTime = LogTime.getLogTime();
    boolean isStarted = false;
    while (!isCancelled && currentGenerator != null
        && !(isStarted = currentGenerator.startNext())) {
      stage = getNextStage(stage);
      currentGenerator = getNextGenerator();

      if (stage == Stage.SOURCE) {
        reschedule();
        return;
      }
    }
    // We've run out of stages and generators, give up.
    if ((stage == Stage.FINISHED || isCancelled) && !isStarted) {
      notifyFailed();
    }

    // Otherwise a generator started a new load and we expect to be called back in
    // onDataFetcherReady.
  }

while的判断条件是 请求没有被取消并且currentGenterator != null 并且要currentGenterator.startNext()返回false才可以。currentGentGenterator就是上面我们实例化的那个ResourceCacheGenerator对象。

 @Override
  public boolean startNext() {
    List sourceIds = helper.getCacheKeys();
    if (sourceIds.isEmpty()) {
      return false;
    }
    List> resourceClasses = helper.getRegisteredResourceClasses();
    if (resourceClasses.isEmpty()) {
      if (File.class.equals(helper.getTranscodeClass())) {
        return false;
      }
      throw new IllegalStateException(
          "Failed to find any load path from " + helper.getModelClass() + " to "
              + helper.getTranscodeClass());
    }
    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);
      // PMD.AvoidInstantiatingObjectsInLoops Each iteration is comparatively expensive anyway,
      // we only run until the first one succeeds, the loop runs for only a limited
      // number of iterations on the order of 10-20 in the worst case.
      currentKey =
          new ResourceCacheKey(// NOPMD AvoidInstantiatingObjectsInLoops
              helper.getArrayPool(),
              sourceId,
              helper.getSignature(),
              helper.getWidth(),
              helper.getHeight(),
              transformation,
              resourceClass,
              helper.getOptions());
      cacheFile = helper.getDiskCache().get(currentKey);
      if (cacheFile != null) {
        sourceKey = sourceId;
        modelLoaders = helper.getModelLoaders(cacheFile);
        modelLoaderIndex = 0;
      }
    }

    loadData = null;
    boolean started = false;
    while (!started && hasNextModelLoader()) {
      ModelLoader modelLoader = modelLoaders.get(modelLoaderIndex++);
      loadData = modelLoader.buildLoadData(cacheFile,
          helper.getWidth(), helper.getHeight(), helper.getOptions());
      if (loadData != null && helper.hasLoadPath(loadData.fetcher.getDataClass())) {
        started = true;
        loadData.fetcher.loadData(helper.getPriority(), this);
      }
    }

    return started;
  }

hepler为新建的DecodeHelper上面我们有说到,

  List getCacheKeys() {
    if (!isCacheKeysSet) {
      isCacheKeysSet = true;
      cacheKeys.clear();
      List> loadData = getLoadData();
      //noinspection ForLoopReplaceableByForEach to improve perf
      for (int i = 0, size = loadData.size(); i < size; i++) {
        LoadData data = loadData.get(i);
        if (!cacheKeys.contains(data.sourceKey)) {
          cacheKeys.add(data.sourceKey);
        }
        for (int j = 0; j < data.alternateKeys.size(); j++) {
          if (!cacheKeys.contains(data.alternateKeys.get(j))) {
            cacheKeys.add(data.alternateKeys.get(j));
          }
        }
      }
    }
    return cacheKeys;
  }

首次创建使用isCacheKeysSet为false,进入判断体,首先根据getLoadData()获取一个LoadData的集合。

  List> getLoadData() {
    if (!isLoadDataSet) {
      isLoadDataSet = true;
      loadData.clear();
      List> modelLoaders = glideContext.getRegistry().getModelLoaders(model);
      //noinspection ForLoopReplaceableByForEach to improve perf
      for (int i = 0, size = modelLoaders.size(); i < size; i++) {
        ModelLoader modelLoader = modelLoaders.get(i);
        LoadData current =
            modelLoader.buildLoadData(model, width, height, options);
        if (current != null) {
          loadData.add(current);
        }
      }
    }
    return loadData;
  }

这个方法先获取一个ModelLoader的集合,然后遍历集合将其中的ModelLoader取出,并调用buildLoadData方法创建一个LoadData对象 将其加入loadData集合中 并最终返回 model为图片源地址。

  @NonNull
  public synchronized  List> getModelLoaders(@NonNull A model) {
    List> modelLoaders = getModelLoadersForClass(getClass(model));
    int size = modelLoaders.size();
    List> filteredLoaders = new ArrayList<>(size);
    //noinspection ForLoopReplaceableByForEach to improve perf
    for (int i = 0; i < size; i++) {
      ModelLoader loader = modelLoaders.get(i);
      if (loader.handles(model)) {
        filteredLoaders.add(loader);
      }
    }
    return filteredLoaders;
  }

getModelLoadersForClass下面关联的代码逻辑很长,但是都很简单这里就不贴不出来,大致作用就是根据在实例化Glide对象的时候注册的ModelLoader对象集,根据图片源的类型筛选出部分ModelLoader对象集并最终返回
modelLoader.buildLoadData()这个方法在我们自定义的ModelLoader中也有一个

@GlideModule
public class OkHttpGlideModule extends AppGlideModule {
    private static final String TAG = "通讯顾问";

    @Override
    public void registerComponents(@NonNull Context context, @NonNull Glide glide, @NonNull Registry registry) {
        Log.i(TAG, "registerComponents: ");
        registry.replace(GlideUrl.class,InputStream.class,new OkHttpUrlLoader.Factory(new HTTPSUtils(context).getInstance()));
    }
}

public class OkHttpUrlLoader implements ModelLoader {

    private final Call.Factory mClient;
    @Nullable
    @Override
    public LoadData buildLoadData(@NonNull GlideUrl glideUrl, int width, int height, @NonNull Options options) {
        return new LoadData<>(glideUrl,new OkHttpStreamFetcher(mClient,glideUrl));
    }
}    

回到getCacheKeys()中,遍历得到的LoadData对象集,并将loadData所持有的key加入到cacheKeys中,其中data.alternateKeys为空,为什么来看loadData的构造器


    public LoadData(@NonNull Key sourceKey, @NonNull DataFetcher fetcher) {
      this(sourceKey, Collections.emptyList(), fetcher);
    }

    public LoadData(@NonNull Key sourceKey, @NonNull List alternateKeys,
        @NonNull DataFetcher fetcher) {
      this.sourceKey = Preconditions.checkNotNull(sourceKey);
      this.alternateKeys = Preconditions.checkNotNull(alternateKeys);
      this.fetcher = Preconditions.checkNotNull(fetcher);
    }

新建的LoadData中,alternateKeys为空,除了BaseGlideUrlLoader这个类其他的类都是没有传入alternateKeys的。所以这里也就不再多说了。sourceKey就是我们传入的图片源,所以这里的集合里面也就一个key值
回到startNext(),得到key之后,然后调用DecodeHepler.getRegisteredResourceClasses()

  List> getRegisteredResourceClasses() {
    return glideContext.getRegistry()
        .getRegisteredResourceClasses(model.getClass(), resourceClass, transcodeClass);
  }
Registry#getRegisteredResourceClasses()
  @NonNull
  public  List> getRegisteredResourceClasses(
      @NonNull Class modelClass, @NonNull Class resourceClass,
      @NonNull Class transcodeClass) {
    List> result = modelToResourceClassCache.get(modelClass, resourceClass);

    if (result == null) {
      result = new ArrayList<>();
      List> dataClasses = modelLoaderRegistry.getDataClasses(modelClass);
      for (Class dataClass : dataClasses) {
        List> registeredResourceClasses =
            decoderRegistry.getResourceClasses(dataClass, resourceClass);
        for (Class registeredResourceClass : registeredResourceClasses) {
          List> registeredTranscodeClasses = transcoderRegistry
              .getTranscodeClasses(registeredResourceClass, transcodeClass);
          if (!registeredTranscodeClasses.isEmpty() && !result.contains(registeredResourceClass)) {
            result.add(registeredResourceClass);
          }
        }
      }
      modelToResourceClassCache.put(modelClass, resourceClass,
          Collections.unmodifiableList(result));
    }

    return result;
  }  

resourceClass代表图片的源文件类型,transcodeClass代表需要转换为的图片类型
RequestManager#asBitmap():

  public RequestBuilder asBitmap() {
    return as(Bitmap.class).apply(DECODE_TYPE_BITMAP);
  }

其中as方法的入参Bitmap.class为源文件的类型,appley代表设置需要转换为的图片类型,即transcodeClass

 private static final RequestOptions DECODE_TYPE_BITMAP = decodeTypeOf(Bitmap.class).lock()
  public static RequestOptions decodeTypeOf(@NonNull Class resourceClass) {
    return new RequestOptions().decode(resourceClass);
  }
    public RequestOptions decode(@NonNull Class resourceClass) {
    if (isAutoCloneEnabled) {
      return clone().decode(resourceClass);
    }

    this.resourceClass = Preconditions.checkNotNull(resourceClass);
    fields |= RESOURCE_CLASS;
    return selfOrThrowIfLocked();
  }
 

回到getRegisteredResourceClasses(),先从集合中根据图片源的类型以及图片类型获取,如果成功获取到直接返回,如果没有获取到则进入判断方法,到此为止我们还不知这里面存的到底是什么,要获取的是什么
记得我们在初始化Glide的时候,会使用Registry通过append注册一大堆的乱七八糟的东西,

Registry#append():
  @NonNull
  public  Registry append(
      @NonNull Class modelClass, @NonNull Class dataClass,
      @NonNull ModelLoaderFactory factory) {
    modelLoaderRegistry.append(modelClass, dataClass, factory);
    return this;
  }

ModelLoaerRegistry#append():  
  public synchronized  void append(
      @NonNull Class modelClass,
      @NonNull Class dataClass,
      @NonNull ModelLoaderFactory factory) {
    multiModelLoaderFactory.append(modelClass, dataClass, factory);
    cache.clear();
  }  

multiModelLoaderFactory#append():
  synchronized  void append(
      @NonNull Class modelClass,
      @NonNull Class dataClass,
      @NonNull ModelLoaderFactory factory) {
    add(modelClass, dataClass, factory, /*append=*/ true);
  }

  private  void add(
      @NonNull Class modelClass,
      @NonNull Class dataClass,
      @NonNull ModelLoaderFactory factory,
      boolean append) {
    Entry entry = new Entry<>(modelClass, dataClass, factory);
    entries.add(append ? entries.size() : 0, entry);
  }  

上面的一长串调用链的最终形态就是将传入的图片源路径类型、图片类型、以及一个位置的工厂类封装到一个Entry中,再将这个Entry加入到集合中,为什么要说这个呢,因为这里用到了Entries.

Registry#RegisteredResourceClasses():

  @NonNull
  public  List> getRegisteredResourceClasses(
      @NonNull Class modelClass, @NonNull Class resourceClass,
      @NonNull Class transcodeClass) {
    List> result = modelToResourceClassCache.get(modelClass, resourceClass);

    if (result == null) {
      result = new ArrayList<>();
      List> dataClasses = modelLoaderRegistry.getDataClasses(modelClass);
      for (Class dataClass : dataClasses) {
        List> registeredResourceClasses =
            decoderRegistry.getResourceClasses(dataClass, resourceClass);
        for (Class registeredResourceClass : registeredResourceClasses) {
          List> registeredTranscodeClasses = transcoderRegistry
              .getTranscodeClasses(registeredResourceClass, transcodeClass);
          if (!registeredTranscodeClasses.isEmpty() && !result.contains(registeredResourceClass)) {
            result.add(registeredResourceClass);
          }
        }
      }
      modelToResourceClassCache.put(modelClass, resourceClass,
          Collections.unmodifiableList(result));
    }

    return result;
  }

这里的modelLoaderRegistry.getDataClasses(modelClass)就是根据遍历entries集合中的Entry然后对比找到与传入相同的modelClass,并返回一个图片源类型的集合
ResourceDecoderRegistry#getResourceClasses():

  @NonNull
  @SuppressWarnings("unchecked")
  public synchronized  List> getResourceClasses(@NonNull Class dataClass,
      @NonNull Class resourceClass) {
    List> result = new ArrayList<>();
    for (String bucket : bucketPriorityList) {
      List> entries = decoders.get(bucket);
      if (entries == null) {
        continue;
      }
      for (Entry entry : entries) {
        if (entry.handles(dataClass, resourceClass)
            && !result.contains((Class) entry.resourceClass)) {
          result.add((Class) entry.resourceClass);
        }
      }
    }
    return result;
  }

外部for循环的代码不用看 看里面的,这里也是遍历ectries,然后匹配与传入的图片原地址相同类型以及原图片类型相同的Entry,最后返回图片类型的集合
然后遍历这个集合,并根据源图片类型与要转换的指定类型为参,获取到指定的转换类型集合,最后加入到modelToResourceClassCache中,并返回源图片类型型集合。
回到ResourceCacheGenerator#startNext(),modelLoaders是磁盘缓存中的ModelLoader对象,下面代码下半部分有写,如果创建一个key对象,如果本地磁盘中有对应的文件,那么就根据此文件获取到modelLoaders,当然此时的modelLoaders == null,transfromation表示对图形的变换,然后通过一些属性组成一个key值,并在磁盘中尝试获取
然后下面接着会遍历modelLoaders,并通过遍历出来的ModelLoaders调用其 buildLoadData()方法 生成一个LoadData对象 ,然后调用其成员属性fetcher的loadData进行加载图片的操作

上面的操作都是基于DataFetcherGenerator的startNext()执行的,我们上面的操作都是在ResourceCacheGenerator中执行的,这个类的意义是从缓存中加载数据,而且是经过处理的图片资源缓存,如果在此类中没有找到对应的资源,会在startNext()中的第一个while循环中返回false,然后回到DecodeJob#runGenerators的判断语句中,如果返回false会执行方法体内的代码,首先得到stage的下一个状态,当前状态使RESOURCE_CACHE,下一状态就是DATA_CACHE,对应的类是DataCacheGenerator,此类的作用是从未经过处理的图片资源缓存中获取,逻辑上基本同ResourceCacheGenerator,当然如果缓存中也没有,也会返回false继续下一次的遍历,如果设置了只从缓存中读取,那么下一状态就是结束状态FINISHED,如果不只是缓存中读取那就开始联网下载获取SourceGenerator

关于buildLoadData,我们在自定义的ModelLoader中用到了,我们上面说过了 ,而loaddata.fetcher.loadata()如下


    @Override
    public void loadData(@NonNull Priority priority, @NonNull DataCallback callback) {
        Request.Builder requestBuilder = new Request.Builder().url(mGlideUrl.toStringUrl());
        for (Map.Entry headerEntry : mGlideUrl.getHeaders().entrySet()) {
            String key = headerEntry.getKey();
            requestBuilder.addHeader(key, headerEntry.getValue());
        }

        mCallback = callback;
        Request request = requestBuilder.build();
        mCall = mFactory.newCall(request);
        mCall.enqueue(this);
    }
    
        @Override
    public void onResponse(@NonNull Call call, @NonNull Response response) {
        Log.i(TAG, "onResponse: ");
        mResponseBody = response.body();
        if (response.isSuccessful()) {
            long contentLength = Preconditions.checkNotNull(mResponseBody).contentLength();
            mStream = ContentLengthInputStream.obtain(mResponseBody.byteStream(), contentLength);
            mCallback.onDataReady(mStream);
        } else {
            mCallback.onLoadFailed(new HttpException(response.message(), response.code()));
        }
    }

可以看到我们直接调用了Okhttp进行了请求,成功的话会通过CallBack.onDataReady()将资源传送回去.callBack在调用loadData的时候传递过来,也就是加载器本身。我们这里以SourceGenerator为例

  @Override
  public void onDataReady(Object data) {
    DiskCacheStrategy diskCacheStrategy = helper.getDiskCacheStrategy();
    if (data != null && diskCacheStrategy.isDataCacheable(loadData.fetcher.getDataSource())) {
      dataToCache = data;
      // We might be being called back on someone else's thread. Before doing anything, we should
      // reschedule to get back onto Glide's thread.
      cb.reschedule();
    } else {
      cb.onDataFetcherReady(loadData.sourceKey, data, loadData.fetcher,
          loadData.fetcher.getDataSource(), originalKey);
    }
  }

首先获取到磁盘加载策略,磁盘缓存有几种策略,全部缓存,只缓存原始数据,只缓存转换完毕的数据。这里判断是否缓存原始数据,如果缓存则调用cb.reschedule(),否则调用cb.onDataFetcherReady,其中cb为DecodeJob

DecodeJob#reschedule():
 @Override
  public void reschedule() {
    runReason = RunReason.SWITCH_TO_SOURCE_SERVICE;
    callback.reschedule(this);
  }

EngineJob#reschedule():
  @Override
  public void reschedule(DecodeJob job) {
    // Even if the job is cancelled here, it still needs to be scheduled so that it can clean itself
    // up.
    getActiveSourceExecutor().execute(job);
  }

callback在DecodeJob初始化的时候传入的,在Engine中初始化的,对应EngineJob,最后调用的是DecodeJob中的run(),runWarpped(),因为修改了runReason,所以直接调用runGenerators(),在之后就是进入SourceGenerator中的startNext(),此时的dataToCache不在为空,直接调用cacheData()
SourceGenerator#cacehData():

  private void cacheData(Object dataToCache) {
    long startTime = LogTime.getLogTime();
    try {
      Encoder encoder = helper.getSourceEncoder(dataToCache);
      DataCacheWriter writer =
          new DataCacheWriter<>(encoder, dataToCache, helper.getOptions());
      originalKey = new DataCacheKey(loadData.sourceKey, helper.getSignature());
      helper.getDiskCache().put(originalKey, writer);
      if (Log.isLoggable(TAG, Log.VERBOSE)) {
        Log.v(TAG, "Finished encoding source to cache"
            + ", key: " + originalKey
            + ", data: " + dataToCache
            + ", encoder: " + encoder
            + ", duration: " + LogTime.getElapsedMillis(startTime));
      }
    } finally {
      loadData.fetcher.cleanup();
    }

    sourceCacheGenerator =
        new DataCacheGenerator(Collections.singletonList(loadData.sourceKey), helper, this);
  }
 
 

中间一句helper.getDiskCache().put(originalKey, writer)则是将资源保存到了磁盘中,并为sourceCacheGenerator重新赋值,然后在runGenerators()继续遍历,调用DataCacheGenerator中的startNext(),从磁盘中读取资源,读取结果的处理跟从网络获取成功的处理大致相同
从磁盘读取完之后会调用DecodeJob.onDataFetcherReady();

  @Override
  public void onDataFetcherReady(Key sourceKey, Object data, DataFetcher fetcher,
      DataSource dataSource, Key attemptedKey) {
    this.currentSourceKey = sourceKey;
    this.currentData = data;
    this.currentFetcher = fetcher;
    this.currentDataSource = dataSource;
    this.currentAttemptingKey = attemptedKey;
    if (Thread.currentThread() != currentThread) {
      runReason = RunReason.DECODE_DATA;
      callback.reschedule(this);
    } else {
      TraceCompat.beginSection("DecodeJob.decodeFromRetrievedData");
      try {
        decodeFromRetrievedData();
      } finally {
        TraceCompat.endSection();
      }
    }
  }

上面我们储存资源到磁盘的时候进行了一次线程切换,所以这里会调用callback.reschedule(),注意runReason的值,然后最后又回到了run(),最后调用decodeFromRetrievedData

  private void decodeFromRetrievedData() {
    if (Log.isLoggable(TAG, Log.VERBOSE)) {
      logWithTimeAndKey("Retrieved data", startFetchTime,
          "data: " + currentData
              + ", cache key: " + currentSourceKey
              + ", fetcher: " + currentFetcher);
    }
    Resource resource = null;
    try {
      resource = decodeFromData(currentFetcher, currentData, currentDataSource);
    } catch (GlideException e) {
      e.setLoggingDetails(currentAttemptingKey, currentDataSource);
      throwables.add(e);
    }
    if (resource != null) {
      notifyEncodeAndRelease(resource, currentDataSource);
    } else {
      runGenerators();
    }
  }

decodeFromData就不说了,可以简单理解为解析图片


  private void notifyEncodeAndRelease(Resource resource, DataSource dataSource) {
    if (resource instanceof Initializable) {
      ((Initializable) resource).initialize();
    }

    Resource result = resource;
    LockedResource lockedResource = null;
    if (deferredEncodeManager.hasResourceToEncode()) {
      lockedResource = LockedResource.obtain(resource);
      result = lockedResource;
    }

    notifyComplete(result, dataSource);

    stage = Stage.ENCODE;
    try {
      if (deferredEncodeManager.hasResourceToEncode()) {
        deferredEncodeManager.encode(diskCacheProvider, options);
      }
    } finally {
      if (lockedResource != null) {
        lockedResource.unlock();
      }
    }
    // Call onEncodeComplete outside the finally block so that it's not called if the encode process
    // throws.
    onEncodeComplete();
  }

调用notifyComplete通知图片获取完毕


  private void notifyComplete(Resource resource, DataSource dataSource) {
    setNotifiedOrThrow();
    callback.onResourceReady(resource, dataSource);
  }

EngineJob#onResourceReady():
  @Override
  public void onResourceReady(Resource resource, DataSource dataSource) {
    this.resource = resource;
    this.dataSource = dataSource;
    MAIN_THREAD_HANDLER.obtainMessage(MSG_COMPLETE, this).sendToTarget();
  }  

发送了一条消息,最后到了handleResultOnMainThread():

  @Synthetic
  void handleResultOnMainThread() {
    stateVerifier.throwIfRecycled();
    if (isCancelled) {
      resource.recycle();
      release(false /*isRemovedFromQueue*/);
      return;
    } else if (cbs.isEmpty()) {
      throw new IllegalStateException("Received a resource without any callbacks to notify");
    } else if (hasResource) {
      throw new IllegalStateException("Already have resource");
    }
    engineResource = engineResourceFactory.build(resource, isCacheable);
    hasResource = true;

    // Hold on to resource for duration of request so we don't recycle it in the middle of
    // notifying if it synchronously released by one of the callbacks.
    engineResource.acquire();
    listener.onEngineJobComplete(this, key, engineResource);

    //noinspection ForLoopReplaceableByForEach to improve perf
    for (int i = 0, size = cbs.size(); i < size; i++) {
      ResourceCallback cb = cbs.get(i);
      if (!isInIgnoredCallbacks(cb)) {
        engineResource.acquire();
        cb.onResourceReady(engineResource, dataSource);
      }
    }
    // Our request is complete, so we can release the resource.
    engineResource.release();

    release(false /*isRemovedFromQueue*/);
  }

前面判断如果请求取消了,则释放资源,如果没有取消,注意下面,先是调用engineResource.acquired()对资源的引用加1,然后下面判断cbs的数量,每遍历一次就计数+1,因为如果同一个界面多个地方同时需要使用这张图片,每调用一次就会产生一个cb,但是最终只有一个请求执行,等到这个请求完成之后然后共同使用这张图片,遍历完之后,在调用engineResource.release()释放-1;遍历的过程中,每遍历一次便通过cb.onResourceReady()将资源传递出去 ,这里的cb为SingleRequest

  public void onResourceReady(Resource resource, DataSource dataSource) {
    stateVerifier.throwIfRecycled();
    loadStatus = null;
    if (resource == null) {
      GlideException exception = new GlideException("Expected to receive a Resource with an "
          + "object of " + transcodeClass + " inside, but instead got null.");
      onLoadFailed(exception);
      return;
    }

    Object received = resource.get();
    if (received == null || !transcodeClass.isAssignableFrom(received.getClass())) {
      releaseResource(resource);
      GlideException exception = new GlideException("Expected to receive an object of "
          + transcodeClass + " but instead" + " got "
          + (received != null ? received.getClass() : "") + "{" + received + "} inside" + " "
          + "Resource{" + resource + "}."
          + (received != null ? "" : " " + "To indicate failure return a null Resource "
          + "object, rather than a Resource object containing null data."));
      onLoadFailed(exception);
      return;
    }

    if (!canSetResource()) {
      releaseResource(resource);
      // We can't put the status to complete before asking canSetResource().
      status = Status.COMPLETE;
      return;
    }

    onResourceReady((Resource) resource, (R) received, dataSource);
  }
  
  
  private void onResourceReady(Resource resource, R result, DataSource dataSource) {
    // We must call isFirstReadyResource before setting status.
    boolean isFirstResource = isFirstReadyResource();
    status = Status.COMPLETE;
    this.resource = resource;

    if (glideContext.getLogLevel() <= Log.DEBUG) {
      Log.d(GLIDE_TAG, "Finished loading " + result.getClass().getSimpleName() + " from "
          + dataSource + " for " + model + " with size [" + width + "x" + height + "] in "
          + LogTime.getElapsedMillis(startTime) + " ms");
    }

    isCallingCallbacks = true;
    try {
      if ((requestListener == null
          || !requestListener.onResourceReady(result, model, target, dataSource, isFirstResource))
          && (targetListener == null
          || !targetListener.onResourceReady(result, model, target, dataSource, isFirstResource))) {
        Transition animation =
            animationFactory.build(dataSource, isFirstResource);
        target.onResourceReady(result, animation);
      }
    } finally {
      isCallingCallbacks = false;
    }

    notifyLoadSuccess();
  }  

主要看try-cache中的代码,如果requestListener.onResourceReady()返回了true,或是targetListener.onResourceReady()返回了true,那么target将不会去设置图片,意思也就是Glide将不会主动为我们的ImageView设置图片,如果false则可以

    Glide.with(activity)
                .load(finalPath)
                .apply(new RequestOptions().placeholder(loadingResId).error(failResId).override(width, height))
                .listener(new RequestListener() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) {
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(Drawable resource, Object model, Target target, DataSource dataSource, boolean isFirstResource) {
                        if (displayImageListener != null) {
                            displayImageListener.onSuccess(imageView, finalPath);
                        }
                        return false;
                    }
                })
                .into(imageView);

OK,到这里Glide的流程就结束了

你可能感兴趣的:(Glide4.x源码浅析(三)Glide流程之图片的获取)