* Added retention annotation for Alignment IntDef (#3)

* Task lists (#4)

* Added since annotation to newly added method/classes

* Fixed the indexes bug for margin spans (#6)

* Feature: Revert spans order (#11)

* SpannableBuilder

* Removed nullablity from Markwon class (no null markdown)

* Image sizes via HTML (#13)
This commit is contained in:
Dimitry 2017-11-11 17:41:10 +03:00 committed by GitHub
parent 80efa6dd4c
commit 6e2dd36e4f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
44 changed files with 1877 additions and 170 deletions

4
.gitignore vendored
View File

@ -3,10 +3,6 @@
/local.properties /local.properties
/.idea /.idea
.DS_Store .DS_Store
/build
/captures /captures
.externalNativeBuild .externalNativeBuild
gradlew
gradlew.bat
/gradle
**/build **/build

View File

@ -12,9 +12,9 @@
## Installation ## Installation
```groovy ```groovy
compile 'ru.noties:markwon:1.0.0' compile 'ru.noties:markwon:1.0.1'
compile 'ru.noties:markwon-image-loader:1.0.0' // optional compile 'ru.noties:markwon-image-loader:1.0.1' // optional
compile 'ru.noties:markwon-view:1.0.0' // optional compile 'ru.noties:markwon-view:1.0.1' // optional
``` ```
## Supported markdown features: ## Supported markdown features:
@ -38,6 +38,11 @@ compile 'ru.noties:markwon-view:1.0.0' // optional
* * Underline (`<u>`) * * Underline (`<u>`)
* * Strike-through (`<s>`, `<strike>`, `<del>`) * * Strike-through (`<s>`, `<strike>`, `<del>`)
* other inline html is rendered via (`Html.fromHtml(...)`) * other inline html is rendered via (`Html.fromHtml(...)`)
* Task lists:
- [ ] Not _done_
- [X] **Done** with `X`
- [x] ~~and~~ **or** small `x`
--- ---
@ -45,8 +50,10 @@ compile 'ru.noties:markwon-view:1.0.0' // optional
Taken with default configuration (except for image loading): Taken with default configuration (except for image loading):
<img src="./art/mw_light_01.png" width="33%" /> <img src="./art/mw_light_02.png" width="33%" /> <a href="./art/mw_light_01.png"><img src="./art/mw_light_01.png" width="30%" /></a>
<img src="./art/mw_light_03.png" width="33%" /> <img src="./art/mw_dark_01.png" width="33%" /> <a href="./art/mw_light_02.png"><img src="./art/mw_light_02.png" width="30%" /></a>
<a href="./art/mw_light_03.png"><img src="./art/mw_light_03.png" width="30%" /></a>
<a href="./art/mw_dark_01.png"><img src="./art/mw_dark_01.png" width="30%" /></a>
By default configuration uses TextView textColor for styling, so changing textColor changes style By default configuration uses TextView textColor for styling, so changing textColor changes style

View File

@ -16,6 +16,13 @@ android {
lintOptions { lintOptions {
abortOnError false abortOnError false
} }
buildTypes {
debug {
minifyEnabled false
proguardFile 'proguard.pro'
}
}
} }
dependencies { dependencies {

5
app/proguard.pro vendored Normal file
View File

@ -0,0 +1,5 @@
-dontwarn okhttp3.**
-dontwarn okio.**
-keep class com.caverock.androidsvg.** { *; }
-dontwarn com.caverock.androidsvg.**

View File

@ -0,0 +1,74 @@
package ru.noties.markwon.debug;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import ru.noties.markwon.R;
import ru.noties.markwon.spans.TaskListDrawable;
public class DebugCheckboxDrawableView extends View {
private Drawable drawable;
public DebugCheckboxDrawableView(Context context) {
super(context);
init(context, null);
}
public DebugCheckboxDrawableView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
private void init(Context context, @Nullable AttributeSet attrs) {
int checkedColor = 0;
int normalColor = 0;
int checkMarkColor = 0;
boolean checked = false;
if (attrs != null) {
final TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.DebugCheckboxDrawableView);
try {
checkedColor = array.getColor(R.styleable.DebugCheckboxDrawableView_fcdv_checkedFillColor, checkedColor);
normalColor = array.getColor(R.styleable.DebugCheckboxDrawableView_fcdv_normalOutlineColor, normalColor);
checkMarkColor = array.getColor(R.styleable.DebugCheckboxDrawableView_fcdv_checkMarkColor, checkMarkColor);
//noinspection ConstantConditions
checked = array.getBoolean(R.styleable.DebugCheckboxDrawableView_fcdv_checked, checked);
} finally {
array.recycle();
}
}
final TaskListDrawable drawable = new TaskListDrawable(checkedColor, normalColor, checkMarkColor);
final int[] state;
if (checked) {
state = new int[]{android.R.attr.state_checked};
} else {
state = new int[0];
}
drawable.setState(state);
this.drawable = drawable;
setLayerType(LAYER_TYPE_SOFTWARE, null);
setWillNotDraw(false);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
drawable.setBounds(0, 0, getWidth(), getHeight());
drawable.draw(canvas);
}
}

View File

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ru.noties.markwon.debug.DebugCheckboxDrawableView
android:layout_width="128dip"
android:layout_height="128dip"
android:layout_gravity="center"
app:fcdv_checkMarkColor="#000"
app:fcdv_checked="true"
app:fcdv_checkedFillColor="#F00"
app:fcdv_normalOutlineColor="#ccc" />
</FrameLayout>

View File

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="DebugCheckboxDrawableView">
<attr name="fcdv_checkedFillColor" format="color" />
<attr name="fcdv_normalOutlineColor" format="color" />
<attr name="fcdv_checkMarkColor" format="color" />
<attr name="fcdv_checked" format="boolean" />
</declare-styleable>
</resources>

View File

@ -3,6 +3,7 @@ package ru.noties.markwon;
import android.content.Context; import android.content.Context;
import android.net.Uri; import android.net.Uri;
import android.os.Handler; import android.os.Handler;
import android.os.SystemClock;
import android.support.annotation.NonNull; import android.support.annotation.NonNull;
import android.support.annotation.Nullable; import android.support.annotation.Nullable;
@ -11,6 +12,7 @@ import java.util.concurrent.Future;
import javax.inject.Inject; import javax.inject.Inject;
import ru.noties.debug.Debug;
import ru.noties.markwon.spans.AsyncDrawable; import ru.noties.markwon.spans.AsyncDrawable;
@ActivityScope @ActivityScope
@ -57,8 +59,14 @@ public class MarkdownRenderer {
.urlProcessor(urlProcessor) .urlProcessor(urlProcessor)
.build(); .build();
final long start = SystemClock.uptimeMillis();
final CharSequence text = Markwon.markdown(configuration, markdown); final CharSequence text = Markwon.markdown(configuration, markdown);
final long end = SystemClock.uptimeMillis();
Debug.i("markdown rendered: %d ms", end - start);
if (!isCancelled()) { if (!isCancelled()) {
handler.post(new Runnable() { handler.post(new Runnable() {
@Override @Override

View File

@ -1,15 +1,17 @@
buildscript { buildscript {
repositories { repositories {
jcenter() jcenter()
google()
} }
dependencies { dependencies {
classpath 'com.android.tools.build:gradle:2.3.2' classpath 'com.android.tools.build:gradle:2.3.3'
} }
} }
allprojects { allprojects {
repositories { repositories {
jcenter() jcenter()
google()
} }
version = VERSION_NAME version = VERSION_NAME
group = GROUP group = GROUP
@ -19,24 +21,29 @@ task clean(type: Delete) {
delete rootProject.buildDir delete rootProject.buildDir
} }
task wrapper(type: Wrapper) {
gradleVersion '4.3'
distributionType 'all'
}
ext { ext {
// Config // Config
BUILD_TOOLS = '25.0.2' BUILD_TOOLS = '26.0.3'
TARGET_SDK = 25 TARGET_SDK = 26
MIN_SDK = 16 MIN_SDK = 16
// Dependencies // Dependencies
final def supportVersion = '25.3.1' final def supportVersion = '26.1.0'
SUPPORT_ANNOTATIONS = "com.android.support:support-annotations:$supportVersion" SUPPORT_ANNOTATIONS = "com.android.support:support-annotations:$supportVersion"
SUPPORT_APP_COMPAT = "com.android.support:appcompat-v7:$supportVersion" SUPPORT_APP_COMPAT = "com.android.support:appcompat-v7:$supportVersion"
final def commonMarkVersion = '0.9.0' final def commonMarkVersion = '0.10.0'
COMMON_MARK = "com.atlassian.commonmark:commonmark:$commonMarkVersion" COMMON_MARK = "com.atlassian.commonmark:commonmark:$commonMarkVersion"
COMMON_MARK_STRIKETHROUGHT = "com.atlassian.commonmark:commonmark-ext-gfm-strikethrough:$commonMarkVersion" COMMON_MARK_STRIKETHROUGHT = "com.atlassian.commonmark:commonmark-ext-gfm-strikethrough:$commonMarkVersion"
COMMON_MARK_TABLE = "com.atlassian.commonmark:commonmark-ext-gfm-tables:$commonMarkVersion" COMMON_MARK_TABLE = "com.atlassian.commonmark:commonmark-ext-gfm-tables:$commonMarkVersion"
ANDROID_SVG = 'com.caverock:androidsvg:1.2.1' ANDROID_SVG = 'com.caverock:androidsvg:1.2.1'
ANDROID_GIF = 'pl.droidsonroids.gif:android-gif-drawable:1.2.7' ANDROID_GIF = 'pl.droidsonroids.gif:android-gif-drawable:1.2.8'
OK_HTTP = 'com.squareup.okhttp3:okhttp:3.8.0' OK_HTTP = 'com.squareup.okhttp3:okhttp:3.9.0'
} }

View File

@ -105,6 +105,16 @@ public Builder tableBorderWidth(@Dimension int tableBorderWidth);
public Builder tableOddRowBackgroundColor(@ColorInt int tableOddRowBackgroundColor); public Builder tableOddRowBackgroundColor(@ColorInt int tableOddRowBackgroundColor);
``` ```
#### Task lists
Task lists are supported but with some limitations. First of all, task list cannot be nested
(in a list, quote, etc). By default (if used factory method `builderWithDefaults`) TaskListDrawable
will be used with `linkColor` as the primary color and `windowBackground` as the checkMarkColor.
```java
public Builder taskListDrawable(@NonNull Drawable taskListDrawable);
```
### Contents ### Contents

View File

@ -6,7 +6,7 @@ org.gradle.configureondemand=true
android.enableBuildCache=true android.enableBuildCache=true
android.buildCacheDir=build/pre-dex-cache android.buildCacheDir=build/pre-dex-cache
VERSION_NAME=1.0.0 VERSION_NAME=1.0.1
GROUP=ru.noties GROUP=ru.noties
POM_DESCRIPTION=Markwon POM_DESCRIPTION=Markwon

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.3-all.zip

172
gradlew vendored Executable file
View File

@ -0,0 +1,172 @@
#!/usr/bin/env sh
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"

84
gradlew.bat vendored Normal file
View File

@ -0,0 +1,84 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@ -2,8 +2,6 @@ package ru.noties.markwon;
import android.content.Context; import android.content.Context;
import android.support.annotation.NonNull; import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod; import android.text.method.LinkMovementMethod;
import android.widget.TextView; import android.widget.TextView;
@ -15,19 +13,26 @@ import org.commonmark.parser.Parser;
import java.util.Arrays; import java.util.Arrays;
import ru.noties.markwon.renderer.SpannableRenderer; import ru.noties.markwon.renderer.SpannableRenderer;
import ru.noties.markwon.tasklist.TaskListExtension;
@SuppressWarnings("WeakerAccess") @SuppressWarnings({"WeakerAccess", "unused"})
public abstract class Markwon { public abstract class Markwon {
/** /**
* Helper method to obtain a Parser with registered strike-through &amp; table extensions * Helper method to obtain a Parser with registered strike-through &amp; table extensions
* &amp; task lists (added in 1.0.1)
* *
* @return a Parser instance that is supported by this library * @return a Parser instance that is supported by this library
* @since 1.0.0 * @since 1.0.0
*/ */
@NonNull
public static Parser createParser() { public static Parser createParser() {
return new Parser.Builder() return new Parser.Builder()
.extensions(Arrays.asList(StrikethroughExtension.create(), TablesExtension.create())) .extensions(Arrays.asList(
StrikethroughExtension.create(),
TablesExtension.create(),
TaskListExtension.create()
))
.build(); .build();
} }
@ -54,7 +59,7 @@ public abstract class Markwon {
public static void setMarkdown( public static void setMarkdown(
@NonNull TextView view, @NonNull TextView view,
@NonNull SpannableConfiguration configuration, @NonNull SpannableConfiguration configuration,
@Nullable String markdown @NonNull String markdown
) { ) {
setText(view, markdown(configuration, markdown)); setText(view, markdown(configuration, markdown));
@ -91,15 +96,10 @@ public abstract class Markwon {
* @return parsed markdown * @return parsed markdown
* @since 1.0.0 * @since 1.0.0
*/ */
public static CharSequence markdown(@NonNull Context context, @Nullable String markdown) { @NonNull
final CharSequence out; public static CharSequence markdown(@NonNull Context context, @NonNull String markdown) {
if (TextUtils.isEmpty(markdown)) { final SpannableConfiguration configuration = SpannableConfiguration.create(context);
out = null; return markdown(configuration, markdown);
} else {
final SpannableConfiguration configuration = SpannableConfiguration.create(context);
out = markdown(configuration, markdown);
}
return out;
} }
/** /**
@ -111,17 +111,12 @@ public abstract class Markwon {
* @see SpannableConfiguration * @see SpannableConfiguration
* @since 1.0.0 * @since 1.0.0
*/ */
public static CharSequence markdown(@NonNull SpannableConfiguration configuration, @Nullable String markdown) { @NonNull
final CharSequence out; public static CharSequence markdown(@NonNull SpannableConfiguration configuration, @NonNull String markdown) {
if (TextUtils.isEmpty(markdown)) { final Parser parser = createParser();
out = null; final Node node = parser.parse(markdown);
} else { final SpannableRenderer renderer = new SpannableRenderer();
final Parser parser = createParser(); return renderer.render(configuration, node);
final Node node = parser.parse(markdown);
final SpannableRenderer renderer = new SpannableRenderer();
out = renderer.render(configuration, node);
}
return out;
} }
/** /**

View File

@ -0,0 +1,227 @@
package ru.noties.markwon;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Iterator;
/**
* This class is used to _revert_ order of applied spans. Original SpannableStringBuilder
* is using an array to store all the information about spans. So, a span that is added first
* will be drawn first, which leads to subtle bugs (spans receive wrong `x` values when
* requested to draw itself)
*
* @since 1.0.1
*/
@SuppressWarnings({"WeakerAccess", "unused"})
public class SpannableBuilder {
// do not implement CharSequence (or any of Spanned interfaces)
// we will be using SpannableStringBuilder anyway as a backing store
// as it has tight connection with system (implements some hidden methods, etc)
private final SpannableStringBuilder builder;
// actually we might be just using ArrayList
private final Deque<Span> spans = new ArrayDeque<>(8);
public SpannableBuilder() {
this("");
}
public SpannableBuilder(@NonNull CharSequence cs) {
this.builder = new SpannableStringBuilderImpl(cs.toString());
copySpans(0, cs);
}
/**
* Additional method that takes a String, which is proven to NOT contain any spans
*
* @param text String to append
* @return this instance
*/
@NonNull
public SpannableBuilder append(@NonNull String text) {
builder.append(text);
return this;
}
@NonNull
public SpannableBuilder append(char c) {
builder.append(c);
return this;
}
@NonNull
public SpannableBuilder append(@NonNull CharSequence cs) {
copySpans(length(), cs);
builder.append(cs.toString());
return this;
}
@NonNull
public SpannableBuilder append(@NonNull CharSequence cs, @NonNull Object span) {
final int length = length();
append(cs);
setSpan(span, length);
return this;
}
@NonNull
public SpannableBuilder append(@NonNull CharSequence cs, @NonNull Object span, int flags) {
final int length = length();
append(cs);
setSpan(span, length, length(), flags);
return this;
}
@NonNull
public SpannableBuilder setSpan(@NonNull Object span, int start) {
return setSpan(span, start, length());
}
@NonNull
public SpannableBuilder setSpan(@NonNull Object span, int start, int end) {
return setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
@NonNull
public SpannableBuilder setSpan(@NonNull Object span, int start, int end, int flags) {
spans.push(new Span(span, start, end, flags));
return this;
}
public int length() {
return builder.length();
}
public char charAt(int index) {
return builder.charAt(index);
}
public char lastChar() {
return builder.charAt(length() - 1);
}
@NonNull
public CharSequence removeFromEnd(int start) {
// this method is not intended to be used by clients
// it's a workaround to support tables
final int end = length();
// as we do not expose builder and do no apply spans to it, we are safe to NOT to convert to String
final SpannableStringBuilderImpl impl = new SpannableStringBuilderImpl(builder.subSequence(start, end));
final Iterator<Span> iterator = spans.iterator();
Span span;
while (iterator.hasNext() && ((span = iterator.next())) != null) {
if (span.start >= start && span.end <= end) {
impl.setSpan(span.what, span.start - start, span.end - start, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
iterator.remove();
}
}
builder.replace(start, end, "");
return impl;
}
@Override
@NonNull
public String toString() {
return builder.toString();
}
@NonNull
public CharSequence text() {
// okay, in order to not allow external modification and keep our spans order
// we should not return our builder
//
// plus, if this method was called -> all spans would be applied, which potentially
// breaks the order that we intend to use
// so, we will defensively copy builder
// as we do not expose builder and do no apply spans to it, we are safe to NOT to convert to String
final SpannableStringBuilderImpl impl = new SpannableStringBuilderImpl(builder);
for (Span span : spans) {
impl.setSpan(span.what, span.start, span.end, span.flags);
}
return impl;
}
private void copySpans(final int index, @Nullable CharSequence cs) {
// we must identify already reversed Spanned...
// and (!) iterate backwards when adding (to preserve order)
if (cs instanceof Spanned) {
final Spanned spanned = (Spanned) cs;
final boolean reverse = spanned instanceof SpannedReversed;
final Object[] spans = spanned.getSpans(0, spanned.length(), Object.class);
iterate(reverse, spans, new Action() {
@Override
public void apply(Object o) {
setSpan(
o,
index + spanned.getSpanStart(o),
index + spanned.getSpanEnd(o),
spanned.getSpanFlags(o)
);
}
});
}
}
static class Span {
final Object what;
int start;
int end;
final int flags;
Span(@NonNull Object what, int start, int end, int flags) {
this.what = what;
this.start = start;
this.end = end;
this.flags = flags;
}
}
private interface Action {
void apply(Object o);
}
private static void iterate(boolean reverse, @Nullable Object[] array, @NonNull Action action) {
final int length = array != null
? array.length
: 0;
if (length > 0) {
if (reverse) {
for (int i = length - 1; i >= 0; i--) {
action.apply(array[i]);
}
} else {
for (int i = 0; i < length; i++) {
action.apply(array[i]);
}
}
}
}
}

View File

@ -3,6 +3,8 @@ package ru.noties.markwon;
import android.content.Context; import android.content.Context;
import android.support.annotation.NonNull; import android.support.annotation.NonNull;
import ru.noties.markwon.renderer.html.ImageSizeResolver;
import ru.noties.markwon.renderer.html.ImageSizeResolverDef;
import ru.noties.markwon.renderer.html.SpannableHtmlParser; import ru.noties.markwon.renderer.html.SpannableHtmlParser;
import ru.noties.markwon.spans.AsyncDrawable; import ru.noties.markwon.spans.AsyncDrawable;
import ru.noties.markwon.spans.LinkSpan; import ru.noties.markwon.spans.LinkSpan;
@ -12,10 +14,12 @@ import ru.noties.markwon.spans.SpannableTheme;
public class SpannableConfiguration { public class SpannableConfiguration {
// creates default configuration // creates default configuration
@NonNull
public static SpannableConfiguration create(@NonNull Context context) { public static SpannableConfiguration create(@NonNull Context context) {
return new Builder(context).build(); return new Builder(context).build();
} }
@NonNull
public static Builder builder(@NonNull Context context) { public static Builder builder(@NonNull Context context) {
return new Builder(context); return new Builder(context);
} }
@ -27,7 +31,7 @@ public class SpannableConfiguration {
private final UrlProcessor urlProcessor; private final UrlProcessor urlProcessor;
private final SpannableHtmlParser htmlParser; private final SpannableHtmlParser htmlParser;
private SpannableConfiguration(Builder builder) { private SpannableConfiguration(@NonNull Builder builder) {
this.theme = builder.theme; this.theme = builder.theme;
this.asyncDrawableLoader = builder.asyncDrawableLoader; this.asyncDrawableLoader = builder.asyncDrawableLoader;
this.syntaxHighlight = builder.syntaxHighlight; this.syntaxHighlight = builder.syntaxHighlight;
@ -36,30 +40,37 @@ public class SpannableConfiguration {
this.htmlParser = builder.htmlParser; this.htmlParser = builder.htmlParser;
} }
@NonNull
public SpannableTheme theme() { public SpannableTheme theme() {
return theme; return theme;
} }
@NonNull
public AsyncDrawable.Loader asyncDrawableLoader() { public AsyncDrawable.Loader asyncDrawableLoader() {
return asyncDrawableLoader; return asyncDrawableLoader;
} }
@NonNull
public SyntaxHighlight syntaxHighlight() { public SyntaxHighlight syntaxHighlight() {
return syntaxHighlight; return syntaxHighlight;
} }
@NonNull
public LinkSpan.Resolver linkResolver() { public LinkSpan.Resolver linkResolver() {
return linkResolver; return linkResolver;
} }
@NonNull
public UrlProcessor urlProcessor() { public UrlProcessor urlProcessor() {
return urlProcessor; return urlProcessor;
} }
@NonNull
public SpannableHtmlParser htmlParser() { public SpannableHtmlParser htmlParser() {
return htmlParser; return htmlParser;
} }
@SuppressWarnings("unused")
public static class Builder { public static class Builder {
private final Context context; private final Context context;
@ -69,60 +80,89 @@ public class SpannableConfiguration {
private LinkSpan.Resolver linkResolver; private LinkSpan.Resolver linkResolver;
private UrlProcessor urlProcessor; private UrlProcessor urlProcessor;
private SpannableHtmlParser htmlParser; private SpannableHtmlParser htmlParser;
private ImageSizeResolver imageSizeResolver;
Builder(Context context) { Builder(@NonNull Context context) {
this.context = context; this.context = context;
} }
public Builder theme(SpannableTheme theme) { @NonNull
public Builder theme(@NonNull SpannableTheme theme) {
this.theme = theme; this.theme = theme;
return this; return this;
} }
public Builder asyncDrawableLoader(AsyncDrawable.Loader asyncDrawableLoader) { @NonNull
public Builder asyncDrawableLoader(@NonNull AsyncDrawable.Loader asyncDrawableLoader) {
this.asyncDrawableLoader = asyncDrawableLoader; this.asyncDrawableLoader = asyncDrawableLoader;
return this; return this;
} }
public Builder syntaxHighlight(SyntaxHighlight syntaxHighlight) { @NonNull
public Builder syntaxHighlight(@NonNull SyntaxHighlight syntaxHighlight) {
this.syntaxHighlight = syntaxHighlight; this.syntaxHighlight = syntaxHighlight;
return this; return this;
} }
public Builder linkResolver(LinkSpan.Resolver linkResolver) { @NonNull
public Builder linkResolver(@NonNull LinkSpan.Resolver linkResolver) {
this.linkResolver = linkResolver; this.linkResolver = linkResolver;
return this; return this;
} }
public Builder urlProcessor(UrlProcessor urlProcessor) { @NonNull
public Builder urlProcessor(@NonNull UrlProcessor urlProcessor) {
this.urlProcessor = urlProcessor; this.urlProcessor = urlProcessor;
return this; return this;
} }
public Builder htmlParser(SpannableHtmlParser htmlParser) { @NonNull
public Builder htmlParser(@NonNull SpannableHtmlParser htmlParser) {
this.htmlParser = htmlParser; this.htmlParser = htmlParser;
return this; return this;
} }
/**
* @since 1.0.1
*/
@NonNull
public Builder imageSizeResolver(@NonNull ImageSizeResolver imageSizeResolver) {
this.imageSizeResolver = imageSizeResolver;
return this;
}
@NonNull
public SpannableConfiguration build() { public SpannableConfiguration build() {
if (theme == null) { if (theme == null) {
theme = SpannableTheme.create(context); theme = SpannableTheme.create(context);
} }
if (asyncDrawableLoader == null) { if (asyncDrawableLoader == null) {
asyncDrawableLoader = new AsyncDrawableLoaderNoOp(); asyncDrawableLoader = new AsyncDrawableLoaderNoOp();
} }
if (syntaxHighlight == null) { if (syntaxHighlight == null) {
syntaxHighlight = new SyntaxHighlightNoOp(); syntaxHighlight = new SyntaxHighlightNoOp();
} }
if (linkResolver == null) { if (linkResolver == null) {
linkResolver = new LinkResolverDef(); linkResolver = new LinkResolverDef();
} }
if (urlProcessor == null) { if (urlProcessor == null) {
urlProcessor = new UrlProcessorNoOp(); urlProcessor = new UrlProcessorNoOp();
} }
if (htmlParser == null) { if (htmlParser == null) {
htmlParser = SpannableHtmlParser.create(theme, asyncDrawableLoader, urlProcessor, linkResolver);
if (imageSizeResolver == null) {
imageSizeResolver = new ImageSizeResolverDef();
}
htmlParser = SpannableHtmlParser.create(theme, asyncDrawableLoader, urlProcessor, linkResolver, imageSizeResolver);
} }
return new SpannableConfiguration(this); return new SpannableConfiguration(this);
} }
} }

View File

@ -0,0 +1,13 @@
package ru.noties.markwon;
import android.text.SpannableStringBuilder;
/**
* @since 1.0.1
*/
class SpannableStringBuilderImpl extends SpannableStringBuilder implements SpannedReversed {
SpannableStringBuilderImpl(CharSequence text) {
super(text);
}
}

View File

@ -0,0 +1,9 @@
package ru.noties.markwon;
import android.text.Spanned;
/**
* @since 1.0.1
*/
interface SpannedReversed extends Spanned {
}

View File

@ -5,6 +5,7 @@ import android.support.annotation.NonNull;
import android.support.annotation.Nullable; import android.support.annotation.Nullable;
import android.text.TextUtils; import android.text.TextUtils;
@SuppressWarnings({"unused", "WeakerAccess"})
public class UrlProcessorAndroidAssets implements UrlProcessor { public class UrlProcessorAndroidAssets implements UrlProcessor {
private final UrlProcessorRelativeToAbsolute assetsProcessor private final UrlProcessorRelativeToAbsolute assetsProcessor

View File

@ -1,7 +1,6 @@
package ru.noties.markwon.renderer; package ru.noties.markwon.renderer;
import android.support.annotation.NonNull; import android.support.annotation.NonNull;
import android.text.SpannableStringBuilder;
import android.text.Spanned; import android.text.Spanned;
import android.text.TextUtils; import android.text.TextUtils;
import android.text.style.StrikethroughSpan; import android.text.style.StrikethroughSpan;
@ -14,6 +13,7 @@ import org.commonmark.node.AbstractVisitor;
import org.commonmark.node.BlockQuote; import org.commonmark.node.BlockQuote;
import org.commonmark.node.BulletList; import org.commonmark.node.BulletList;
import org.commonmark.node.Code; import org.commonmark.node.Code;
import org.commonmark.node.CustomBlock;
import org.commonmark.node.CustomNode; import org.commonmark.node.CustomNode;
import org.commonmark.node.Emphasis; import org.commonmark.node.Emphasis;
import org.commonmark.node.FencedCodeBlock; import org.commonmark.node.FencedCodeBlock;
@ -38,6 +38,7 @@ import java.util.ArrayList;
import java.util.Deque; import java.util.Deque;
import java.util.List; import java.util.List;
import ru.noties.markwon.SpannableBuilder;
import ru.noties.markwon.SpannableConfiguration; import ru.noties.markwon.SpannableConfiguration;
import ru.noties.markwon.renderer.html.SpannableHtmlParser; import ru.noties.markwon.renderer.html.SpannableHtmlParser;
import ru.noties.markwon.spans.AsyncDrawable; import ru.noties.markwon.spans.AsyncDrawable;
@ -51,13 +52,16 @@ import ru.noties.markwon.spans.LinkSpan;
import ru.noties.markwon.spans.OrderedListItemSpan; import ru.noties.markwon.spans.OrderedListItemSpan;
import ru.noties.markwon.spans.StrongEmphasisSpan; import ru.noties.markwon.spans.StrongEmphasisSpan;
import ru.noties.markwon.spans.TableRowSpan; import ru.noties.markwon.spans.TableRowSpan;
import ru.noties.markwon.spans.TaskListSpan;
import ru.noties.markwon.spans.ThematicBreakSpan; import ru.noties.markwon.spans.ThematicBreakSpan;
import ru.noties.markwon.tasklist.TaskListBlock;
import ru.noties.markwon.tasklist.TaskListItem;
@SuppressWarnings("WeakerAccess") @SuppressWarnings("WeakerAccess")
public class SpannableMarkdownVisitor extends AbstractVisitor { public class SpannableMarkdownVisitor extends AbstractVisitor {
private final SpannableConfiguration configuration; private final SpannableConfiguration configuration;
private final SpannableStringBuilder builder; private final SpannableBuilder builder;
private final Deque<HtmlInlineItem> htmlInlineItems; private final Deque<HtmlInlineItem> htmlInlineItems;
private int blockQuoteIndent; private int blockQuoteIndent;
@ -69,7 +73,7 @@ public class SpannableMarkdownVisitor extends AbstractVisitor {
public SpannableMarkdownVisitor( public SpannableMarkdownVisitor(
@NonNull SpannableConfiguration configuration, @NonNull SpannableConfiguration configuration,
@NonNull SpannableStringBuilder builder @NonNull SpannableBuilder builder
) { ) {
this.configuration = configuration; this.configuration = configuration;
this.builder = builder; this.builder = builder;
@ -109,10 +113,7 @@ public class SpannableMarkdownVisitor extends AbstractVisitor {
visitChildren(blockQuote); visitChildren(blockQuote);
setSpan(length, new BlockQuoteSpan( setSpan(length, new BlockQuoteSpan(configuration.theme()));
configuration.theme(),
blockQuoteIndent
));
blockQuoteIndent -= 1; blockQuoteIndent -= 1;
@ -197,11 +198,10 @@ public class SpannableMarkdownVisitor extends AbstractVisitor {
visitChildren(listItem); visitChildren(listItem);
// todo| in order to provide real RTL experience there must be a way to provide this string
setSpan(length, new OrderedListItemSpan( setSpan(length, new OrderedListItemSpan(
configuration.theme(), configuration.theme(),
String.valueOf(start) + "." + '\u00a0', String.valueOf(start) + "." + '\u00a0'
blockQuoteIndent,
length
)); ));
// after we have visited the children increment start number // after we have visited the children increment start number
@ -214,9 +214,7 @@ public class SpannableMarkdownVisitor extends AbstractVisitor {
setSpan(length, new BulletListItemSpan( setSpan(length, new BulletListItemSpan(
configuration.theme(), configuration.theme(),
blockQuoteIndent, listLevel - 1
listLevel - 1,
length
)); ));
} }
@ -246,11 +244,7 @@ public class SpannableMarkdownVisitor extends AbstractVisitor {
final int length = builder.length(); final int length = builder.length();
visitChildren(heading); visitChildren(heading);
setSpan(length, new HeadingSpan( setSpan(length, new HeadingSpan(configuration.theme(), heading.getLevel()));
configuration.theme(),
heading.getLevel(),
builder.length())
);
newLine(); newLine();
@ -269,6 +263,22 @@ public class SpannableMarkdownVisitor extends AbstractVisitor {
newLine(); newLine();
} }
/**
* @since 1.0.1
*/
@Override
public void visit(CustomBlock customBlock) {
if (customBlock instanceof TaskListBlock) {
blockQuoteIndent += 1;
visitChildren(customBlock);
blockQuoteIndent -= 1;
newLine();
builder.append('\n');
} else {
super.visit(customBlock);
}
}
@Override @Override
public void visit(CustomNode customNode) { public void visit(CustomNode customNode) {
@ -278,6 +288,28 @@ public class SpannableMarkdownVisitor extends AbstractVisitor {
visitChildren(customNode); visitChildren(customNode);
setSpan(length, new StrikethroughSpan()); setSpan(length, new StrikethroughSpan());
} else if (customNode instanceof TaskListItem) {
// new in 1.0.1
final TaskListItem listItem = (TaskListItem) customNode;
final int length = builder.length();
blockQuoteIndent += listItem.indent();
visitChildren(customNode);
setSpan(length, new TaskListSpan(
configuration.theme(),
blockQuoteIndent,
listItem.done()
));
newLine();
blockQuoteIndent -= listItem.indent();
} else if (!handleTableNodes(customNode)) { } else if (!handleTableNodes(customNode)) {
super.visit(customNode); super.visit(customNode);
} }
@ -326,11 +358,11 @@ public class SpannableMarkdownVisitor extends AbstractVisitor {
if (pendingTableRow == null) { if (pendingTableRow == null) {
pendingTableRow = new ArrayList<>(2); pendingTableRow = new ArrayList<>(2);
} }
pendingTableRow.add(new TableRowSpan.Cell( pendingTableRow.add(new TableRowSpan.Cell(
tableCellAlignment(cell.getAlignment()), tableCellAlignment(cell.getAlignment()),
builder.subSequence(length, builder.length()) builder.removeFromEnd(length)
)); ));
builder.replace(length, builder.length(), "");
tableRowIsHeader = cell.isHeader(); tableRowIsHeader = cell.isHeader();
@ -456,7 +488,7 @@ public class SpannableMarkdownVisitor extends AbstractVisitor {
private void newLine() { private void newLine() {
if (builder.length() > 0 if (builder.length() > 0
&& '\n' != builder.charAt(builder.length() - 1)) { && '\n' != builder.lastChar()) {
builder.append('\n'); builder.append('\n');
} }
} }

View File

@ -1,32 +1,18 @@
package ru.noties.markwon.renderer; package ru.noties.markwon.renderer;
import android.support.annotation.NonNull; import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.SpannableStringBuilder;
import org.commonmark.node.Node; import org.commonmark.node.Node;
import ru.noties.markwon.SpannableBuilder;
import ru.noties.markwon.SpannableConfiguration; import ru.noties.markwon.SpannableConfiguration;
// please note that this class does not implement Renderer in order to return CharSequence (instead of String)
public class SpannableRenderer { public class SpannableRenderer {
// todo @NonNull
// * LinkDrawableSpan, that draws link whilst image is still loading (it must be clickable...) public CharSequence render(@NonNull SpannableConfiguration configuration, @NonNull Node node) {
// * Common interface for images (in markdown & inline-html) final SpannableBuilder builder = new SpannableBuilder();
// * util method to properly copy markdown (with lists/links, etc) node.accept(new SpannableMarkdownVisitor(configuration, builder));
// * util to apply empty line height return builder.text();
// * transform relative urls to absolute ones...
public CharSequence render(@NonNull SpannableConfiguration configuration, @Nullable Node node) {
final CharSequence out;
if (node == null) {
out = null;
} else {
final SpannableStringBuilder builder = new SpannableStringBuilder();
node.accept(new SpannableMarkdownVisitor(configuration, builder));
out = builder;
}
return out;
} }
} }

View File

@ -1,10 +1,13 @@
package ru.noties.markwon.renderer.html; package ru.noties.markwon.renderer.html;
import android.support.annotation.NonNull; import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.SpannableString; import android.text.SpannableString;
import android.text.Spanned; import android.text.Spanned;
import android.text.TextUtils; import android.text.TextUtils;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map; import java.util.Map;
import ru.noties.markwon.UrlProcessor; import ru.noties.markwon.UrlProcessor;
@ -17,14 +20,18 @@ class ImageProviderImpl implements SpannableHtmlParser.ImageProvider {
private final SpannableTheme theme; private final SpannableTheme theme;
private final AsyncDrawable.Loader loader; private final AsyncDrawable.Loader loader;
private final UrlProcessor urlProcessor; private final UrlProcessor urlProcessor;
private final ImageSizeResolver imageSizeResolver;
ImageProviderImpl( ImageProviderImpl(
@NonNull SpannableTheme theme, @NonNull SpannableTheme theme,
@NonNull AsyncDrawable.Loader loader, @NonNull AsyncDrawable.Loader loader,
@NonNull UrlProcessor urlProcessor) { @NonNull UrlProcessor urlProcessor,
@NonNull ImageSizeResolver imageSizeResolver
) {
this.theme = theme; this.theme = theme;
this.loader = loader; this.loader = loader;
this.urlProcessor = urlProcessor; this.urlProcessor = urlProcessor;
this.imageSizeResolver = imageSizeResolver;
} }
@Override @Override
@ -47,7 +54,7 @@ class ImageProviderImpl implements SpannableHtmlParser.ImageProvider {
replacement = "\uFFFC"; replacement = "\uFFFC";
} }
final AsyncDrawable drawable = new AsyncDrawable(destination, loader); final AsyncDrawable drawable = new AsyncDrawable(destination, loader, imageSizeResolver, parseImageSize(attributes));
final AsyncDrawableSpan span = new AsyncDrawableSpan(theme, drawable); final AsyncDrawableSpan span = new AsyncDrawableSpan(theme, drawable);
final SpannableString string = new SpannableString(replacement); final SpannableString string = new SpannableString(replacement);
@ -60,4 +67,138 @@ class ImageProviderImpl implements SpannableHtmlParser.ImageProvider {
return spanned; return spanned;
} }
@Nullable
private static ImageSize parseImageSize(@NonNull Map<String, String> attributes) {
final ImageSize imageSize;
final StyleProvider styleProvider = new StyleProvider(attributes.get("style"));
final ImageSize.Dimension width = parseDimension(extractDimension("width", attributes, styleProvider));
final ImageSize.Dimension height = parseDimension(extractDimension("height", attributes, styleProvider));
if (width == null
&& height == null) {
imageSize = null;
} else {
imageSize = new ImageSize(width, height);
}
return imageSize;
}
@Nullable
private static String extractDimension(@NonNull String name, @NonNull Map<String, String> attributes, @NonNull StyleProvider styleProvider) {
final String out;
final String inline = attributes.get(name);
if (!TextUtils.isEmpty(inline)) {
out = inline;
} else {
out = extractDimensionFromStyle(name, styleProvider);
}
return out;
}
@Nullable
private static String extractDimensionFromStyle(@NonNull String name, @NonNull StyleProvider styleProvider) {
return styleProvider.attributes().get(name);
}
@Nullable
private static ImageSize.Dimension parseDimension(@Nullable String raw) {
// a set of digits, then dimension unit (allow floating)
final ImageSize.Dimension dimension;
final int length = raw != null
? raw.length()
: 0;
if (length == 0) {
dimension = null;
} else {
// first digit to find -> unit is finished (can be null)
int index = -1;
for (int i = length - 1; i >= 0; i--) {
if (Character.isDigit(raw.charAt(i))) {
index = i;
break;
}
}
// no digits -> no dimension
if (index == -1) {
dimension = null;
} else {
final String value;
final String unit;
// no unit is specified
if (index == length - 1) {
value = raw;
unit = null;
} else {
value = raw.substring(0, index + 1);
unit = raw.substring(index + 1);
}
ImageSize.Dimension inner;
try {
final float floatValue = Float.parseFloat(value);
inner = new ImageSize.Dimension(floatValue, unit);
} catch (NumberFormatException e) {
inner = null;
}
dimension = inner;
}
}
return dimension;
}
private static class StyleProvider {
private final String style;
private Map<String, String> attributes;
StyleProvider(@Nullable String style) {
this.style = style;
}
@NonNull
Map<String, String> attributes() {
final Map<String, String> out;
if (attributes != null) {
out = attributes;
} else {
if (TextUtils.isEmpty(style)) {
out = attributes = Collections.emptyMap();
} else {
final String[] split = style.split(";");
final Map<String, String> map = new HashMap<>(split.length);
String[] parts;
for (String s : split) {
if (!TextUtils.isEmpty(s)) {
parts = s.split(":");
if (parts.length == 2) {
map.put(parts[0].trim(), parts[1].trim());
}
}
}
out = attributes = map;
}
}
return out;
}
}
} }

View File

@ -0,0 +1,37 @@
package ru.noties.markwon.renderer.html;
import android.support.annotation.Nullable;
/**
* @since 1.0.1
*/
@SuppressWarnings("WeakerAccess")
public class ImageSize {
public static class Dimension {
public final float value;
public final String unit;
public Dimension(float value, @Nullable String unit) {
this.value = value;
this.unit = unit;
}
@Override
public String toString() {
return "Dimension{" +
"value=" + value +
", unit='" + unit + '\'' +
'}';
}
}
public final Dimension width;
public final Dimension height;
public ImageSize(@Nullable Dimension width, @Nullable Dimension height) {
this.width = width;
this.height = height;
}
}

View File

@ -0,0 +1,29 @@
package ru.noties.markwon.renderer.html;
import android.graphics.Rect;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
/**
* @since 1.0.1
*/
@SuppressWarnings({"WeakerAccess", "unused"})
public abstract class ImageSizeResolver {
/**
* We do not expose canvas height deliberately. As we cannot rely on this value very much
*
* @param imageSize {@link ImageSize} parsed from HTML
* @param imageBounds original image bounds
* @param canvasWidth width of the canvas
* @param textSize current font size
* @return resolved image bounds
*/
@NonNull
public abstract Rect resolveImageSize(
@Nullable ImageSize imageSize,
@NonNull Rect imageBounds,
int canvasWidth,
float textSize
);
}

View File

@ -0,0 +1,85 @@
package ru.noties.markwon.renderer.html;
import android.graphics.Rect;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
/**
* @since 1.0.1
*/
@SuppressWarnings({"WeakerAccess", "unused"})
public class ImageSizeResolverDef extends ImageSizeResolver {
// we track these two, others are considered to be pixels
protected static final String UNIT_PERCENT = "%";
protected static final String UNIT_EM = "em";
@NonNull
@Override
public Rect resolveImageSize(
@Nullable ImageSize imageSize,
@NonNull Rect imageBounds,
int canvasWidth,
float textSize
) {
if (imageSize == null) {
return imageBounds;
}
final Rect rect;
final ImageSize.Dimension width = imageSize.width;
final ImageSize.Dimension height = imageSize.height;
final int imageWidth = imageBounds.width();
final int imageHeight = imageBounds.height();
final float ratio = (float) imageWidth / imageHeight;
if (width != null) {
final int w;
final int h;
if (UNIT_PERCENT.equals(width.unit)) {
w = (int) (canvasWidth * (width.value / 100.F) + .5F);
} else {
w = resolveAbsolute(width, imageWidth, textSize);
}
if (height == null
|| UNIT_PERCENT.equals(height.unit)) {
h = (int) (w / ratio + .5F);
} else {
h = resolveAbsolute(height, imageHeight, textSize);
}
rect = new Rect(0, 0, w, h);
} else if (height != null) {
if (!UNIT_PERCENT.equals(height.unit)) {
final int h = resolveAbsolute(height, imageHeight, textSize);
final int w = (int) (h * ratio + .5F);
rect = new Rect(0, 0, w, h);
} else {
rect = imageBounds;
}
} else {
rect = imageBounds;
}
return rect;
}
protected int resolveAbsolute(@NonNull ImageSize.Dimension dimension, int original, float textSize) {
final int out;
if (UNIT_EM.equals(dimension.unit)) {
out = (int) (dimension.value * textSize + .5F);
} else {
out = original;
}
return out;
}
}

View File

@ -21,37 +21,74 @@ import ru.noties.markwon.spans.SpannableTheme;
public class SpannableHtmlParser { public class SpannableHtmlParser {
// creates default parser // creates default parser
@NonNull
public static SpannableHtmlParser create( public static SpannableHtmlParser create(
@NonNull SpannableTheme theme, @NonNull SpannableTheme theme,
@NonNull AsyncDrawable.Loader loader @NonNull AsyncDrawable.Loader loader
) { ) {
return builderWithDefaults(theme, loader, null, null) return builderWithDefaults(theme, loader, null, null, null)
.build(); .build();
} }
/**
* @since 1.0.1
*/
@NonNull
public static SpannableHtmlParser create(
@NonNull SpannableTheme theme,
@NonNull AsyncDrawable.Loader loader,
@NonNull ImageSizeResolver imageSizeResolver
) {
return builderWithDefaults(theme, loader, null, null, imageSizeResolver)
.build();
}
@NonNull
public static SpannableHtmlParser create( public static SpannableHtmlParser create(
@NonNull SpannableTheme theme, @NonNull SpannableTheme theme,
@NonNull AsyncDrawable.Loader loader, @NonNull AsyncDrawable.Loader loader,
@NonNull UrlProcessor urlProcessor, @NonNull UrlProcessor urlProcessor,
@NonNull LinkSpan.Resolver resolver @NonNull LinkSpan.Resolver resolver
) { ) {
return builderWithDefaults(theme, loader, urlProcessor, resolver) return builderWithDefaults(theme, loader, urlProcessor, resolver, null)
.build(); .build();
} }
/**
* @since 1.0.1
*/
@NonNull
public static SpannableHtmlParser create(
@NonNull SpannableTheme theme,
@NonNull AsyncDrawable.Loader loader,
@NonNull UrlProcessor urlProcessor,
@NonNull LinkSpan.Resolver resolver,
@NonNull ImageSizeResolver imageSizeResolver
) {
return builderWithDefaults(theme, loader, urlProcessor, resolver, imageSizeResolver)
.build();
}
@NonNull
public static Builder builder() { public static Builder builder() {
return new Builder(); return new Builder();
} }
@NonNull
public static Builder builderWithDefaults(@NonNull SpannableTheme theme) { public static Builder builderWithDefaults(@NonNull SpannableTheme theme) {
return builderWithDefaults(theme, null, null, null); return builderWithDefaults(theme, null, null, null, null);
} }
/**
* Updated in 1.0.1: added imageSizeResolverArgument
*/
@NonNull
public static Builder builderWithDefaults( public static Builder builderWithDefaults(
@NonNull SpannableTheme theme, @NonNull SpannableTheme theme,
@Nullable AsyncDrawable.Loader asyncDrawableLoader, @Nullable AsyncDrawable.Loader asyncDrawableLoader,
@Nullable UrlProcessor urlProcessor, @Nullable UrlProcessor urlProcessor,
@Nullable LinkSpan.Resolver resolver @Nullable LinkSpan.Resolver resolver,
@Nullable ImageSizeResolver imageSizeResolver
) { ) {
if (urlProcessor == null) { if (urlProcessor == null) {
@ -68,7 +105,12 @@ public class SpannableHtmlParser {
final ImageProvider imageProvider; final ImageProvider imageProvider;
if (asyncDrawableLoader != null) { if (asyncDrawableLoader != null) {
imageProvider = new ImageProviderImpl(theme, asyncDrawableLoader, urlProcessor);
if (imageSizeResolver == null) {
imageSizeResolver = new ImageSizeResolverDef();
}
imageProvider = new ImageProviderImpl(theme, asyncDrawableLoader, urlProcessor, imageSizeResolver);
} else { } else {
imageProvider = null; imageProvider = null;
} }
@ -163,21 +205,25 @@ public class SpannableHtmlParser {
private ImageProvider imageProvider; private ImageProvider imageProvider;
private HtmlParser parser; private HtmlParser parser;
@NonNull
Builder simpleTag(@NonNull String tag, @NonNull SpanProvider provider) { Builder simpleTag(@NonNull String tag, @NonNull SpanProvider provider) {
simpleTags.put(tag, provider); simpleTags.put(tag, provider);
return this; return this;
} }
public Builder imageProvider(ImageProvider imageProvider) { @NonNull
public Builder imageProvider(@Nullable ImageProvider imageProvider) {
this.imageProvider = imageProvider; this.imageProvider = imageProvider;
return this; return this;
} }
@NonNull
public Builder parser(@NonNull HtmlParser parser) { public Builder parser(@NonNull HtmlParser parser) {
this.parser = parser; this.parser = parser;
return this; return this;
} }
@NonNull
public SpannableHtmlParser build() { public SpannableHtmlParser build() {
if (parser == null) { if (parser == null) {
parser = DefaultHtmlParser.create(); parser = DefaultHtmlParser.create();

View File

@ -3,15 +3,20 @@ package ru.noties.markwon.spans;
import android.graphics.Canvas; import android.graphics.Canvas;
import android.graphics.ColorFilter; import android.graphics.ColorFilter;
import android.graphics.PixelFormat; import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.Animatable; import android.graphics.drawable.Animatable;
import android.graphics.drawable.Drawable; import android.graphics.drawable.Drawable;
import android.support.annotation.IntRange; import android.support.annotation.IntRange;
import android.support.annotation.NonNull; import android.support.annotation.NonNull;
import android.support.annotation.Nullable; import android.support.annotation.Nullable;
import ru.noties.markwon.renderer.html.ImageSize;
import ru.noties.markwon.renderer.html.ImageSizeResolver;
public class AsyncDrawable extends Drawable { public class AsyncDrawable extends Drawable {
public interface Loader { public interface Loader {
void load(@NonNull String destination, @NonNull AsyncDrawable drawable); void load(@NonNull String destination, @NonNull AsyncDrawable drawable);
void cancel(@NonNull String destination); void cancel(@NonNull String destination);
@ -19,13 +24,32 @@ public class AsyncDrawable extends Drawable {
private final String destination; private final String destination;
private final Loader loader; private final Loader loader;
private final ImageSize imageSize;
private final ImageSizeResolver imageSizeResolver;
private Drawable result; private Drawable result;
private Callback callback; private Callback callback;
private int canvasWidth;
private float textSize;
public AsyncDrawable(@NonNull String destination, @NonNull Loader loader) { public AsyncDrawable(@NonNull String destination, @NonNull Loader loader) {
this(destination, loader, null, null);
}
/**
* @since 1.0.1
*/
public AsyncDrawable(
@NonNull String destination,
@NonNull Loader loader,
@Nullable ImageSizeResolver imageSizeResolver,
@Nullable ImageSize imageSize
) {
this.destination = destination; this.destination = destination;
this.loader = loader; this.loader = loader;
this.imageSizeResolver = imageSizeResolver;
this.imageSize = imageSize;
} }
public String getDestination() { public String getDestination() {
@ -77,13 +101,22 @@ public class AsyncDrawable extends Drawable {
this.result = result; this.result = result;
this.result.setCallback(callback); this.result.setCallback(callback);
// should we copy the data here? like bounds etc? final Rect bounds = resolveBounds();
// if we are async and we load some image from some source result.setBounds(bounds);
// thr bounds might change... so we are better off copy `result` bounds to this instance setBounds(bounds);
setBounds(result.getBounds());
invalidateSelf(); invalidateSelf();
} }
/**
* @since 1.0.1
*/
@SuppressWarnings("WeakerAccess")
public void initWithKnownDimensions(int width, float textSize) {
this.canvasWidth = width;
this.textSize = textSize;
}
@Override @Override
public void draw(@NonNull Canvas canvas) { public void draw(@NonNull Canvas canvas) {
if (hasResult()) { if (hasResult()) {
@ -133,4 +166,19 @@ public class AsyncDrawable extends Drawable {
} }
return out; return out;
} }
/**
* @since 1.0.1
*/
@NonNull
private Rect resolveBounds() {
final Rect rect;
if (imageSizeResolver == null
|| imageSize == null) {
rect = result.getBounds();
} else {
rect = imageSizeResolver.resolveImageSize(imageSize, result.getBounds(), canvasWidth, textSize);
}
return rect;
}
} }

View File

@ -9,10 +9,14 @@ import android.support.annotation.NonNull;
import android.support.annotation.Nullable; import android.support.annotation.Nullable;
import android.text.style.ReplacementSpan; import android.text.style.ReplacementSpan;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@SuppressWarnings("WeakerAccess") @SuppressWarnings("WeakerAccess")
public class AsyncDrawableSpan extends ReplacementSpan { public class AsyncDrawableSpan extends ReplacementSpan {
@IntDef({ALIGN_BOTTOM, ALIGN_BASELINE, ALIGN_CENTER}) @IntDef({ALIGN_BOTTOM, ALIGN_BASELINE, ALIGN_CENTER})
@Retention(RetentionPolicy.SOURCE)
@interface Alignment { @interface Alignment {
} }
@ -25,9 +29,6 @@ public class AsyncDrawableSpan extends ReplacementSpan {
private final int alignment; private final int alignment;
private final boolean replacementTextIsLink; private final boolean replacementTextIsLink;
private int lastKnownDrawX;
private int lastKnownDrawY;
public AsyncDrawableSpan(@NonNull SpannableTheme theme, @NonNull AsyncDrawable drawable) { public AsyncDrawableSpan(@NonNull SpannableTheme theme, @NonNull AsyncDrawable drawable) {
this(theme, drawable, ALIGN_BOTTOM); this(theme, drawable, ALIGN_BOTTOM);
} }
@ -108,8 +109,7 @@ public class AsyncDrawableSpan extends ReplacementSpan {
int bottom, int bottom,
@NonNull Paint paint) { @NonNull Paint paint) {
this.lastKnownDrawX = (int) (x + .5F); drawable.initWithKnownDimensions(canvas.getWidth(), paint.getTextSize());
this.lastKnownDrawY = y;
final AsyncDrawable drawable = this.drawable; final AsyncDrawable drawable = this.drawable;
@ -150,12 +150,4 @@ public class AsyncDrawableSpan extends ReplacementSpan {
public AsyncDrawable getDrawable() { public AsyncDrawable getDrawable() {
return drawable; return drawable;
} }
public int lastKnownDrawX() {
return lastKnownDrawX;
}
public int lastKnownDrawY() {
return lastKnownDrawY;
}
} }

View File

@ -12,11 +12,9 @@ public class BlockQuoteSpan implements LeadingMarginSpan {
private final SpannableTheme theme; private final SpannableTheme theme;
private final Rect rect = ObjectsPool.rect(); private final Rect rect = ObjectsPool.rect();
private final Paint paint = ObjectsPool.paint(); private final Paint paint = ObjectsPool.paint();
private final int indent;
public BlockQuoteSpan(@NonNull SpannableTheme theme, int indent) { public BlockQuoteSpan(@NonNull SpannableTheme theme) {
this.theme = theme; this.theme = theme;
this.indent = indent;
} }
@Override @Override
@ -43,8 +41,16 @@ public class BlockQuoteSpan implements LeadingMarginSpan {
theme.applyBlockQuoteStyle(paint); theme.applyBlockQuoteStyle(paint);
final int left = theme.getBlockMargin() * (indent - 1); final int left;
rect.set(left, top, left + width, bottom); final int right;
{
final int l = x + (dir * width);
final int r = l + (dir * width);
left = Math.min(l, r);
right = Math.max(l, r);
}
rect.set(left, top, right, bottom);
c.drawRect(rect, paint); c.drawRect(rect, paint);
} }

View File

@ -17,19 +17,13 @@ public class BulletListItemSpan implements LeadingMarginSpan {
private final RectF circle = ObjectsPool.rectF(); private final RectF circle = ObjectsPool.rectF();
private final Rect rectangle = ObjectsPool.rect(); private final Rect rectangle = ObjectsPool.rect();
private final int blockIndent;
private final int level; private final int level;
private final int start;
public BulletListItemSpan( public BulletListItemSpan(
@NonNull SpannableTheme theme, @NonNull SpannableTheme theme,
@IntRange(from = 0) int blockIndent, @IntRange(from = 0) int level) {
@IntRange(from = 0) int level,
@IntRange(from = 0) int start) {
this.theme = theme; this.theme = theme;
this.blockIndent = blockIndent;
this.level = level; this.level = level;
this.start = start;
} }
@Override @Override
@ -41,7 +35,8 @@ public class BulletListItemSpan implements LeadingMarginSpan {
public void drawLeadingMargin(Canvas c, Paint p, int x, int dir, int top, int baseline, int bottom, CharSequence text, int start, int end, boolean first, Layout layout) { public void drawLeadingMargin(Canvas c, Paint p, int x, int dir, int top, int baseline, int bottom, CharSequence text, int start, int end, boolean first, Layout layout) {
// if there was a line break, we don't need to draw anything // if there was a line break, we don't need to draw anything
if (this.start != start) { if (!first
|| !LeadingMarginUtils.selfStart(start, text, this)) {
return; return;
} }
@ -60,9 +55,16 @@ public class BulletListItemSpan implements LeadingMarginSpan {
final int marginLeft = (width - side) / 2; final int marginLeft = (width - side) / 2;
final int marginTop = (height - side) / 2; final int marginTop = (height - side) / 2;
final int l = (width * (blockIndent - 1)) + marginLeft; // in order to support RTL
final int l;
final int r;
{
final int left = x + (dir * marginLeft);
final int right = left + (dir * side);
l = Math.min(left, right);
r = Math.max(left, right);
}
final int t = top + marginTop; final int t = top + marginTop;
final int r = l + side;
final int b = t + side; final int b = t + side;
if (level == 0 if (level == 0

View File

@ -52,7 +52,17 @@ public class CodeSpan extends MetricAffectingSpan implements LeadingMarginSpan {
paint.setStyle(Paint.Style.FILL); paint.setStyle(Paint.Style.FILL);
paint.setColor(theme.getCodeBackgroundColor(p)); paint.setColor(theme.getCodeBackgroundColor(p));
rect.set(x, top, c.getWidth(), bottom); final int left;
final int right;
if (dir > 0) {
left = x;
right = c.getWidth();
} else {
left = x - c.getWidth();
right = x;
}
rect.set(left, top, right, bottom);
c.drawRect(rect, paint); c.drawRect(rect, paint);
} }

View File

@ -16,12 +16,10 @@ public class HeadingSpan extends MetricAffectingSpan implements LeadingMarginSpa
private final Rect rect = ObjectsPool.rect(); private final Rect rect = ObjectsPool.rect();
private final Paint paint = ObjectsPool.paint(); private final Paint paint = ObjectsPool.paint();
private final int level; private final int level;
private final int end;
public HeadingSpan(@NonNull SpannableTheme theme, @IntRange(from = 1, to = 6) int level, @IntRange(from = 0) int end) { public HeadingSpan(@NonNull SpannableTheme theme, @IntRange(from = 1, to = 6) int level) {
this.theme = theme; this.theme = theme;
this.level = level; this.level = level;
this.end = end;
} }
@Override @Override
@ -47,21 +45,28 @@ public class HeadingSpan extends MetricAffectingSpan implements LeadingMarginSpa
@Override @Override
public void drawLeadingMargin(Canvas c, Paint p, int x, int dir, int top, int baseline, int bottom, CharSequence text, int start, int end, boolean first, Layout layout) { public void drawLeadingMargin(Canvas c, Paint p, int x, int dir, int top, int baseline, int bottom, CharSequence text, int start, int end, boolean first, Layout layout) {
if (level == 1 if ((level == 1 || level == 2)
|| level == 2) { && LeadingMarginUtils.selfEnd(end, text, this)) {
if (this.end == end) { paint.set(p);
paint.set(p); theme.applyHeadingBreakStyle(paint);
theme.applyHeadingBreakStyle(paint); final float height = paint.getStrokeWidth();
final int b = (int) (bottom - height + .5F);
final float height = paint.getStrokeWidth(); final int left;
final int b = (int) (bottom - height + .5F); final int right;
if (dir > 0) {
rect.set(x, b, c.getWidth(), bottom); left = x;
c.drawRect(rect, paint); right = c.getWidth();
} else {
left = x - c.getWidth();
right = x;
} }
rect.set(left, b, right, bottom);
c.drawRect(rect, paint);
} }
} }
} }

View File

@ -0,0 +1,17 @@
package ru.noties.markwon.spans;
import android.text.Spanned;
abstract class LeadingMarginUtils {
static boolean selfStart(int start, CharSequence text, Object span) {
return text instanceof Spanned && ((Spanned) text).getSpanStart(span) == start;
}
static boolean selfEnd(int end, CharSequence text, Object span) {
return text instanceof Spanned && ((Spanned) text).getSpanEnd(span) == end;
}
private LeadingMarginUtils() {
}
}

View File

@ -2,7 +2,6 @@ package ru.noties.markwon.spans;
import android.graphics.Canvas; import android.graphics.Canvas;
import android.graphics.Paint; import android.graphics.Paint;
import android.support.annotation.IntRange;
import android.support.annotation.NonNull; import android.support.annotation.NonNull;
import android.text.Layout; import android.text.Layout;
import android.text.style.LeadingMarginSpan; import android.text.style.LeadingMarginSpan;
@ -11,19 +10,13 @@ public class OrderedListItemSpan implements LeadingMarginSpan {
private final SpannableTheme theme; private final SpannableTheme theme;
private final String number; private final String number;
private final int blockIndent;
private final int start;
public OrderedListItemSpan( public OrderedListItemSpan(
@NonNull SpannableTheme theme, @NonNull SpannableTheme theme,
@NonNull String number, @NonNull String number
@IntRange(from = 0) int blockIndent,
@IntRange(from = 0) int start
) { ) {
this.theme = theme; this.theme = theme;
this.number = number; this.number = number;
this.blockIndent = blockIndent;
this.start = start;
} }
@Override @Override
@ -35,7 +28,8 @@ public class OrderedListItemSpan implements LeadingMarginSpan {
public void drawLeadingMargin(Canvas c, Paint p, int x, int dir, int top, int baseline, int bottom, CharSequence text, int start, int end, boolean first, Layout layout) { public void drawLeadingMargin(Canvas c, Paint p, int x, int dir, int top, int baseline, int bottom, CharSequence text, int start, int end, boolean first, Layout layout) {
// if there was a line break, we don't need to draw anything // if there was a line break, we don't need to draw anything
if (this.start != start) { if (!first
|| !LeadingMarginUtils.selfStart(start, text, this)) {
return; return;
} }
@ -43,10 +37,16 @@ public class OrderedListItemSpan implements LeadingMarginSpan {
final int width = theme.getBlockMargin(); final int width = theme.getBlockMargin();
final int numberWidth = (int) (p.measureText(number) + .5F); final int numberWidth = (int) (p.measureText(number) + .5F);
final int numberX = (width * blockIndent) - numberWidth;
final int left;
if (dir > 0) {
left = x + (width * dir) - numberWidth;
} else {
left = x + (width * dir) + (width - numberWidth);
}
final float numberY = CanvasUtils.textCenterY(top, bottom, p); final float numberY = CanvasUtils.textCenterY(top, bottom, p);
c.drawText(number, numberX, numberY, p); c.drawText(number, left, numberY, p);
} }
} }

View File

@ -4,44 +4,81 @@ import android.content.Context;
import android.content.res.TypedArray; import android.content.res.TypedArray;
import android.graphics.Paint; import android.graphics.Paint;
import android.graphics.Typeface; import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.support.annotation.AttrRes; import android.support.annotation.AttrRes;
import android.support.annotation.ColorInt; import android.support.annotation.ColorInt;
import android.support.annotation.Dimension; import android.support.annotation.Dimension;
import android.support.annotation.FloatRange; import android.support.annotation.FloatRange;
import android.support.annotation.IntRange; import android.support.annotation.IntRange;
import android.support.annotation.NonNull; import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextPaint; import android.text.TextPaint;
import android.util.TypedValue; import android.util.TypedValue;
@SuppressWarnings("WeakerAccess") @SuppressWarnings("WeakerAccess")
public class SpannableTheme { public class SpannableTheme {
//
// // this method should be used if TextView is known beforehand
// // it will correctly measure the `space` char and set it as `codeMultilineMargin`
// // otherwise this value must be set explicitly
// public static SpannableTheme create(@NonNull TextView textView) {
// return builderWithDefaults(textView.getContext())
// .codeMultilineMargin((int) (textView.getPaint().measureText("\u00a0") + .5F))
// .build();
// }
// this create default theme (except for `codeMultilineMargin` property) /**
* Factory method to obtain an instance of {@link SpannableTheme} with all values as defaults
*
* @param context Context in order to resolve defaults
* @return {@link SpannableTheme} instance
* @see #builderWithDefaults(Context)
* @since 1.0.0
*/
@NonNull
public static SpannableTheme create(@NonNull Context context) { public static SpannableTheme create(@NonNull Context context) {
return builderWithDefaults(context).build(); return builderWithDefaults(context).build();
} }
/**
* Factory method to obtain an instance of {@link Builder}. Please note, that no default
* values are set. This might be useful if you require a lot of special styling that differs
* a lot with default one
*
* @return {@link Builder instance}
* @see #builderWithDefaults(Context)
* @see #builder(SpannableTheme)
* @since 1.0.0
*/
@NonNull
public static Builder builder() { public static Builder builder() {
return new Builder(); return new Builder();
} }
/**
* Factory method to create a {@link Builder} instance and initialize it with values
* from supplied {@link SpannableTheme}
*
* @param copyFrom {@link SpannableTheme} to copy values from
* @return {@link Builder} instance
* @see #builderWithDefaults(Context)
* @since 1.0.0
*/
@NonNull
public static Builder builder(@NonNull SpannableTheme copyFrom) { public static Builder builder(@NonNull SpannableTheme copyFrom) {
return new Builder(copyFrom); return new Builder(copyFrom);
} }
/**
* Factory method to obtain a {@link Builder} instance initialized with default values taken
* from current application theme.
*
* @param context Context to obtain default styling values (colors, etc)
* @return {@link Builder} instance
* @since 1.0.0
*/
@NonNull
public static Builder builderWithDefaults(@NonNull Context context) { public static Builder builderWithDefaults(@NonNull Context context) {
// by default we will be using link color for the checkbox color
// & window background as a checkMark color
final int linkColor = resolve(context, android.R.attr.textColorLink);
final int backgroundColor = resolve(context, android.R.attr.colorBackground);
final Dip dip = new Dip(context); final Dip dip = new Dip(context);
return new Builder() return new Builder()
.linkColor(resolve(context, android.R.attr.textColorLink)) .linkColor(linkColor)
.codeMultilineMargin(dip.toPx(8)) .codeMultilineMargin(dip.toPx(8))
.blockMargin(dip.toPx(24)) .blockMargin(dip.toPx(24))
.blockQuoteWidth(dip.toPx(4)) .blockQuoteWidth(dip.toPx(4))
@ -49,7 +86,8 @@ public class SpannableTheme {
.headingBreakHeight(dip.toPx(1)) .headingBreakHeight(dip.toPx(1))
.thematicBreakHeight(dip.toPx(4)) .thematicBreakHeight(dip.toPx(4))
.tableCellPadding(dip.toPx(4)) .tableCellPadding(dip.toPx(4))
.tableBorderWidth(dip.toPx(1)); .tableBorderWidth(dip.toPx(1))
.taskListDrawable(new TaskListDrawable(linkColor, linkColor, backgroundColor));
} }
private static int resolve(Context context, @AttrRes int attr) { private static int resolve(Context context, @AttrRes int attr) {
@ -147,6 +185,10 @@ public class SpannableTheme {
// by default paint.color * TABLE_ODD_ROW_DEF_ALPHA // by default paint.color * TABLE_ODD_ROW_DEF_ALPHA
protected final int tableOddRowBackgroundColor; protected final int tableOddRowBackgroundColor;
// drawable that will be used to render checkbox (should be stateful)
// TaskListDrawable can be used
protected final Drawable taskListDrawable;
protected SpannableTheme(@NonNull Builder builder) { protected SpannableTheme(@NonNull Builder builder) {
this.linkColor = builder.linkColor; this.linkColor = builder.linkColor;
this.blockMargin = builder.blockMargin; this.blockMargin = builder.blockMargin;
@ -169,6 +211,7 @@ public class SpannableTheme {
this.tableBorderColor = builder.tableBorderColor; this.tableBorderColor = builder.tableBorderColor;
this.tableBorderWidth = builder.tableBorderWidth; this.tableBorderWidth = builder.tableBorderWidth;
this.tableOddRowBackgroundColor = builder.tableOddRowBackgroundColor; this.tableOddRowBackgroundColor = builder.tableOddRowBackgroundColor;
this.taskListDrawable = builder.taskListDrawable;
} }
@ -243,10 +286,16 @@ public class SpannableTheme {
// custom typeface was set // custom typeface was set
if (codeTypeface != null) { if (codeTypeface != null) {
paint.setTypeface(codeTypeface); paint.setTypeface(codeTypeface);
// please note that we won't be calculating textSize
// (like we do when no Typeface is provided), if it's some specific typeface
// we would confuse users about textSize
if (codeTextSize != 0) { if (codeTextSize != 0) {
paint.setTextSize(codeTextSize); paint.setTextSize(codeTextSize);
} }
} else { } else {
paint.setTypeface(Typeface.MONOSPACE); paint.setTypeface(Typeface.MONOSPACE);
final float textSize; final float textSize;
@ -363,6 +412,15 @@ public class SpannableTheme {
paint.setStyle(Paint.Style.FILL); paint.setStyle(Paint.Style.FILL);
} }
/**
* @return a Drawable to be used as a checkbox indication in task lists
* @since 1.0.1
*/
@Nullable
public Drawable getTaskListDrawable() {
return taskListDrawable;
}
public static class Builder { public static class Builder {
private int linkColor; private int linkColor;
@ -386,6 +444,7 @@ public class SpannableTheme {
private int tableBorderColor; private int tableBorderColor;
private int tableBorderWidth; private int tableBorderWidth;
private int tableOddRowBackgroundColor; private int tableOddRowBackgroundColor;
private Drawable taskListDrawable;
Builder() { Builder() {
} }
@ -412,119 +471,159 @@ public class SpannableTheme {
this.tableBorderColor = theme.tableBorderColor; this.tableBorderColor = theme.tableBorderColor;
this.tableBorderWidth = theme.tableBorderWidth; this.tableBorderWidth = theme.tableBorderWidth;
this.tableOddRowBackgroundColor = theme.tableOddRowBackgroundColor; this.tableOddRowBackgroundColor = theme.tableOddRowBackgroundColor;
this.taskListDrawable = theme.taskListDrawable;
} }
@NonNull
public Builder linkColor(@ColorInt int linkColor) { public Builder linkColor(@ColorInt int linkColor) {
this.linkColor = linkColor; this.linkColor = linkColor;
return this; return this;
} }
@NonNull
public Builder blockMargin(@Dimension int blockMargin) { public Builder blockMargin(@Dimension int blockMargin) {
this.blockMargin = blockMargin; this.blockMargin = blockMargin;
return this; return this;
} }
@NonNull
public Builder blockQuoteWidth(@Dimension int blockQuoteWidth) { public Builder blockQuoteWidth(@Dimension int blockQuoteWidth) {
this.blockQuoteWidth = blockQuoteWidth; this.blockQuoteWidth = blockQuoteWidth;
return this; return this;
} }
@NonNull
public Builder blockQuoteColor(@ColorInt int blockQuoteColor) { public Builder blockQuoteColor(@ColorInt int blockQuoteColor) {
this.blockQuoteColor = blockQuoteColor; this.blockQuoteColor = blockQuoteColor;
return this; return this;
} }
@NonNull
public Builder listItemColor(@ColorInt int listItemColor) { public Builder listItemColor(@ColorInt int listItemColor) {
this.listItemColor = listItemColor; this.listItemColor = listItemColor;
return this; return this;
} }
@NonNull
public Builder bulletListItemStrokeWidth(@Dimension int bulletListItemStrokeWidth) { public Builder bulletListItemStrokeWidth(@Dimension int bulletListItemStrokeWidth) {
this.bulletListItemStrokeWidth = bulletListItemStrokeWidth; this.bulletListItemStrokeWidth = bulletListItemStrokeWidth;
return this; return this;
} }
@NonNull
public Builder bulletWidth(@Dimension int bulletWidth) { public Builder bulletWidth(@Dimension int bulletWidth) {
this.bulletWidth = bulletWidth; this.bulletWidth = bulletWidth;
return this; return this;
} }
@NonNull
public Builder codeTextColor(@ColorInt int codeTextColor) { public Builder codeTextColor(@ColorInt int codeTextColor) {
this.codeTextColor = codeTextColor; this.codeTextColor = codeTextColor;
return this; return this;
} }
@NonNull
public Builder codeBackgroundColor(@ColorInt int codeBackgroundColor) { public Builder codeBackgroundColor(@ColorInt int codeBackgroundColor) {
this.codeBackgroundColor = codeBackgroundColor; this.codeBackgroundColor = codeBackgroundColor;
return this; return this;
} }
@NonNull
public Builder codeMultilineMargin(@Dimension int codeMultilineMargin) { public Builder codeMultilineMargin(@Dimension int codeMultilineMargin) {
this.codeMultilineMargin = codeMultilineMargin; this.codeMultilineMargin = codeMultilineMargin;
return this; return this;
} }
@NonNull
public Builder codeTypeface(@NonNull Typeface codeTypeface) { public Builder codeTypeface(@NonNull Typeface codeTypeface) {
this.codeTypeface = codeTypeface; this.codeTypeface = codeTypeface;
return this; return this;
} }
@NonNull
public Builder codeTextSize(@Dimension int codeTextSize) { public Builder codeTextSize(@Dimension int codeTextSize) {
this.codeTextSize = codeTextSize; this.codeTextSize = codeTextSize;
return this; return this;
} }
@NonNull
public Builder headingBreakHeight(@Dimension int headingBreakHeight) { public Builder headingBreakHeight(@Dimension int headingBreakHeight) {
this.headingBreakHeight = headingBreakHeight; this.headingBreakHeight = headingBreakHeight;
return this; return this;
} }
@NonNull
public Builder headingBreakColor(@ColorInt int headingBreakColor) { public Builder headingBreakColor(@ColorInt int headingBreakColor) {
this.headingBreakColor = headingBreakColor; this.headingBreakColor = headingBreakColor;
return this; return this;
} }
@NonNull
public Builder scriptTextSizeRatio(@FloatRange(from = .0F, to = Float.MAX_VALUE) float scriptTextSizeRatio) { public Builder scriptTextSizeRatio(@FloatRange(from = .0F, to = Float.MAX_VALUE) float scriptTextSizeRatio) {
this.scriptTextSizeRatio = scriptTextSizeRatio; this.scriptTextSizeRatio = scriptTextSizeRatio;
return this; return this;
} }
@NonNull
public Builder thematicBreakColor(@ColorInt int thematicBreakColor) { public Builder thematicBreakColor(@ColorInt int thematicBreakColor) {
this.thematicBreakColor = thematicBreakColor; this.thematicBreakColor = thematicBreakColor;
return this; return this;
} }
@NonNull
public Builder thematicBreakHeight(@Dimension int thematicBreakHeight) { public Builder thematicBreakHeight(@Dimension int thematicBreakHeight) {
this.thematicBreakHeight = thematicBreakHeight; this.thematicBreakHeight = thematicBreakHeight;
return this; return this;
} }
@NonNull
public Builder tableCellPadding(@Dimension int tableCellPadding) { public Builder tableCellPadding(@Dimension int tableCellPadding) {
this.tableCellPadding = tableCellPadding; this.tableCellPadding = tableCellPadding;
return this; return this;
} }
@NonNull
public Builder tableBorderColor(@ColorInt int tableBorderColor) { public Builder tableBorderColor(@ColorInt int tableBorderColor) {
this.tableBorderColor = tableBorderColor; this.tableBorderColor = tableBorderColor;
return this; return this;
} }
@NonNull
public Builder tableBorderWidth(@Dimension int tableBorderWidth) { public Builder tableBorderWidth(@Dimension int tableBorderWidth) {
this.tableBorderWidth = tableBorderWidth; this.tableBorderWidth = tableBorderWidth;
return this; return this;
} }
@NonNull
public Builder tableOddRowBackgroundColor(@ColorInt int tableOddRowBackgroundColor) { public Builder tableOddRowBackgroundColor(@ColorInt int tableOddRowBackgroundColor) {
this.tableOddRowBackgroundColor = tableOddRowBackgroundColor; this.tableOddRowBackgroundColor = tableOddRowBackgroundColor;
return this; return this;
} }
/**
* Supplied Drawable must be stateful ({@link Drawable#isStateful()} returns true). If a task
* is marked as done, then this drawable will be updated with an {@code int[] { android.R.attr.state_checked }}
* as the state, otherwise an empty array will be used. This library provides a ready to be
* used Drawable: {@link TaskListDrawable}
*
* @param taskListDrawable Drawable to be used as the task list indication (checkbox)
* @see TaskListDrawable
* @since 1.0.1
*/
@NonNull
public Builder taskListDrawable(@NonNull Drawable taskListDrawable) {
this.taskListDrawable = taskListDrawable;
return this;
}
@NonNull
public SpannableTheme build() { public SpannableTheme build() {
return new SpannableTheme(this); return new SpannableTheme(this);
} }
} }
private static class Dip { private static class Dip {
private final float density; private final float density;
Dip(@NonNull Context context) { Dip(@NonNull Context context) {

View File

@ -0,0 +1,180 @@
package ru.noties.markwon.spans;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.support.annotation.ColorInt;
import android.support.annotation.IntRange;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
/**
* @since 1.0.1
*/
@SuppressWarnings("WeakerAccess")
public class TaskListDrawable extends Drawable {
// represent ratios (not exact coordinates)
private static final Point POINT_0 = new Point(2.75F / 18, 8.25F / 18);
private static final Point POINT_1 = new Point(7.F / 18, 12.5F / 18);
private static final Point POINT_2 = new Point(15.25F / 18, 4.75F / 18);
private final int checkedFillColor;
private final int normalOutlineColor;
private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
private final RectF rectF = new RectF();
private final Paint checkMarkPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private final Path checkMarkPath = new Path();
private boolean isChecked;
// unfortunately we cannot rely on TextView to be LAYER_TYPE_SOFTWARE
// if we could we would draw our checkMarkPath with PorterDuff.CLEAR
public TaskListDrawable(@ColorInt int checkedFillColor, @ColorInt int normalOutlineColor, @ColorInt int checkMarkColor) {
this.checkedFillColor = checkedFillColor;
this.normalOutlineColor = normalOutlineColor;
checkMarkPaint.setColor(checkMarkColor);
checkMarkPaint.setStyle(Paint.Style.STROKE);
}
@Override
protected void onBoundsChange(Rect bounds) {
super.onBoundsChange(bounds);
// we should exclude stroke with from final bounds (half of the strokeWidth from all sides)
// we should have square shape
final float min = Math.min(bounds.width(), bounds.height());
final float stroke = min / 8;
final float side = min - stroke;
rectF.set(0, 0, side, side);
paint.setStrokeWidth(stroke);
checkMarkPaint.setStrokeWidth(stroke);
checkMarkPath.reset();
POINT_0.moveTo(checkMarkPath, side);
POINT_1.lineTo(checkMarkPath, side);
POINT_2.lineTo(checkMarkPath, side);
}
@Override
public void draw(@NonNull Canvas canvas) {
final Paint.Style style;
final int color;
if (isChecked) {
style = Paint.Style.FILL_AND_STROKE;
color = checkedFillColor;
} else {
style = Paint.Style.STROKE;
color = normalOutlineColor;
}
paint.setStyle(style);
paint.setColor(color);
final Rect bounds = getBounds();
final float left = (bounds.width() - rectF.width()) / 2;
final float top = (bounds.height() - rectF.height()) / 2;
final float radius = rectF.width() / 8;
final int save = canvas.save();
try {
canvas.translate(left, top);
canvas.drawRoundRect(rectF, radius, radius, paint);
if (isChecked) {
canvas.drawPath(checkMarkPath, checkMarkPaint);
}
} finally {
canvas.restoreToCount(save);
}
}
@Override
public void setAlpha(@IntRange(from = 0, to = 255) int alpha) {
paint.setAlpha(alpha);
}
@Override
public void setColorFilter(@Nullable ColorFilter colorFilter) {
paint.setColorFilter(colorFilter);
}
@Override
public int getOpacity() {
return PixelFormat.OPAQUE;
}
@Override
public boolean isStateful() {
return true;
}
@Override
protected boolean onStateChange(int[] state) {
final boolean checked;
final int length = state != null
? state.length
: 0;
if (length > 0) {
boolean inner = false;
for (int i = 0; i < length; i++) {
if (android.R.attr.state_checked == state[i]) {
inner = true;
break;
}
}
checked = inner;
} else {
checked = false;
}
final boolean result = checked != isChecked;
if (result) {
invalidateSelf();
isChecked = checked;
}
return result;
}
private static class Point {
final float x;
final float y;
Point(float x, float y) {
this.x = x;
this.y = y;
}
void moveTo(@NonNull Path path, float side) {
path.moveTo(side * x, side * y);
}
void lineTo(@NonNull Path path, float side) {
path.lineTo(side * x, side * y);
}
}
}

View File

@ -0,0 +1,84 @@
package ru.noties.markwon.spans;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.text.Layout;
import android.text.style.LeadingMarginSpan;
/**
* @since 1.0.1
*/
public class TaskListSpan implements LeadingMarginSpan {
private static final int[] STATE_CHECKED = new int[]{android.R.attr.state_checked};
private static final int[] STATE_NONE = new int[0];
private final SpannableTheme theme;
private final int blockIndent;
private final boolean isDone;
public TaskListSpan(@NonNull SpannableTheme theme, int blockIndent, boolean isDone) {
this.theme = theme;
this.blockIndent = blockIndent;
this.isDone = isDone;
}
@Override
public int getLeadingMargin(boolean first) {
return theme.getBlockMargin() * blockIndent;
}
@Override
public void drawLeadingMargin(Canvas c, Paint p, int x, int dir, int top, int baseline, int bottom, CharSequence text, int start, int end, boolean first, Layout layout) {
if (!first
|| !LeadingMarginUtils.selfStart(start, text, this)) {
return;
}
final Drawable drawable = theme.getTaskListDrawable();
if (drawable == null) {
return;
}
final int save = c.save();
try {
final int width = theme.getBlockMargin();
final int height = bottom - top;
final int w = (int) (width * .75F + .5F);
final int h = (int) (height * .75F + .5F);
drawable.setBounds(0, 0, w, h);
if (drawable.isStateful()) {
final int[] state;
if (isDone) {
state = STATE_CHECKED;
} else {
state = STATE_NONE;
}
drawable.setState(state);
}
final int l;
if (dir > 0) {
l = x + (width * (blockIndent - 1)) + ((width - w) / 2);
} else {
l = x - (width * blockIndent) + ((width - w) / 2);
}
final int t = top + ((height - h) / 2);
c.translate(l, t);
drawable.draw(c);
} finally {
c.restoreToCount(save);
}
}
}

View File

@ -33,7 +33,17 @@ public class ThematicBreakSpan implements LeadingMarginSpan {
final int height = (int) (paint.getStrokeWidth() + .5F); final int height = (int) (paint.getStrokeWidth() + .5F);
final int halfHeight = (int) (height / 2.F + .5F); final int halfHeight = (int) (height / 2.F + .5F);
rect.set(x, middle - halfHeight, c.getWidth(), middle + halfHeight); final int left;
final int right;
if (dir > 0) {
left = x;
right = c.getWidth();
} else {
left = x - c.getWidth();
right = x;
}
rect.set(left, middle - halfHeight, right, middle + halfHeight);
c.drawRect(rect, paint); c.drawRect(rect, paint);
} }
} }

View File

@ -0,0 +1,9 @@
package ru.noties.markwon.tasklist;
import org.commonmark.node.CustomBlock;
/**
* @since 1.0.1
*/
public class TaskListBlock extends CustomBlock {
}

View File

@ -0,0 +1,150 @@
package ru.noties.markwon.tasklist;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import org.commonmark.node.Block;
import org.commonmark.parser.InlineParser;
import org.commonmark.parser.block.AbstractBlockParser;
import org.commonmark.parser.block.AbstractBlockParserFactory;
import org.commonmark.parser.block.BlockContinue;
import org.commonmark.parser.block.BlockStart;
import org.commonmark.parser.block.MatchedBlockParser;
import org.commonmark.parser.block.ParserState;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @since 1.0.1
*/
@SuppressWarnings("WeakerAccess")
class TaskListBlockParser extends AbstractBlockParser {
private static final Pattern PATTERN = Pattern.compile("\\s*-\\s+\\[(x|X|\\s)\\]\\s+(.*)");
private final TaskListBlock block = new TaskListBlock();
private final List<Item> items = new ArrayList<>(3);
private int indent = 0;
TaskListBlockParser(@NonNull String startLine, int startIndent) {
items.add(new Item(startLine, startIndent));
indent = startIndent;
}
@Override
public Block getBlock() {
return block;
}
@Override
public BlockContinue tryContinue(ParserState parserState) {
final BlockContinue blockContinue;
final String line = line(parserState);
final int currentIndent = parserState.getIndent();
if (currentIndent > indent) {
indent += 2;
} else if (currentIndent < indent && indent > 1) {
indent -= 2;
}
if (line != null
&& line.length() > 0
&& PATTERN.matcher(line).matches()) {
blockContinue = BlockContinue.atIndex(parserState.getIndex());
} else {
blockContinue = BlockContinue.finished();
}
return blockContinue;
}
@Override
public void addLine(CharSequence line) {
if (length(line) > 0) {
items.add(new Item(line.toString(), indent));
}
}
@Override
public void parseInlines(InlineParser inlineParser) {
Matcher matcher;
TaskListItem listItem;
for (Item item : items) {
matcher = PATTERN.matcher(item.line);
if (!matcher.matches()) {
continue;
}
listItem = new TaskListItem()
.done(isDone(matcher.group(1)))
.indent(item.indent / 2);
inlineParser.parse(matcher.group(2), listItem);
block.appendChild(listItem);
}
}
static class Factory extends AbstractBlockParserFactory {
@Override
public BlockStart tryStart(ParserState state, MatchedBlockParser matchedBlockParser) {
final String line = line(state);
if (line != null
&& line.length() > 0
&& PATTERN.matcher(line).matches()) {
final int length = line.length();
final int index = state.getIndex();
final int atIndex = index != 0
? index + (length - index)
: length;
return BlockStart.of(new TaskListBlockParser(line, state.getIndent()))
.atIndex(atIndex);
}
return BlockStart.none();
}
}
@Nullable
private static String line(@NonNull ParserState state) {
final CharSequence lineRaw = state.getLine();
return lineRaw != null
? lineRaw.toString()
: null;
}
private static int length(@Nullable CharSequence text) {
return text != null
? text.length()
: 0;
}
private static boolean isDone(@NonNull String value) {
return "X".equals(value)
|| "x".equals(value);
}
private static class Item {
final String line;
final int indent;
Item(@NonNull String line, int indent) {
this.line = line;
this.indent = indent;
}
}
}

View File

@ -0,0 +1,21 @@
package ru.noties.markwon.tasklist;
import android.support.annotation.NonNull;
import org.commonmark.parser.Parser;
/**
* @since 1.0.1
*/
public class TaskListExtension implements Parser.ParserExtension {
@NonNull
public static TaskListExtension create() {
return new TaskListExtension();
}
@Override
public void extend(Parser.Builder parserBuilder) {
parserBuilder.customBlockParserFactory(new TaskListBlockParser.Factory());
}
}

View File

@ -0,0 +1,31 @@
package ru.noties.markwon.tasklist;
import org.commonmark.node.CustomNode;
/**
* @since 1.0.1
*/
@SuppressWarnings("WeakerAccess")
public class TaskListItem extends CustomNode {
private boolean done;
private int indent;
public boolean done() {
return done;
}
public TaskListItem done(boolean done) {
this.done = done;
return this;
}
public int indent() {
return indent;
}
public TaskListItem indent(int indent) {
this.indent = indent;
return this;
}
}