summaryrefslogtreecommitdiff
path: root/org.fox.ttcomics/src/main/java/org/fox/ttcomics2/utils/StreamGlideModule.java
blob: 3659bfa754844952c3b5e7fc498077f1a1373269 (plain)
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
package org.fox.ttcomics2.utils;

import android.content.Context;
import android.util.Log;

import com.bumptech.glide.Glide;
import com.bumptech.glide.GlideBuilder;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.data.DataFetcher;
import com.bumptech.glide.load.model.GenericLoaderFactory;
import com.bumptech.glide.load.model.ModelLoader;
import com.bumptech.glide.load.model.ModelLoaderFactory;
import com.bumptech.glide.load.model.stream.StreamModelLoader;
import com.bumptech.glide.module.GlideModule;

import java.io.IOException;
import java.io.InputStream;

class StreamGlideModule implements GlideModule {
    @Override public void applyOptions(Context context, GlideBuilder builder) {

    }
    @Override public void registerComponents(Context context, Glide glide) {
        glide.register(InputStream.class, InputStream.class, new PassthroughStreamLoader.Factory());
    }
}

class PassthroughStreamLoader implements StreamModelLoader<InputStream> {
    @Override public DataFetcher<InputStream> getResourceFetcher(final InputStream model, int width, int height) {
        return new DataFetcher<InputStream>() {
            @Override public InputStream loadData(Priority priority) throws Exception {
                return model;
            }
            @Override public void cleanup() {
                try {
                    model.close();
                } catch (IOException e) {
                    Log.w("PassthroughDataFetcher", "Cannot clean up after stream", e);
                }
            }
            @Override public String getId() {
                return String.valueOf(System.currentTimeMillis()); // There's no way to have a meaningful value here,
                // which means that caching of straight-loaded InputStreams is not possible.
            }
            @Override public void cancel() {
                // do nothing
            }
        };
    }

    public static class Factory implements ModelLoaderFactory<InputStream, InputStream> {
        @Override public ModelLoader<InputStream, InputStream> build(Context context, GenericLoaderFactory factories) {
            return new PassthroughStreamLoader();
        }
        @Override public void teardown() {
            // nothing to do
        }
    }
}