package com.fourlastor.dante.html;

import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ImageSpan;

import com.fourlastor.dante.parser.Block;
import com.fourlastor.dante.parser.BlockListener;

public class ImgListener implements BlockListener {

    private static final String UNICODE_REPLACE = "\uFFFC";

    private final ImgGetter imgGetter;

    ImgListener(ImgGetter imgGetter) {
        this.imgGetter = imgGetter;
    }

    @Override
    public void start(Block block, SpannableStringBuilder text) {
        String src = ((HtmlBlock) block).getAttributes().get("src");
        if (src == null) {
            return;
        }

        int len = text.length();
        text.append(UNICODE_REPLACE);
        Drawable image = imgGetter.getImage(src);
        text.setSpan(
                new ImageSpan(image, src),
                len,
                text.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
        );
    }

    @Override
    public void end(Block block, SpannableStringBuilder text) {

    }

    @Override
    public boolean match(Block block) {
        return block instanceof HtmlBlock
                && "img".equalsIgnoreCase(((HtmlBlock) block).getName());
    }

    public interface ImgGetter {

        Drawable getImage(@NonNull String src);
    }
}

@@ -29,16 +29,135 @@
 .html;%0A%0A
+import android.content.res.Resources;%0Aimport android.graphics.Bitmap;%0Aimport android.graphics.drawable.BitmapDrawable;%0A
 import a
@@ -1540,11 +1540,631 @@
 );%0A    %7D
+%0A%0A    public static abstract class BitmapImgGetter implements ImgGetter %7B%0A%0A        private final Resources resources;%0A%0A        protected BitmapImgGetter(Resources resources) %7B%0A            this.resources = resources;%0A        %7D%0A%0A        @Override%0A        public Drawable getImage(@NonNull String src) %7B%0A            Bitmap bitmap = getBitmap(src);%0A            BitmapDrawable bitmapDrawable = new BitmapDrawable(resources, bitmap);%0A%0A            bitmapDrawable.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight());%0A            return bitmapDrawable;%0A        %7D%0A%0A        protected abstract Bitmap getBitmap(String src);%0A    %7D
 %0A%7D%0A

Add convenience implementation for bitmaps