Skip to content
TheChatArchiveThe Chat Archive
o1-preview-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

explain: package com.skythinker.gptassistant; import android.content.Context; import…

  1. User

    explain: package com.skythinker.gptassistant;

    import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.text.Layout; import android.text.Spanned; import android.text.TextPaint; import android.text.style.ClickableSpan; import android.text.style.LeadingMarginSpan; import android.util.Log; import android.view.View; import android.widget.TextView;

    import androidx.annotation.NonNull; import androidx.annotation.Nullable;

    import org.commonmark.node.FencedCodeBlock;

    import java.util.ArrayList; import java.util.Arrays; import java.util.List;

    import io.noties.markwon.AbstractMarkwonPlugin; import io.noties.markwon.Markwon; import io.noties.markwon.MarkwonConfiguration; import io.noties.markwon.MarkwonSpansFactory; import io.noties.markwon.ext.latex.JLatexMathPlugin; import io.noties.markwon.ext.tables.TableAwareMovementMethod; import io.noties.markwon.ext.tables.TablePlugin; import io.noties.markwon.image.ImageSize; import io.noties.markwon.image.ImageSizeResolverDef; import io.noties.markwon.image.ImagesPlugin; import io.noties.markwon.inlineparser.MarkwonInlineParserPlugin; import io.noties.markwon.linkify.LinkifyPlugin; import io.noties.markwon.movement.MovementMethodPlugin; import io.noties.markwon.syntax.Prism4jThemeDefault; import io.noties.markwon.syntax.SyntaxHighlightPlugin; import io.noties.markwon.utils.LeadingMarginUtils; import io.noties.prism4j.Prism4j;

    public class MarkdownRenderer { private final Context context; private final Markwon markwon;

    class ClickToCopySpan extends ClickableSpan {
        @Override
        public void onClick(@NonNull View widget) {
            if(widget instanceof TextView) {
                Spanned spanned = (Spanned) ((TextView) widget).getText();
                int start = spanned.getSpanStart(this);
                int end = spanned.getSpanEnd(this);
                String text = spanned.subSequence(start, end).toString().trim();
                GlobalUtils.copyToClipboard(context, text);
                GlobalUtils.showToast(context, context.getString(R.string.toast_code_clipboard), false);
            }
        }
    
        @Override
        public void updateDrawState(@NonNull TextPaint ds) { }
    }
    
    class CopyIconSpan implements LeadingMarginSpan {
        @Override
        public int getLeadingMargin(boolean first) { return 0; }
    
        @Override
        public void drawLeadingMargin(@NonNull Canvas canvas, @NonNull Paint p, int x, int dir, int top, int baseline, int bottom, @NonNull CharSequence text, int start, int end, boolean first, @NonNull Layout layout) {
            if (!LeadingMarginUtils.selfStart(start, text, this)) return; // 仅处理第一行
    
            int save = canvas.save();
            try {
                Paint paint = new Paint();
                String textToDraw = context.getString(R.string.text_copy_code_notice);
                paint.setTextSize(GlobalUtils.dpToPx(context, 14));
                paint.setColor(0x50000000);
                Rect bounds = new Rect();
                paint.getTextBounds(textToDraw, 0, textToDraw.length(), bounds);
                int y = top + bounds.height() + GlobalUtils.dpToPx(context, 4);
                int x1 = layout.getWidth() - bounds.width() - GlobalUtils.dpToPx(context, 8);
                if(layout.getWidth() > bounds.width() + GlobalUtils.dpToPx(context, 16))
                    canvas.drawText(textToDraw, x1, y, paint);
            } finally {
                canvas.restoreToCount(save);
            }
        }
    }
    
    public MarkdownRenderer(Context context) {
        this.context = context;
        markwon = Markwon.builder(context)
                .usePlugin(SyntaxHighlightPlugin.create(new Prism4j(new GrammarLocatorDef()), Prism4jThemeDefault.create(0)))
                .usePlugin(new AbstractMarkwonPlugin() {
                    @Override
                    public void configureSpansFactory(@NonNull MarkwonSpansFactory.Builder builder) {
                        builder.appendFactory(FencedCodeBlock.class, (configuration, props) -> new ClickToCopySpan());
                        builder.appendFactory(FencedCodeBlock.class, (configuration, props) -> new CopyIconSpan());
                    }
                })
                .usePlugin(JLatexMathPlugin.create(40, builder -> builder.inlinesEnabled(true)))
                .usePlugin(ImagesPlugin.create())
                .usePlugin(MarkwonInlineParserPlugin.create())
                .usePlugin(LinkifyPlugin.create())
                .usePlugin(new AbstractMarkwonPlugin() {
                    @NonNull
                    @Override
                    public String processMarkdown(@NonNull String markdown) { // 预处理MD文本
                        List<String> sepList = new ArrayList<>(Arrays.asList(markdown.split("```", -1)));
                        for (int i = 0; i < sepList.size(); i += 2) { // 跳过代码块不处理
                            // 解决仅能渲染“$$...$$”公式的问题
                            String regexDollar = "(?<!\\$)\\$(?!\\$)([^\\n]*?)(?<!\\$)\\$(?!\\$)"; // 匹配单行内的“$...$”
                            String regexBrackets = "(?s)\\\\\\[(.*?)\\\\\\]"; // 跨行匹配“\[...\]”
                            String regexParentheses = "\\\\\\(([^\\n]*?)\\\\\\)"; // 匹配单行内的“\(...\)”
                            String latexReplacement = "\\$\\$$1\\$\\$"; // 替换为“$$...$$”
                            // 为图片添加指向同一URL的链接
                            String regexImage = "!\\[(.*?)\\]\\((.*?)\\)"; // 匹配“![...](...)”
                            String imageReplacement = "[$0]($2)"; // 替换为“[![...](...)](...)”
                            // 进行替换
                            sepList.set(i, sepList.get(i).replaceAll(regexDollar, latexReplacement)
                                    .replaceAll(regexBrackets, latexReplacement)
                                    .replaceAll(regexParentheses, latexReplacement)
                                    .replaceAll(regexImage, imageReplacement));
                        }
                        return String.join("```", sepList);
                    }
                })
                .usePlugin(new AbstractMarkwonPlugin() { // 设置图片大小
                    @Override
                    public void configureConfiguration(@NonNull MarkwonConfiguration.Builder builder) {
                        builder.imageSizeResolver(new ImageSizeResolverDef(){
                            @NonNull @Override
                            protected Rect resolveImageSize(@Nullable ImageSize imageSize, @NonNull Rect imageBounds, int canvasWidth, float textSize) {
                                int maxSize = GlobalUtils.dpToPx(context, 120);
                                if(imageBounds.width() > maxSize || imageBounds.height() > maxSize) {
                                    float ratio = Math.min((float)maxSize / imageBounds.width(), (float)maxSize / imageBounds.height());
                                    imageBounds.right = imageBounds.left + (int)(imageBounds.width() * ratio);
                                    imageBounds.bottom = imageBounds.top + (int)(imageBounds.height() * ratio);
                                }
                                return imageBounds;
                            }
                        });
                    }
                })
    

    // .usePlugin(TablePlugin.create(context)) // unstable // .usePlugin(MovementMethodPlugin.create(TableAwareMovementMethod.create())) .build(); }

    public void render(TextView textView, String markdown) {
        if(textView != null && markdown != null) {
            try {
                markwon.setMarkdown(textView, markdown);
    

    // Log.d("MarkdownRenderer", "render: " + markdown); } catch (Exception e) { e.printStackTrace(); } } } }

  2. Assistant

    The MarkdownRenderer class is designed to render Markdown content in an Android application using the Markwon library. It enhances the standard Markdown rendering by adding features such as syntax highlighting, LaTeX support, image resizing, and interactive code blocks that users can copy to the clipboard.

    Here's a detailed explanation of the code:


    Package and Imports

    package com.skythinker.gptassistant;
    
    import android.content.Context;
    import android.graphics.Canvas;
    import android.graphics.Paint;
    import android.graphics.Rect;
    import android.text.Layout;
    import android.text.Spanned;
    import android.text.TextPaint;
    import android.text.style.ClickableSpan;
    import android.text.style.LeadingMarginSpan;
    import android.view.View;
    import android.widget.TextView;
    
    // AndroidX annotations for null safety
    import androidx.annotation.NonNull;
    import androidx.annotation.Nullable;
    
    // CommonMark node for code blocks
    import org.commonmark.node.FencedCodeBlock;
    
    // Java utility classes
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    
    // Markwon library imports
    import io.noties.markwon.AbstractMarkwonPlugin;
    import io.noties.markwon.Markwon;
    import io.noties.markwon.MarkwonConfiguration;
    import io.noties.markwon.MarkwonSpansFactory;
    import io.noties.markwon.ext.latex.JLatexMathPlugin;
    import io.noties.markwon.image.ImageSize;
    import io.noties.markwon.image.ImageSizeResolverDef;
    import io.noties.markwon.image.ImagesPlugin;
    import io.noties.markwon.inlineparser.MarkwonInlineParserPlugin;
    import io.noties.markwon.linkify.LinkifyPlugin;
    import io.noties.markwon.syntax.Prism4jThemeDefault;
    import io.noties.markwon.syntax.SyntaxHighlightPlugin;
    import io.noties.markwon.utils.LeadingMarginUtils;
    
    // Prism4j library for syntax highlighting
    import io.noties.prism4j.Prism4j;
    
    • Package Declaration: The class is part of the com.skythinker.gptassistant package.
    • Imports: The class imports necessary Android components, the Markwon library for rendering Markdown, and Prism4j for syntax highlighting.

    Class Definition

    public class MarkdownRenderer {
        private final Context context;
        private final Markwon markwon;
        // ...
    }
    
    • Fields:
      • context: The Android Context used for accessing resources.
      • markwon: An instance of Markwon configured for rendering Markdown with custom plugins.

    Inner Classes

    1. ClickToCopySpan

    class ClickToCopySpan extends ClickableSpan {
        @Override
        public void onClick(@NonNull View widget) {
            if(widget instanceof TextView) {
                Spanned spanned = (Spanned) ((TextView) widget).getText();
                int start = spanned.getSpanStart(this);
                int end = spanned.getSpanEnd(this);
                String text = spanned.subSequence(start, end).toString().trim();
                GlobalUtils.copyToClipboard(context, text);
                GlobalUtils.showToast(context, context.getString(R.string.toast_code_clipboard), false);
            }
        }
    
        @Override
        public void updateDrawState(@NonNull TextPaint ds) { }
    }
    
    • Purpose: Makes code blocks clickable so that when tapped, the code is copied to the clipboard.
    • Methods:
      • onClick: Retrieves the text within the span and uses GlobalUtils to copy it to the clipboard and show a toast message.
      • updateDrawState: Overridden to prevent any default styling changes (like underline).

    2. CopyIconSpan

    class CopyIconSpan implements LeadingMarginSpan {
        @Override
        public int getLeadingMargin(boolean first) { return 0; }
    
        @Override
        public void drawLeadingMargin(@NonNull Canvas canvas, @NonNull Paint p, int x, int dir, int top, int baseline, int bottom, @NonNull CharSequence text, int start, int end, boolean first, @NonNull Layout layout) {
            if (!LeadingMarginUtils.selfStart(start, text, this)) return; // Only process the first line
    
            int save = canvas.save();
            try {
                Paint paint = new Paint();
                String textToDraw = context.getString(R.string.text_copy_code_notice);
                paint.setTextSize(GlobalUtils.dpToPx(context, 14));
                paint.setColor(0x50000000); // Semi-transparent black
                Rect bounds = new Rect();
                paint.getTextBounds(textToDraw, 0, textToDraw.length(), bounds);
                int y = top + bounds.height() + GlobalUtils.dpToPx(context, 4);
                int x1 = layout.getWidth() - bounds.width() - GlobalUtils.dpToPx(context, 8);
                if(layout.getWidth() > bounds.width() + GlobalUtils.dpToPx(context, 16))
                    canvas.drawText(textToDraw, x1, y, paint);
            } finally {
                canvas.restoreToCount(save);
            }
        }
    }
    
    • Purpose: Draws a "Copy Code" label on the code block to inform users that the code can be copied.
    • Methods:
      • getLeadingMargin: Returns 0; no extra margin is needed.
      • drawLeadingMargin: Draws the "Copy Code" text on the first line of the code block, positioned at the top-right corner.

    Constructor

    public MarkdownRenderer(Context context) {
        this.context = context;
        markwon = Markwon.builder(context)
            // Syntax highlighting plugin
            .usePlugin(SyntaxHighlightPlugin.create(new Prism4j(new GrammarLocatorDef()), Prism4jThemeDefault.create(0)))
            // Custom plugin to add click-to-copy and copy icon spans
            .usePlugin(new AbstractMarkwonPlugin() {
                @Override
                public void configureSpansFactory(@NonNull MarkwonSpansFactory.Builder builder) {
                    builder.appendFactory(FencedCodeBlock.class, (configuration, props) -> new ClickToCopySpan());
                    builder.appendFactory(FencedCodeBlock.class, (configuration, props) -> new CopyIconSpan());
                }
            })
            // LaTeX support
            .usePlugin(JLatexMathPlugin.create(40, builder -> builder.inlinesEnabled(true)))
            // Image support
            .usePlugin(ImagesPlugin.create())
            // Inline parsing
            .usePlugin(MarkwonInlineParserPlugin.create())
            // Link recognition
            .usePlugin(LinkifyPlugin.create())
            // Custom plugin for preprocessing Markdown
            .usePlugin(new AbstractMarkwonPlugin() {
                @NonNull
                @Override
                public String processMarkdown(@NonNull String markdown) { /* ... */ }
            })
            // Custom plugin to set image sizes
            .usePlugin(new AbstractMarkwonPlugin() { /* ... */ })
            // Build the Markwon instance
            .build();
    }
    
    • Purpose: Initializes the Markwon instance with various plugins to enhance Markdown rendering.

    Plugins and Configuration

    1. SyntaxHighlightPlugin:

      • Enables syntax highlighting using Prism4j.
      • Uses a default theme.
    2. Custom Plugin for Spans:

      • Registers ClickToCopySpan and CopyIconSpan for FencedCodeBlock elements.
    3. JLatexMathPlugin:

      • Adds support for rendering LaTeX equations.
      • Configured to enable inline equations.
    4. ImagesPlugin:

      • Handles image rendering.
    5. MarkwonInlineParserPlugin:

      • Enhances parsing of inline Markdown elements.
    6. LinkifyPlugin:

      • Automatically detects and links URLs in the text.
    7. Custom Plugin for Markdown Preprocessing:

    .usePlugin(new AbstractMarkwonPlugin() {
        @NonNull
        @Override
        public String processMarkdown(@NonNull String markdown) { // Preprocess MD text
            // Split markdown by code blocks to avoid processing code content
            List<String> sepList = new ArrayList<>(Arrays.asList(markdown.split("```", -1)));
            for (int i = 0; i < sepList.size(); i += 2) { // Skip code blocks
                // Patterns to match LaTeX expressions
                String regexDollar = "(?<!\\$)\\$(?!\\$)([^\\n]*?)(?<!\\$)\\$(?!\\$)";
                String regexBrackets = "(?s)\\\\\\[(.*?)\\\\\\]";
                String regexParentheses = "\\\\\\(([^\\n]*?)\\\\\\)";
                String latexReplacement = "\\$\\$$1\\$\\$"; // Replace with "$$...$$"
                // Pattern to match images and make them clickable
                String regexImage = "!\\[(.*?)\\]\\((.*?)\\)";
                String imageReplacement = "[$0]($2)"; // Wrap image in a link
                // Perform replacements
                sepList.set(i, sepList.get(i)
                    .replaceAll(regexDollar, latexReplacement)
                    .replaceAll(regexBrackets, latexReplacement)
                    .replaceAll(regexParentheses, latexReplacement)
                    .replaceAll(regexImage, imageReplacement));
            }
            return String.join("```", sepList);
        }
    })
    
    • Purpose: Preprocesses the Markdown text to:
      • Convert single-dollar LaTeX expressions ($...$) to double-dollar expressions ($$...$$) for correct rendering.
      • Convert LaTeX expressions enclosed in \[ \] or \( \) to $$...$$.
      • Make images clickable by wrapping them in links that point to the image URL.
    1. Custom Plugin for Image Size Configuration:
    .usePlugin(new AbstractMarkwonPlugin() { // Set image size
        @Override
        public void configureConfiguration(@NonNull MarkwonConfiguration.Builder builder) {
            builder.imageSizeResolver(new ImageSizeResolverDef(){
                @NonNull @Override
                protected Rect resolveImageSize(@Nullable ImageSize imageSize, @NonNull Rect imageBounds, int canvasWidth, float textSize) {
                    int maxSize = GlobalUtils.dpToPx(context, 120);
                    if(imageBounds.width() > maxSize || imageBounds.height() > maxSize) {
                        float ratio = Math.min((float)maxSize / imageBounds.width(), (float)maxSize / imageBounds.height());
                        imageBounds.right = imageBounds.left + (int)(imageBounds.width() * ratio);
                        imageBounds.bottom = imageBounds.top + (int)(imageBounds.height() * ratio);
                    }
                    return imageBounds;
                }
            });
        }
    })
    
    • Purpose: Limits the size of images in the Markdown content to a maximum dimension (e.g., 120dp).
    • Functionality:
      • Checks if the image dimensions exceed the maximum size.
      • Scales down the image while maintaining the aspect ratio.

    Render Method

    public void render(TextView textView, String markdown) {
        if(textView != null && markdown != null) {
            try {
                markwon.setMarkdown(textView, markdown);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    • Purpose: Applies the processed and rendered Markdown content to a TextView.
    • Functionality:
      • Checks for null values to prevent NullPointerException.
      • Uses markwon.setMarkdown to render the Markdown in the TextView.
      • Catches and logs any exceptions that occur during rendering.

    Additional Notes

    • GlobalUtils: Utility class (assumed to be defined elsewhere) that provides methods like:
      • copyToClipboard: Copies text to the clipboard.
      • showToast: Displays a toast message.
      • dpToPx: Converts dp units to pixels.
    • Resource Strings:
      • R.string.toast_code_clipboard: String resource for the toast message displayed after copying code.
      • R.string.text_copy_code_notice: String resource for the "Copy Code" notice drawn on code blocks.
    • Commented Code:
      • Lines related to the TablePlugin and MovementMethodPlugin are commented out, possibly due to stability issues.

    Summary

    The MarkdownRenderer class provides an enhanced Markdown rendering experience in Android by:

    • Adding Interactive Code Blocks: Users can tap on code blocks to copy the code to their clipboard, improving usability.
    • Implementing Syntax Highlighting: Makes code within the Markdown more readable and visually appealing.
    • Supporting LaTeX Rendering: Allows for mathematical expressions and equations to be displayed correctly.
    • Handling Images: Resizes images to fit within specified dimensions and makes them clickable to view larger versions if needed.
    • Automatic Link Detection: Recognizes URLs and email addresses, converting them into clickable links.

    Usage Example

    To use the MarkdownRenderer in an Android application:

    // Initialize the renderer
    MarkdownRenderer markdownRenderer = new MarkdownRenderer(context);
    
    // Prepare the TextView and Markdown content
    TextView textView = findViewById(R.id.markdownTextView);
    String markdownContent = "# Hello World\nThis is a sample markdown text with a code block:\n```java\nSystem.out.println(\"Hello, World!\");\n```";
    
    // Render the Markdown content
    markdownRenderer.render(textView, markdownContent);
    

    By integrating this renderer, developers can provide a rich Markdown viewing experience in their Android applications, enhancing content presentation and user interaction.