samples = new ArrayList<>();
19 |
20 | public Samples(Context context) {
21 | this.context = context;
22 | }
23 |
24 | public void readSamples() {
25 | try {
26 | InputStreamReader ir = new InputStreamReader(context.getAssets().open("SAMPLES.tex"));
27 | BufferedReader reader = new BufferedReader(ir);
28 | String line = "";
29 | StringBuilder sb = new StringBuilder();
30 | while ((line = reader.readLine()) != null) {
31 | if (!line.isEmpty() && !isSpace(line) && isSeparator(line)) {
32 | addSample(sb.toString());
33 | sb.delete(0, sb.length());
34 | } else if (!line.isEmpty() && !isSpace(line)) {
35 | sb.append(line).append('\n');
36 | }
37 | }
38 | } catch (IOException e) {
39 | e.printStackTrace();
40 | }
41 | }
42 |
43 | private boolean isSpace(String str) {
44 | for (int i = 0; i < str.length(); i++) {
45 | if (!Character.isSpaceChar(str.charAt(i))) return false;
46 | }
47 | return true;
48 | }
49 |
50 | private boolean isSeparator(String str) {
51 | for (int i = 0; i < str.length(); i++) {
52 | if (str.charAt(i) != '%') return false;
53 | }
54 | return true;
55 | }
56 |
57 | private void addSample(String sample) {
58 | if (sample == null || sample.isEmpty() || isSpace(sample)) return;
59 | samples.add(sample);
60 | }
61 |
62 | public String next() {
63 | if (index >= samples.size()) index = 0;
64 | String x = samples.get(index);
65 | index++;
66 | return x;
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/app/src/main/java/io/nano/tex/test/TeXView.java:
--------------------------------------------------------------------------------
1 | package io.nano.tex.test;
2 |
3 | import android.content.Context;
4 | import android.graphics.Canvas;
5 | import android.graphics.Color;
6 | import android.os.Build;
7 | import android.support.annotation.Nullable;
8 | import android.support.annotation.RequiresApi;
9 | import android.util.AttributeSet;
10 | import android.view.View;
11 |
12 | import io.nano.tex.Graphics2D;
13 | import io.nano.tex.LaTeX;
14 | import io.nano.tex.TeXRender;
15 |
16 | /**
17 | * Created by nano on 18-11-12
18 | */
19 | public class TeXView extends View {
20 |
21 | public TeXView(Context context) {
22 | super(context);
23 | }
24 |
25 | public TeXView(Context context, @Nullable AttributeSet attrs) {
26 | super(context, attrs);
27 | }
28 |
29 | public TeXView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
30 | super(context, attrs, defStyleAttr);
31 | }
32 |
33 | @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
34 | public TeXView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
35 | super(context, attrs, defStyleAttr, defStyleRes);
36 | }
37 |
38 | private int textSize = 40;
39 | private TeXRender render;
40 | private Graphics2D g2 = new Graphics2D();
41 |
42 | public void setLaTeX(String ltx) {
43 | int w = getWidth();
44 | if (w == 0) w = 2048;
45 | render = LaTeX.instance().parse(ltx, w, textSize, 10, Color.DKGRAY);
46 | requestLayout();
47 | }
48 |
49 | public void setTextSize(int size) {
50 | textSize = size;
51 | if (render != null) render.setTextSize(size);
52 | requestLayout();
53 | }
54 |
55 | public void invalidateRender() {
56 | render.invalidateDrawingCache();
57 | invalidate();
58 | }
59 |
60 | @Override
61 | protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
62 | super.onMeasure(widthMeasureSpec, heightMeasureSpec);
63 | if (render == null) return;
64 | int h = render.getHeight();
65 | setMeasuredDimension(getMeasuredWidth(), h + getPaddingTop() + getPaddingBottom());
66 | }
67 |
68 | @Override
69 | protected void onDraw(Canvas canvas) {
70 | if (render == null) return;
71 | g2.setCanvas(canvas);
72 | render.draw(g2, getPaddingLeft(), getPaddingTop());
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
12 |
13 |
19 |
22 |
25 |
26 |
27 |
28 |
34 |
35 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
11 |
16 |
21 |
26 |
31 |
36 |
41 |
46 |
51 |
56 |
61 |
66 |
71 |
76 |
81 |
86 |
91 |
96 |
101 |
106 |
111 |
116 |
121 |
126 |
131 |
136 |
141 |
146 |
151 |
156 |
161 |
166 |
171 |
172 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
10 |
11 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/app/src/main/res/menu/main.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
7 |
8 |
12 |
13 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NanoMichael/AndroidLaTeXMath/c0159021c7349656b38bb4a702234f4ccc76d4d3/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NanoMichael/AndroidLaTeXMath/c0159021c7349656b38bb4a702234f4ccc76d4d3/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NanoMichael/AndroidLaTeXMath/c0159021c7349656b38bb4a702234f4ccc76d4d3/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NanoMichael/AndroidLaTeXMath/c0159021c7349656b38bb4a702234f4ccc76d4d3/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NanoMichael/AndroidLaTeXMath/c0159021c7349656b38bb4a702234f4ccc76d4d3/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NanoMichael/AndroidLaTeXMath/c0159021c7349656b38bb4a702234f4ccc76d4d3/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NanoMichael/AndroidLaTeXMath/c0159021c7349656b38bb4a702234f4ccc76d4d3/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NanoMichael/AndroidLaTeXMath/c0159021c7349656b38bb4a702234f4ccc76d4d3/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NanoMichael/AndroidLaTeXMath/c0159021c7349656b38bb4a702234f4ccc76d4d3/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NanoMichael/AndroidLaTeXMath/c0159021c7349656b38bb4a702234f4ccc76d4d3/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | AndroidLaTeXMath
3 |
4 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 |
5 | ext {
6 | compileSdk = 27
7 | minSdk = 14
8 |
9 | bintrayRepo = 'maven'
10 | bintrayName = 'AndroidLaTeXMath'
11 |
12 | bintrayRepo = 'maven'
13 | bintrayName = 'AndroidLaTeXMath'
14 |
15 | publishedGroupId = 'io.nano'
16 | libraryName = 'AndroidLaTeXMath'
17 | artifact = 'android-tex'
18 |
19 | libraryDesc = 'An efficient LaTeX rendering library on Android.'
20 |
21 | siteUrl = 'https://github.com/NanoMichael/AndroidLaTeXMath'
22 | gitUrl = 'https://github.com/NanoMichael/AndroidLaTeXMath'
23 |
24 | developerId = 'Nano'
25 | developerName = 'Nano'
26 | developerEmail = 'artiano@hotmail.com'
27 |
28 | licenseName = 'The Apache Software License, Version 2.0'
29 | licenseUrl = 'http://www.apache.org/licenses/LICENSE-2.0.txt'
30 | allLicenses = ["Apache-2.0"]
31 | }
32 |
33 | repositories {
34 | google()
35 | jcenter()
36 | }
37 |
38 | dependencies {
39 | classpath 'com.android.tools.build:gradle:3.3.0'
40 |
41 | classpath "com.github.dcendents:android-maven-gradle-plugin:2.1"
42 | classpath "com.jfrog.bintray.gradle:gradle-bintray-plugin:1.8.4"
43 |
44 | // NOTE: Do not place your application dependencies here; they belong
45 | // in the individual module build.gradle files
46 | }
47 | }
48 |
49 | allprojects {
50 | repositories {
51 | google()
52 | jcenter()
53 | }
54 | }
55 |
56 | task clean(type: Delete) {
57 | delete rootProject.buildDir
58 | }
59 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx1536m
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NanoMichael/AndroidLaTeXMath/c0159021c7349656b38bb4a702234f4ccc76d4d3/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Fri Jan 25 20:56:22 CST 2019
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.1-all.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/libtex/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/libtex/build.gradle:
--------------------------------------------------------------------------------
1 | import org.apache.tools.ant.taskdefs.condition.Os
2 |
3 | apply plugin: 'com.android.library'
4 | apply plugin: 'com.github.dcendents.android-maven'
5 | apply plugin: 'com.jfrog.bintray'
6 |
7 | android {
8 | compileSdkVersion compileSdk
9 |
10 | compileOptions {
11 | sourceCompatibility JavaVersion.VERSION_1_7
12 | targetCompatibility JavaVersion.VERSION_1_7
13 | }
14 |
15 | defaultConfig {
16 | minSdkVersion minSdk
17 | targetSdkVersion compileSdk
18 | versionCode 1
19 | versionName "1.0.0"
20 |
21 | consumerProguardFiles 'consumer-rules.pro'
22 | }
23 |
24 | buildTypes {
25 | release {
26 | minifyEnabled false
27 | }
28 | }
29 |
30 | sourceSets.main {
31 | jni.srcDirs = []
32 | jniLibs.srcDirs 'src/main/libs'
33 | }
34 |
35 | def ndkBuild = ndkBuildCmd()
36 |
37 | task buildTeX(type: Exec) {
38 | workingDir file('src/main')
39 | commandLine ndkBuild
40 | }
41 |
42 | tasks.withType(JavaCompile) { task -> task.dependsOn buildTeX }
43 |
44 | task cleanNative(type: Exec) {
45 | workingDir file('src/main')
46 | commandLine ndkBuild, 'clean'
47 | }
48 |
49 | clean.dependsOn cleanNative
50 |
51 | tasks.withType(JavaCompile) {
52 | it.doLast { task ->
53 | println "COPY TEX RESOURCES INTO CLASSES"
54 | copy {
55 | from "${projectDir}/src/main/jni/tex/res"
56 | into "${task.destinationDir}/io/nano/tex/res"
57 | }
58 | }
59 | }
60 | }
61 |
62 | def ndkBuildCmd() {
63 | if (System.env.ANDROID_NDK_ROOT != null) return System.env.ANDROID_NDK_ROOT
64 | Properties prop = new Properties()
65 | prop.load(project.rootProject.file('local.properties').newDataInputStream())
66 | def ndkDir = prop.getProperty('ndk.dir', null)
67 | if (ndkDir == null) throw new GradleException("NDK location not found.")
68 | def ndkBuild = ndkDir + "/ndk-build"
69 | if (Os.isFamily(Os.FAMILY_WINDOWS)) ndkBuild += ".cmd"
70 | return ndkBuild
71 | }
72 |
73 | dependencies {
74 | implementation fileTree(dir: 'libs', include: ['*.jar'])
75 | }
76 |
77 | group = publishedGroupId
78 | version = android.defaultConfig.versionName
79 |
80 | install {
81 | repositories.mavenInstaller {
82 | pom.project {
83 | packaging 'aar'
84 | groupId publishedGroupId
85 | artifactId artifact
86 |
87 | name libraryName
88 | description libraryDesc
89 | url siteUrl
90 |
91 | licenses {
92 | license {
93 | name licenseName
94 | url licenseUrl
95 | }
96 | }
97 | developers {
98 | developer {
99 | id developerId
100 | name developerName
101 | email developerEmail
102 | }
103 | }
104 | scm {
105 | connection gitUrl
106 | developerConnection gitUrl
107 | url siteUrl
108 | }
109 | }
110 | }
111 | }
112 |
113 | task javadoc(type: Javadoc) {
114 | source = android.sourceSets.main.java.srcDirs
115 | classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
116 | destinationDir = file("../javadoc/")
117 | failOnError false
118 | }
119 |
120 | task javadocJar(type: Jar) {
121 | classifier = 'javadoc'
122 | from javadoc.destinationDir
123 | }
124 |
125 | task androidSourcesJar(type: Jar) {
126 | classifier = 'sources'
127 | from android.sourceSets.main.java.srcDirs
128 | }
129 |
130 | artifacts {
131 | archives androidSourcesJar
132 | archives javadocJar
133 | }
134 |
135 | bintray {
136 | Properties properties = new Properties()
137 | properties.load(project.rootProject.file('local.properties').newDataInputStream())
138 |
139 | user = properties.getProperty("bintray.user")
140 | key = properties.getProperty("bintray.apikey")
141 |
142 | configurations = ['archives']
143 | pkg {
144 | repo = bintrayRepo
145 | name = bintrayName
146 | desc = libraryDesc
147 | websiteUrl = siteUrl
148 | vcsUrl = gitUrl
149 | licenses = allLicenses
150 | dryRun = false
151 | publish = true
152 | override = false
153 | publicDownloadNumbers = true
154 | version {
155 | desc = libraryDesc
156 | }
157 | }
158 | }
159 |
--------------------------------------------------------------------------------
/libtex/consumer-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 | -keep class io.nano.tex.** {*;}
--------------------------------------------------------------------------------
/libtex/src/main/.gitignore:
--------------------------------------------------------------------------------
1 | /libs
2 | /obj
3 |
--------------------------------------------------------------------------------
/libtex/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
--------------------------------------------------------------------------------
/libtex/src/main/java/io/nano/tex/ActionRecorder.java:
--------------------------------------------------------------------------------
1 | package io.nano.tex;
2 |
3 | import android.util.Log;
4 |
5 | import java.util.LinkedList;
6 | import java.util.List;
7 |
8 | /**
9 | * Created by nano on 18-11-9
10 | *
11 | * To record the operations on {@link Graphics2D}.
12 | */
13 | final class ActionRecorder {
14 |
15 | private static final String TAG = "ActionRecorder";
16 |
17 | private static final byte ACT_setFont = 0;
18 | private static final byte ACT_setColor = 1;
19 | private static final byte ACT_setStrokeWidth = 2;
20 | private static final byte ACT_setStroke = 3;
21 | private static final byte ACT_translate = 4;
22 | private static final byte ACT_scale = 5;
23 | private static final byte ACT_rotate = 6;
24 | private static final byte ACT_reset = 7;
25 | private static final byte ACT_drawChar = 8;
26 | private static final byte ACT_drawText = 9;
27 | private static final byte ACT_drawLine = 10;
28 | private static final byte ACT_drawRect = 11;
29 | private static final byte ACT_fillRect = 12;
30 | private static final byte ACT_drawRoundRect = 13;
31 | private static final byte ACT_fillRoundRect = 14;
32 |
33 | private static final class Action {
34 | byte action;
35 | Object arg;
36 | float[] args;
37 |
38 | Action(byte action, Object arg, float[] args) {
39 | this.action = action;
40 | this.arg = arg;
41 | this.args = args;
42 | }
43 |
44 | @Override
45 | public String toString() {
46 | StringBuilder builder = new StringBuilder();
47 | builder
48 | .append("{ action: ")
49 | .append(action)
50 | .append(", arg: ")
51 | .append(arg)
52 | .append(", args: [");
53 | if (args == null) builder.append("null");
54 | else for (float x : args) builder.append(x).append(", ");
55 | builder.append("] }");
56 | return builder.toString();
57 | }
58 | }
59 |
60 | private List actions = new LinkedList<>();
61 | private Action origin = new Action(ACT_translate, null, new float[]{0, 0});
62 |
63 | ActionRecorder() {
64 | actions.add(origin);
65 | }
66 |
67 | void setPosition(float x, float y) {
68 | origin.args[0] = x;
69 | origin.args[1] = y;
70 | }
71 |
72 | void record(int action, Object arg, float[] args) {
73 | Action act = new Action((byte) action, arg, args);
74 | actions.add(act);
75 | }
76 |
77 | void play(Graphics2D g2) {
78 | for (Action act : actions) {
79 | if (BuildConfig.DEBUG) Log.d(TAG, act.toString());
80 | play(g2, act);
81 | }
82 | }
83 |
84 | private void play(Graphics2D g2, Action act) {
85 | if (act == null) return;
86 | switch (act.action) {
87 | case ACT_setFont:
88 | g2.setFont((Font) act.arg);
89 | break;
90 | case ACT_setColor:
91 | g2.setColor((int) act.args[0]);
92 | break;
93 | case ACT_setStrokeWidth:
94 | g2.setStrokeWidth(act.args[0]);
95 | break;
96 | case ACT_setStroke:
97 | g2.setStroke(act.args[0], act.args[1], (int) act.args[2], (int) act.args[3]);
98 | break;
99 | case ACT_translate:
100 | g2.translate(act.args[0], act.args[1]);
101 | break;
102 | case ACT_scale:
103 | g2.scale(act.args[0], act.args[1]);
104 | break;
105 | case ACT_rotate:
106 | g2.rotate(act.args[0], act.args[1], act.args[2]);
107 | break;
108 | case ACT_reset:
109 | g2.reset();
110 | break;
111 | case ACT_drawChar:
112 | g2.drawChar((char) act.args[0], act.args[1], act.args[2]);
113 | break;
114 | case ACT_drawText:
115 | g2.drawText((String) act.arg, act.args[0], act.args[1]);
116 | break;
117 | case ACT_drawLine:
118 | g2.drawLine(act.args[0], act.args[1], act.args[2], act.args[3]);
119 | break;
120 | case ACT_drawRect:
121 | g2.drawRect(act.args[0], act.args[1], act.args[2], act.args[3]);
122 | break;
123 | case ACT_fillRect:
124 | g2.fillRect(act.args[0], act.args[1], act.args[2], act.args[3]);
125 | break;
126 | case ACT_drawRoundRect:
127 | g2.drawRoundRect(
128 | act.args[0], act.args[1], act.args[2], act.args[3], act.args[4], act.args[5]);
129 | break;
130 | case ACT_fillRoundRect:
131 | g2.fillRoundRect(
132 | act.args[0], act.args[1], act.args[2], act.args[3], act.args[4], act.args[5]);
133 | break;
134 | default:
135 | break;
136 | }
137 | }
138 | }
139 |
--------------------------------------------------------------------------------
/libtex/src/main/java/io/nano/tex/Alignment.java:
--------------------------------------------------------------------------------
1 | package io.nano.tex;
2 |
3 | /**
4 | * Created by nano on 18-11-10
5 | *
6 | * Keep in sync with the tex::TeXConstants
7 | */
8 | public class Alignment {
9 | /**
10 | * Alignment constant: extra space will be added to the right of the formula
11 | */
12 | public static final int LEFT = 0;
13 |
14 | /**
15 | * Alignment constant: extra space will be added to the left of the formula
16 | */
17 | public static final int RIGHT = 1;
18 |
19 | /**
20 | * Alignment constant: the formula will be centered in the middle. This
21 | * constant can be used for both horizontal and vertical alignment.
22 | */
23 | public static final int CENTER = 2;
24 |
25 | /**
26 | * Alignment constant: extra space will be added under the formula
27 | */
28 | public static final int TOP = 3;
29 |
30 | /**
31 | * Alignment constant: extra space will be added above the formula
32 | */
33 | public static final int BOTTOM = 4;
34 | }
35 |
36 |
--------------------------------------------------------------------------------
/libtex/src/main/java/io/nano/tex/Font.java:
--------------------------------------------------------------------------------
1 | package io.nano.tex;
2 |
3 | import android.graphics.Typeface;
4 |
5 | /**
6 | * Created by nano on 18-11-10
7 | */
8 | public final class Font {
9 |
10 | private Typeface typeface;
11 | private float size;
12 |
13 | private Font(Typeface typeface, float size) {
14 | this.typeface = typeface;
15 | this.size = size;
16 | }
17 |
18 | public Font deriveFont(int style) {
19 | if (typeface.getStyle() == style) return this;
20 | Typeface typeface = Typeface.create(this.typeface, style);
21 | return new Font(typeface, size);
22 | }
23 |
24 | public Typeface getTypeface() {
25 | return typeface;
26 | }
27 |
28 | public float getSize() {
29 | return size;
30 | }
31 |
32 | public static Font create(String name, int style, float size) {
33 | Typeface typeface = Typeface.create(name, style);
34 | return new Font(typeface, size);
35 | }
36 |
37 | public static Font create(String file, float size) {
38 | Typeface tf = Typeface.createFromFile(file);
39 | return new Font(tf, size);
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/libtex/src/main/java/io/nano/tex/Graphics2D.java:
--------------------------------------------------------------------------------
1 | package io.nano.tex;
2 |
3 | import android.graphics.Canvas;
4 | import android.graphics.Matrix;
5 | import android.graphics.Paint;
6 | import android.graphics.RectF;
7 | import android.graphics.Typeface;
8 | import android.text.TextPaint;
9 |
10 | import java.lang.ref.WeakReference;
11 |
12 | /**
13 | * Created by nano on 18-11-10
14 | *
15 | * Represents a 2D graphics context, wrap the Android's 2D graphics API. The context doesn't use the
16 | * Android API to perform the affine transformations, the rendering result is unpredictable when we
17 | * do it. Android do not support the scale operations to draw texts on {@link Canvas} directly when
18 | * have hardware accelerations since Android 3.0, the reason behind is complicated. We maintain a
19 | * transform matrix ({@link Graphics2D#T}) manually to represents the "affine transformations".
20 | */
21 | public final class Graphics2D {
22 |
23 | static final String TAG = "io.nano.tex.Graphics2D";
24 |
25 | /**
26 | * Keep in sync with tex::Cap
27 | */
28 | private static final int CAP_BUTT = 0, CAP_ROUND = 1, CAP_SQUARE = 2;
29 | /**
30 | * Keep in sync with tex::Join
31 | */
32 | private static final int JOIN_BEVEL = 0, JOIN_MITER = 1, JOIN_ROUND = 2;
33 |
34 | private static final int SX = Matrix.MSCALE_X;
35 | private static final int SY = Matrix.MSCALE_Y;
36 | private static final int TX = Matrix.MTRANS_X;
37 | private static final int TY = Matrix.MTRANS_Y;
38 | private static final int R = Matrix.MPERSP_0;
39 | private static final int PX = Matrix.MPERSP_1;
40 | private static final int PY = Matrix.MPERSP_2;
41 |
42 | private TextPaint paint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
43 | private WeakReference canvas;
44 | private float[] T = new float[]{1, 0, 0, 0, 1, 0, 0, 0, 0};
45 | private boolean colorLocked = false;
46 |
47 | public Graphics2D() {
48 | this(null);
49 | }
50 |
51 | public Graphics2D(Canvas canvas) {
52 | if (canvas != null) this.canvas = new WeakReference<>(canvas);
53 | init();
54 | }
55 |
56 | private void init() {
57 | paint.setAntiAlias(true);
58 | // Do not set dither here since we don't draw any bitmap to accelerate the draw speed
59 | // paint.setDither(true);
60 | /*
61 | * Do not use subpixel feature here since the subpixel OP will cause the drawing element
62 | * change its position dynamically, we need exactly the right position here
63 | */
64 | // paint.setSubpixelText(true);
65 | paint.setTextSize(46);
66 | }
67 |
68 | public void setCanvas(Canvas canvas) {
69 | this.canvas = new WeakReference<>(canvas);
70 | }
71 |
72 | public Canvas getCanvas() {
73 | if (canvas == null) return null;
74 | return canvas.get();
75 | }
76 |
77 | public Paint getPaint() {
78 | return paint;
79 | }
80 |
81 | public void setFont(Font font) {
82 | if (font == null) {
83 | paint.setTypeface(Typeface.DEFAULT);
84 | paint.setTextSize(46);
85 | } else {
86 | paint.setTypeface(font.getTypeface());
87 | paint.setTextSize(font.getSize());
88 | }
89 | }
90 |
91 | public void lockColor() {
92 | colorLocked = true;
93 | }
94 |
95 | public void unlockColor() {
96 | colorLocked = false;
97 | }
98 |
99 | public void setColor(int c) {
100 | // Do not allow the drawing op to change the color of the context if the color is locked
101 | if (colorLocked) return;
102 | paint.setColor(c);
103 | }
104 |
105 | public void setStrokeWidth(float width) {
106 | paint.setStrokeWidth(width);
107 | }
108 |
109 | public void setStroke(float width, float miterLimit, int cap, int join) {
110 | paint.setStrokeWidth(width);
111 | paint.setStrokeMiter(miterLimit);
112 | switch (cap) {
113 | case CAP_BUTT:
114 | paint.setStrokeCap(Paint.Cap.BUTT);
115 | break;
116 | case CAP_ROUND:
117 | paint.setStrokeCap(Paint.Cap.ROUND);
118 | break;
119 | case CAP_SQUARE:
120 | paint.setStrokeCap(Paint.Cap.SQUARE);
121 | break;
122 | default:
123 | break;
124 | }
125 | switch (join) {
126 | case JOIN_BEVEL:
127 | paint.setStrokeJoin(Paint.Join.BEVEL);
128 | break;
129 | case JOIN_MITER:
130 | paint.setStrokeJoin(Paint.Join.MITER);
131 | break;
132 | case JOIN_ROUND:
133 | paint.setStrokeJoin(Paint.Join.ROUND);
134 | break;
135 | default:
136 | break;
137 | }
138 | }
139 |
140 | public void translate(float dx, float dy) {
141 | T[TX] += T[SX] * dx;
142 | T[TY] += T[SY] * dy;
143 | }
144 |
145 | public void scale(float sx, float sy) {
146 | T[SX] *= sx;
147 | T[SY] *= sy;
148 | }
149 |
150 | public void rotate(float angle, float px, float py) {
151 | float r = (float) (angle / Math.PI * 180);
152 | T[R] += r;
153 | T[PX] = x(px);
154 | T[PY] = y(py);
155 |
156 | Canvas canvas = getCanvas();
157 | if (canvas == null) return;
158 | canvas.rotate(r, px(), py());
159 | }
160 |
161 | public void reset() {
162 | float r = r(), px = px(), py = py();
163 | Canvas canvas = getCanvas();
164 | T = new float[]{1, 0, 0, 0, 1, 0, 0, 0, 0};
165 | if (canvas == null) return;
166 | canvas.rotate(-r, px, py);
167 | }
168 |
169 | public float sx() {
170 | return T[SX];
171 | }
172 |
173 | public float sy() {
174 | return T[SY];
175 | }
176 |
177 | public float px() {
178 | return T[PX];
179 | }
180 |
181 | public float py() {
182 | return T[PY];
183 | }
184 |
185 | public float r() {
186 | return T[R];
187 | }
188 |
189 | public float x(float x) {
190 | return x * T[SX] + T[TX];
191 | }
192 |
193 | public float y(float y) {
194 | return y * T[SY] + T[TY];
195 | }
196 |
197 | public float w(float w) {
198 | return T[SX] * w;
199 | }
200 |
201 | public float h(float h) {
202 | return T[SY] * h;
203 | }
204 |
205 | private StringBuilder sb = new StringBuilder();
206 |
207 | public void drawChar(char c, float x, float y) {
208 | sb.delete(0, sb.length());
209 | sb.append(c);
210 | drawText(sb.toString(), x, y);
211 | }
212 |
213 | public void drawText(String txt, float x, float y) {
214 | Canvas canvas = getCanvas();
215 | if (canvas == null) return;
216 | float s = paint.getTextSize();
217 | float sx = paint.getTextScaleX();
218 | paint.setTextSize(s * sy());
219 | paint.setTextScaleX(sx() / sy());
220 | canvas.drawText(txt, x(x), y(y), paint);
221 | paint.setTextSize(s);
222 | paint.setTextScaleX(sx);
223 | }
224 |
225 | public void drawLine(float x1, float y1, float x2, float y2) {
226 | Canvas canvas = getCanvas();
227 | if (canvas == null) return;
228 | float th = paint.getStrokeWidth();
229 | float sw = h(th);
230 | if (sw < 1.f) sw = 1.f;
231 | paint.setStrokeWidth(sw);
232 | float xx1 = x(x1);
233 | float yy1 = y(y1);
234 | float xx2 = x(x2);
235 | float yy2 = y(y2);
236 | canvas.drawLine(xx1, yy1, xx2, yy2, paint);
237 | paint.setStrokeWidth(th);
238 | }
239 |
240 | private void renderRect(float x, float y, float w, float h, Paint.Style s) {
241 | Canvas canvas = getCanvas();
242 | if (canvas == null) return;
243 | Paint.Style style = paint.getStyle();
244 | // draw
245 | paint.setStyle(s);
246 | float th = paint.getStrokeWidth();
247 | paint.setStrokeWidth(h(th));
248 | float xx = x(x);
249 | float yy = y(y);
250 | float ww = w(w);
251 | float hh = h(h);
252 | canvas.drawRect(xx, yy, xx + ww, yy + hh, paint);
253 | // reset
254 | paint.setStyle(style);
255 | paint.setStrokeWidth(th);
256 | }
257 |
258 | public void drawRect(float x, float y, float w, float h) {
259 | renderRect(x, y, w, h, Paint.Style.STROKE);
260 | }
261 |
262 | public void fillRect(float x, float y, float w, float h) {
263 | renderRect(x, y, w, h, Paint.Style.FILL);
264 | }
265 |
266 | private RectF tr = new RectF();
267 |
268 | private void renderRoundRect(float x, float y, float w, float h, float rx, float ry, Paint.Style s) {
269 | Canvas canvas = getCanvas();
270 | if (canvas == null) return;
271 | Paint.Style style = paint.getStyle();
272 | paint.setStyle(s);
273 | float th = paint.getStrokeWidth();
274 | paint.setStrokeWidth(h(th));
275 | tr.left = x(x);
276 | tr.top = y(y);
277 | tr.right = tr.left + w(w);
278 | tr.bottom = tr.top + h(h);
279 | float rxx = w(rx);
280 | float ryy = h(ry);
281 | canvas.drawRoundRect(tr, rxx, ryy, paint);
282 | // reset
283 | paint.setStyle(style);
284 | paint.setStrokeWidth(th);
285 | }
286 |
287 | public void drawRoundRect(float x, float y, float w, float h, float rx, float ry) {
288 | renderRoundRect(x, y, w, h, rx, ry, Paint.Style.STROKE);
289 | }
290 |
291 | public void fillRoundRect(float x, float y, float w, float h, float rx, float ry) {
292 | renderRoundRect(x, y, w, h, rx, ry, Paint.Style.FILL);
293 | }
294 | }
295 |
--------------------------------------------------------------------------------
/libtex/src/main/java/io/nano/tex/LaTeX.java:
--------------------------------------------------------------------------------
1 | package io.nano.tex;
2 |
3 | import android.content.Context;
4 |
5 | import io.nano.tex.res.ResManager;
6 |
7 | /**
8 | * Created by nano on 18-11-10
9 | */
10 | public final class LaTeX {
11 |
12 | private static boolean libLoaded = false;
13 | private static LaTeX instance;
14 |
15 | /**
16 | * Get the instance of the LaTeX engine.
17 | */
18 | public synchronized static LaTeX instance() {
19 | if (!libLoaded) {
20 | System.loadLibrary("tex");
21 | libLoaded = true;
22 | }
23 | if (instance == null) instance = new LaTeX();
24 | return instance;
25 | }
26 |
27 | private volatile boolean initialized = false;
28 | private volatile boolean isDebug = false;
29 |
30 | private LaTeX() {
31 | }
32 |
33 | /**
34 | * Initialize the LaTeX engine. Call of this function will copy the "TeX resources" from apk into the
35 | * data files directory of the host application, and parse the "TeX resources", it may takes long time,
36 | * you may call it from a background thread.
37 | */
38 | public synchronized void init(Context context) {
39 | ResManager rm = new ResManager(context);
40 | rm.unpackResources();
41 | boolean success = nInit(rm.getResourcesRootDirectory());
42 | if (!success) {
43 | throw new TeXException("Failed to initialize LaTeX engine.");
44 | }
45 | initialized = true;
46 | }
47 |
48 | /**
49 | * Check if the LaTeX engine is initialized.
50 | */
51 | public boolean isInitialized() {
52 | return initialized;
53 | }
54 |
55 | /**
56 | * Release the LaTeX engine.
57 | */
58 | public synchronized void release() {
59 | nFree();
60 | initialized = false;
61 | }
62 |
63 | private void check() {
64 | if (!initialized) throw new IllegalStateException(
65 | "The engine was not initialized, call init(Context) before use.");
66 | }
67 |
68 | /**
69 | * Parse a TeX formatted code with specified text size and foreground color.
70 | */
71 | public synchronized TeXRender parse(String ltx, float textSize, int foreground) {
72 | check();
73 | long ptr = nParse(ltx, 0, textSize, 0, foreground);
74 | if (ptr == 0) throw new TeXException("Failed to parse LaTeX: " + ltx);
75 | return new TeXRender(ptr);
76 | }
77 |
78 | /**
79 | * Parse a TeX code
80 | *
81 | * @param ltx the TeX formatted code
82 | * @param width the width of the 2D graphics context
83 | * @param textSize the text size to draw
84 | * @param lineSpace the space between two lines
85 | * @param foreground the foreground color
86 | */
87 | public synchronized TeXRender parse(
88 | String ltx, int width,
89 | float textSize, float lineSpace,
90 | int foreground) {
91 | check();
92 | long ptr = nParse(ltx, width, textSize, lineSpace, foreground);
93 | if (ptr == 0) throw new TeXException("Failed to parse LaTeX: " + ltx);
94 | // We got a very long formula, scale to fit the width
95 | TeXRender r = new TeXRender(ptr);
96 | if (r.getWidth() > width) {
97 | float w = r.getWidth();
98 | float scale = width / w;
99 | r.setTextSize(scale * textSize);
100 | }
101 | return r;
102 | }
103 |
104 | /**
105 | * Set if debug
106 | */
107 | public synchronized void setDebug(boolean debug) {
108 | nSetDebug(debug);
109 | isDebug = debug;
110 | }
111 |
112 | /**
113 | * Check if is in debug mode.
114 | */
115 | public boolean isDebug() {
116 | return isDebug;
117 | }
118 |
119 | private static native boolean nInit(String resDir);
120 |
121 | private static native void nFree();
122 |
123 | private static native long nParse(
124 | String ltx, int width,
125 | float textSize, float lineSpace,
126 | int foreground);
127 |
128 | private static native void nSetDebug(boolean debug);
129 | }
130 |
--------------------------------------------------------------------------------
/libtex/src/main/java/io/nano/tex/Rect.java:
--------------------------------------------------------------------------------
1 | package io.nano.tex;
2 |
3 | /**
4 | * Created by nano on 18-11-10
5 | */
6 | final class Rect {
7 |
8 | float x, y, w, h;
9 |
10 | Rect(float x, float y, float w, float h) {
11 | this.x = x;
12 | this.y = y;
13 | this.w = w;
14 | this.h = h;
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/libtex/src/main/java/io/nano/tex/TeXException.java:
--------------------------------------------------------------------------------
1 | package io.nano.tex;
2 |
3 | /**
4 | * Created by nano on 18-11-10
5 | */
6 | public class TeXException extends RuntimeException {
7 |
8 | public TeXException(String msg) {
9 | super(msg);
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/libtex/src/main/java/io/nano/tex/TeXRender.java:
--------------------------------------------------------------------------------
1 | package io.nano.tex;
2 |
3 | /**
4 | * Created by nano on 18-11-10
5 | */
6 | public final class TeXRender {
7 |
8 | /**
9 | * Delegate class to release native resources while finalize.
10 | */
11 | private static class Finalizer {
12 |
13 | private long nativePtr;
14 |
15 | Finalizer(long nativePtr) {
16 | this.nativePtr = nativePtr;
17 | }
18 |
19 | @Override
20 | protected void finalize() throws Throwable {
21 | if (nativePtr != 0) {
22 | nFinalize(nativePtr);
23 | nativePtr = 0;
24 | }
25 | super.finalize();
26 | }
27 | }
28 |
29 | private long nativePtr;
30 | private ActionRecorder recorder;
31 | private Finalizer finalizer;
32 |
33 | TeXRender(long nativePtr) {
34 | this.nativePtr = nativePtr;
35 | finalizer = new Finalizer(nativePtr);
36 | }
37 |
38 | /**
39 | * Get the text size
40 | */
41 | public float getTextSize() {
42 | return nGetTextSize(nativePtr);
43 | }
44 |
45 | /**
46 | * Get the height
47 | */
48 | public int getHeight() {
49 | return nGetHeight(nativePtr);
50 | }
51 |
52 | /**
53 | * Get the depth (descent in positive)
54 | */
55 | public int getDepth() {
56 | return nGetDepth(nativePtr);
57 | }
58 |
59 | public int getWidth() {
60 | return nGetWidth(nativePtr);
61 | }
62 |
63 | public float getBaseline() {
64 | return nGetBaseline(nativePtr);
65 | }
66 |
67 | /**
68 | * Set the text size
69 | */
70 | public void setTextSize(float size) {
71 | nSetTextSize(nativePtr, size);
72 | }
73 |
74 | /**
75 | * Set the foreground color
76 | */
77 | public void setForeground(int color) {
78 | // Cancel previous records
79 | recorder = null;
80 | nSetForeground(nativePtr, color);
81 | }
82 |
83 | /**
84 | * Set the width
85 | *
86 | * @param width the width, in pixel
87 | * @param align the alignment, must be one of the value defined in {@link Alignment}
88 | */
89 | public void setWidth(int width, int align) {
90 | nSetWidth(nativePtr, width, align);
91 | }
92 |
93 | /**
94 | * Set the height
95 | *
96 | * @param height the height, in pixel
97 | * @param align the alignment, must be one of the value defined in {@link Alignment}
98 | */
99 | public void setHeight(int height, int align) {
100 | nSetHeight(nativePtr, height, align);
101 | }
102 |
103 | /**
104 | * Draw the formula
105 | *
106 | * @param g2 the 2D graphics context
107 | * @param x the left position to draw
108 | * @param y the top position to draw
109 | */
110 | public void draw(Graphics2D g2, int x, int y) {
111 | if (recorder == null) {
112 | recorder = new ActionRecorder();
113 | nDraw(nativePtr, recorder, 0, 0);
114 | }
115 | recorder.setPosition(x, y);
116 | recorder.play(g2);
117 | }
118 |
119 | /**
120 | * Invalidate the drawing cache, refill the cache when next call of
121 | * {@link TeXRender#draw(Graphics2D, int, int)}
122 | */
123 | public void invalidateDrawingCache() {
124 | recorder = null;
125 | }
126 |
127 | private static native void nDraw(long ptr, ActionRecorder recorder, int x, int y);
128 |
129 | private static native float nGetTextSize(long ptr);
130 |
131 | private static native int nGetHeight(long ptr);
132 |
133 | private static native int nGetDepth(long ptr);
134 |
135 | private static native int nGetWidth(long ptr);
136 |
137 | private static native float nGetBaseline(long ptr);
138 |
139 | private static native void nSetTextSize(long ptr, float size);
140 |
141 | private static native void nSetForeground(long ptr, int color);
142 |
143 | private static native void nSetWidth(long ptr, int width, int align);
144 |
145 | private static native void nSetHeight(long ptr, int height, int align);
146 |
147 | private static native void nFinalize(long ptr);
148 | }
149 |
--------------------------------------------------------------------------------
/libtex/src/main/java/io/nano/tex/TextLayout.java:
--------------------------------------------------------------------------------
1 | package io.nano.tex;
2 |
3 | import android.graphics.Typeface;
4 | import android.text.TextPaint;
5 |
6 | /**
7 | * Created by nano on 18-11-10
8 | */
9 | public final class TextLayout {
10 |
11 | private static final TextPaint TMP_PAINT = new TextPaint();
12 | /**
13 | * Keep in sync with the size of TextRenderingBox::_font
14 | */
15 | private static final float FACTORED_TEXT_SIZE = 10.f;
16 |
17 | static {
18 | TMP_PAINT.setTextSize(FACTORED_TEXT_SIZE);
19 | }
20 |
21 | public static Rect getBounds(String txt, Font font) {
22 | Typeface oldTypeface = TMP_PAINT.getTypeface();
23 | TMP_PAINT.setTypeface(font.getTypeface());
24 | android.graphics.Rect ar = new android.graphics.Rect();
25 | TMP_PAINT.getTextBounds(txt, 0, txt.length(), ar);
26 | Rect r = new Rect(ar.left, ar.top, ar.width(), ar.height());
27 | // Reset typeface to avoid memory leak
28 | TMP_PAINT.setTypeface(oldTypeface);
29 | return r;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/libtex/src/main/java/io/nano/tex/res/ResManager.java:
--------------------------------------------------------------------------------
1 | package io.nano.tex.res;
2 |
3 | import android.content.Context;
4 | import android.util.Log;
5 |
6 | import java.io.BufferedOutputStream;
7 | import java.io.BufferedReader;
8 | import java.io.File;
9 | import java.io.FileOutputStream;
10 | import java.io.IOException;
11 | import java.io.InputStream;
12 | import java.io.InputStreamReader;
13 | import java.io.OutputStream;
14 | import java.util.ArrayList;
15 | import java.util.List;
16 |
17 | /**
18 | * Created by nano on 18-11-10
19 | */
20 | public final class ResManager {
21 |
22 | private static final String TAG = "ResManager";
23 |
24 | private String rootDir;
25 |
26 | public ResManager(Context context) {
27 | rootDir = context.getFilesDir().getPath() + File.separator + "tex";
28 | }
29 |
30 | public String getResourcesRootDirectory() {
31 | return rootDir;
32 | }
33 |
34 | private List listRes() {
35 | InputStream is = ResManager.class.getResourceAsStream("RES_README");
36 | BufferedReader in = new BufferedReader(new InputStreamReader(is));
37 | String line;
38 | List res = new ArrayList<>();
39 | try {
40 | while ((line = in.readLine()) != null) res.add(line);
41 | } catch (IOException e) {
42 | Log.e(TAG, "Failed to read resources", e);
43 | } finally {
44 | try {
45 | in.close();
46 | } catch (IOException e) {
47 | Log.e(TAG, "Failed to close resources file.", e);
48 | }
49 | }
50 | return res;
51 | }
52 |
53 | public void unpackResources() {
54 | List res = listRes();
55 | File root = new File(rootDir);
56 | if (!root.exists()) root.mkdirs();
57 |
58 | for (String path : res) {
59 | File file = new File(rootDir + File.separator + path);
60 | if (file.exists()) continue;
61 | int li = path.lastIndexOf(File.separator);
62 | if (li >= 0) {
63 | String dir = path.substring(0, li);
64 | File f = new File(rootDir + File.separator + dir);
65 | if (!f.exists()) f.mkdirs();
66 | }
67 | String p = rootDir + File.separator + path;
68 | InputStream is = ResManager.class.getResourceAsStream(path);
69 | Log.i(TAG, "Copy resource: " + path);
70 | copyTo(is, p);
71 | }
72 | }
73 |
74 | private static void copyTo(InputStream is, String targetPath) {
75 | OutputStream os = null;
76 | try {
77 | byte[] buffer = new byte[2048];
78 | os = new BufferedOutputStream(new FileOutputStream(targetPath));
79 | int l;
80 | while ((l = is.read(buffer)) > 0) os.write(buffer, 0, l);
81 | os.flush();
82 | } catch (Exception e) {
83 | Log.e(TAG, "Copy resource failed", e);
84 | } finally {
85 | try {
86 | is.close();
87 | if (os != null) os.close();
88 | } catch (IOException e) {
89 | Log.e(TAG, "Copy resource failed", e);
90 | }
91 | }
92 | }
93 | }
94 |
--------------------------------------------------------------------------------
/libtex/src/main/jni/Android.mk:
--------------------------------------------------------------------------------
1 | LOCAL_PATH := $(call my-dir)
2 |
3 | include $(CLEAR_VARS)
4 |
5 | LOCAL_LDLIBS := -lm -llog
6 |
7 | LOCAL_CFLAGS := \
8 | -D__GXX_EXPERIMENTAL_CXX0X__ \
9 | -fvisibility=hidden \
10 | -ffunction-sections \
11 | -fdata-sections \
12 | -Os
13 |
14 | LOCAL_CPPFLAGS := \
15 | -std=gnu++0x \
16 | -fvisibility=hidden \
17 | -ffunction-sections \
18 | -fdata-sections \
19 | -Os
20 |
21 | LOCAL_LDFLAGS := -Wl,--gc-sections
22 |
23 | LOCAL_C_INCLUDES := $(LOCAL_PATH)/tex/src $(LOCAL_PATH)/port
24 |
25 | # Traverse all the directory and subdirectory
26 | define walk
27 | $(wildcard $(1)) $(foreach e, $(wildcard $(1)/*), $(call walk, $(e)))
28 | endef
29 |
30 | # Find all the file recursively under directory jni/
31 | ALLFILES = $(call walk, $(LOCAL_PATH))
32 | SRC_FILE_LIST = $(filter %.cpp, $(ALLFILES))
33 |
34 | $(info [$(TARGET_ARCH_ABI)] source files are:)
35 | $(foreach f, $(SRC_FILE_LIST), $(info $(f)))
36 |
37 | LOCAL_MODULE := tex
38 | LOCAL_SRC_FILES := $(SRC_FILE_LIST:$(LOCAL_PATH)/%=%)
39 |
40 | include $(BUILD_SHARED_LIBRARY)
41 |
--------------------------------------------------------------------------------
/libtex/src/main/jni/Application.mk:
--------------------------------------------------------------------------------
1 | APP_STL := c++_static
2 | APP_CPPFLAGS += -fexceptions -frtti
3 | APP_OPTIM := release
4 | APP_ABI := armeabi-v7a arm64-v8a
5 |
--------------------------------------------------------------------------------
/libtex/src/main/jni/port/graphics_android.cpp:
--------------------------------------------------------------------------------
1 | #include "config.h"
2 |
3 | #ifdef __OS_Android__
4 |
5 | #include "jni_def.h"
6 | #include "jni_log.h"
7 |
8 | #include "common.h"
9 | #include "graphics_android.h"
10 |
11 | #include
12 |
13 | using namespace tex;
14 | using namespace std;
15 |
16 | /******************************************* Android Font *****************************************/
17 |
18 | static void _delete_java_ref(jobject ptr) {
19 | JNIEnv* env = getJNIEnv();
20 | env->DeleteGlobalRef(ptr);
21 | LOGI("Delete global java ref: %p", ptr);
22 | }
23 |
24 | void Font_Android::setSize(float size) {
25 | _size = size;
26 | }
27 |
28 | void Font_Android::setJavaFont(jobject font) {
29 | jobject ref = getJNIEnv()->NewGlobalRef(font);
30 | _javaFont = shared_ptr<_jobject>(ref, _delete_java_ref);
31 | }
32 |
33 | shared_ptr<_jobject> Font_Android::getJavaFont() const {
34 | return _javaFont;
35 | }
36 |
37 | float Font_Android::getSize() const {
38 | return _size;
39 | }
40 |
41 | shared_ptr Font_Android::deriveFont(int style) const {
42 | Font_Android* f = new Font_Android();
43 | JNIEnv* env = getJNIEnv();
44 | jobject obj = env->CallObjectMethod(_javaFont.get(), gMethodDeriveFont, style);
45 | f->_size = _size;
46 | if (env->IsSameObject(_javaFont.get(), obj)) {
47 | f->_javaFont = _javaFont;
48 | } else {
49 | f->setJavaFont(obj);
50 | }
51 | LOGI("Derive font, java font: %p, style: %d, derived java font: %p",
52 | _javaFont.get(), style, f->_javaFont.get());
53 | return shared_ptr(f);
54 | }
55 |
56 | bool Font_Android::operator==(const Font& f) const {
57 | return _javaFont.get() == static_cast(f)._javaFont.get();
58 | }
59 |
60 | bool Font_Android::operator!=(const Font& f) const {
61 | return !(*this == f);
62 | }
63 |
64 | Font* Font::create(const string& file, float size) {
65 | Font_Android* f = new Font_Android();
66 | JNIEnv* env = getJNIEnv();
67 | jstring str = env->NewStringUTF(file.c_str());
68 | jobject obj = env->CallStaticObjectMethod(
69 | gClassFont, gMethodCreateFontFromFile, str, size);
70 | f->setSize(size);
71 | f->setJavaFont(obj);
72 | env->DeleteLocalRef(str);
73 | return f;
74 | }
75 |
76 | shared_ptr Font::_create(const string& name, int style, float size) {
77 | Font_Android* f = new Font_Android();
78 | JNIEnv* env = getJNIEnv();
79 | jstring str = env->NewStringUTF(name.c_str());
80 | jobject obj = env->CallStaticObjectMethod(
81 | gClassFont, gMethodCreateFontFromName, str, style, size);
82 | f->setSize(size);
83 | f->setJavaFont(obj);
84 | env->DeleteLocalRef(str);
85 | return shared_ptr(f);
86 | }
87 |
88 | /******************************************* Text layout ******************************************/
89 |
90 | void TextLayout_Android::getBounds(_out_ Rect& bounds) {
91 | JNIEnv* env = getJNIEnv();
92 | shared_ptr<_jobject> jfont = static_cast(_font.get())->getJavaFont();
93 | jstring str = env->NewStringUTF(wide2utf8(_txt.c_str()).c_str());
94 | jobject obj = env->CallStaticObjectMethod(
95 | gClassTextLayout, gMethodGetBounds, str, jfont.get());
96 | bounds.x = env->GetFloatField(obj, gFieldRectX);
97 | bounds.y = env->GetFloatField(obj, gFieldRectY);
98 | bounds.w = env->GetFloatField(obj, gFieldRectW);
99 | bounds.h = env->GetFloatField(obj, gFieldRectH);
100 |
101 | env->DeleteLocalRef(str);
102 | env->DeleteLocalRef(obj);
103 |
104 | LOGI("TextLayout::getBounds: [%.2f, %.2f, %.2f, %.2f]", bounds.x, bounds.y, bounds.w, bounds.h);
105 | }
106 |
107 | void TextLayout_Android::draw(Graphics2D& g2, float x, float y) {
108 | const Font* oldFont = g2.getFont();
109 | g2.setFont(_font.get());
110 | string str = wide2utf8(_txt.c_str());
111 | LOGI("TextLayout::draw, text: %s", str.c_str());
112 | g2.drawText(_txt, x, y);
113 | g2.setFont(oldFont);
114 | }
115 |
116 | shared_ptr TextLayout::create(const wstring& txt, const shared_ptr& font) {
117 | return shared_ptr(new TextLayout_Android(txt, font));
118 | }
119 |
120 | /******************************************* Graphics 2D ******************************************/
121 |
122 | /**
123 | * Keep in sync with io/nano/tex/ActionRecorder
124 | */
125 | enum Action {
126 | ACT_setFont,
127 | ACT_setColor,
128 | ACT_setStrokeWidth,
129 | ACT_setStroke,
130 | ACT_translate,
131 | ACT_scale,
132 | ACT_rotate,
133 | ACT_reset,
134 | ACT_drawChar,
135 | ACT_drawText,
136 | ACT_drawLine,
137 | ACT_drawRect,
138 | ACT_fillRect,
139 | ACT_drawRoundRect,
140 | ACT_fillRoundRect
141 | };
142 |
143 | enum AffineTransformIndex {
144 | SX,
145 | SY,
146 | TX,
147 | TY,
148 | R,
149 | PX,
150 | PY
151 | };
152 |
153 | Graphics2D_Android::Graphics2D_Android(jobject jrecorder) : _font(nullptr), _stroke() {
154 | _t = new float[9]();
155 | _t[SX] = _t[SY] = 1;
156 | _color = black;
157 | JNIEnv* env = getJNIEnv();
158 | _jrecorder = env->NewGlobalRef(jrecorder);
159 | }
160 |
161 | Graphics2D_Android::~Graphics2D_Android() {
162 | delete _t;
163 | JNIEnv* env = getJNIEnv();
164 | env->DeleteGlobalRef(_jrecorder);
165 | }
166 |
167 | void Graphics2D_Android::makeRecord(int action, jobject arg, const jfloat* args, int argsLen) {
168 | jfloatArray arr = 0;
169 | JNIEnv* env = getJNIEnv();
170 | if (argsLen != 0) {
171 | arr = env->NewFloatArray(argsLen);
172 | env->SetFloatArrayRegion(arr, 0, argsLen, args);
173 | }
174 | env->CallVoidMethod(_jrecorder, gMethodRecord, action, arg, arr);
175 | if (arr) env->DeleteLocalRef(arr);
176 | }
177 |
178 | void Graphics2D_Android::setColor(color c) {
179 | _color = c;
180 | jfloat p[] = {static_cast((int)c)};
181 | makeRecord(ACT_setColor, NULL, p, 1);
182 | }
183 |
184 | color Graphics2D_Android::getColor() const {
185 | return _color;
186 | }
187 |
188 | void Graphics2D_Android::setStroke(const Stroke& s) {
189 | _stroke = s;
190 | jfloat p[] = {
191 | s.lineWidth,
192 | s.miterLimit,
193 | static_cast(s.cap),
194 | static_cast(s.join)};
195 | makeRecord(ACT_setStroke, NULL, p, 4);
196 | }
197 |
198 | const Stroke& Graphics2D_Android::getStroke() const {
199 | return _stroke;
200 | }
201 |
202 | void Graphics2D_Android::setStrokeWidth(float w) {
203 | _stroke.lineWidth = w;
204 | jfloat p[] = {w};
205 | makeRecord(ACT_setStrokeWidth, NULL, p, 1);
206 | }
207 |
208 | const Font* Graphics2D_Android::getFont() const {
209 | return _font;
210 | }
211 |
212 | void Graphics2D_Android::setFont(const Font* font) {
213 | _font = font;
214 | if (font == nullptr) {
215 | makeRecord(ACT_setFont, NULL, NULL, 0);
216 | return;
217 | }
218 | const Font_Android* f = static_cast(font);
219 | makeRecord(ACT_setFont, f->getJavaFont().get(), NULL, 0);
220 | }
221 |
222 | void Graphics2D_Android::translate(float dx, float dy) {
223 | _t[TX] += _t[SX] * dx;
224 | _t[TY] += _t[SY] * dy;
225 | jfloat p[] = {dx, dy};
226 | makeRecord(ACT_translate, NULL, p, 2);
227 | }
228 |
229 | void Graphics2D_Android::scale(float sx, float sy) {
230 | _t[SX] *= sx;
231 | _t[SY] *= sy;
232 | jfloat p[] = {sx, sy};
233 | makeRecord(ACT_scale, NULL, p, 2);
234 | }
235 |
236 | void Graphics2D_Android::rotate(float angle) {
237 | rotate(angle, 0, 0);
238 | }
239 |
240 | void Graphics2D_Android::rotate(float angle, float px, float py) {
241 | float r = (float)(angle / PI * 180);
242 | _t[R] += r;
243 | _t[PX] = px * _t[SX] + _t[TX];
244 | _t[PY] = py * _t[SY] + _t[TY];
245 | jfloat p[] = {angle, px, py};
246 | makeRecord(ACT_rotate, NULL, p, 3);
247 | }
248 |
249 | void Graphics2D_Android::reset() {
250 | memset(_t, 0, sizeof(float) * 9);
251 | _t[SX] = _t[SY] = 1;
252 | makeRecord(ACT_reset, NULL, NULL, 0);
253 | }
254 |
255 | float Graphics2D_Android::sx() const {
256 | return _t[SX];
257 | }
258 |
259 | float Graphics2D_Android::sy() const {
260 | return _t[SY];
261 | }
262 |
263 | void Graphics2D_Android::drawChar(wchar_t c, float x, float y) {
264 | jfloat p[] = {static_cast(c), x, y};
265 | makeRecord(ACT_drawChar, NULL, p, 3);
266 | }
267 |
268 | void Graphics2D_Android::drawText(const wstring& c, float x, float y) {
269 | string str = wide2utf8(c.c_str());
270 | JNIEnv* env = getJNIEnv();
271 | jstring jstr = env->NewStringUTF(str.c_str());
272 | jfloat p[] = {x, y};
273 | makeRecord(ACT_drawText, jstr, p, 2);
274 | env->DeleteLocalRef(jstr);
275 | }
276 |
277 | void Graphics2D_Android::drawLine(float x1, float y1, float x2, float y2) {
278 | jfloat p[] = {x1, y1, x2, y2};
279 | makeRecord(ACT_drawLine, NULL, p, 4);
280 | }
281 |
282 | void Graphics2D_Android::drawRect(float x, float y, float w, float h) {
283 | jfloat p[] = {x, y, w, h};
284 | makeRecord(ACT_drawRect, NULL, p, 4);
285 | }
286 |
287 | void Graphics2D_Android::fillRect(float x, float y, float w, float h) {
288 | jfloat p[] = {x, y, w, h};
289 | makeRecord(ACT_fillRect, NULL, p, 4);
290 | }
291 |
292 | void Graphics2D_Android::drawRoundRect(float x, float y, float w, float h, float rx, float ry) {
293 | jfloat p[] = {x, y, w, h, rx, ry};
294 | makeRecord(ACT_drawRoundRect, NULL, p, 6);
295 | }
296 |
297 | void Graphics2D_Android::fillRoundRect(float x, float y, float w, float h, float rx, float ry) {
298 | jfloat p[] = {x, y, w, h, rx, ry};
299 | makeRecord(ACT_fillRoundRect, NULL, p, 6);
300 | }
301 |
302 | #endif // __OS_Android__
303 |
--------------------------------------------------------------------------------
/libtex/src/main/jni/port/graphics_android.h:
--------------------------------------------------------------------------------
1 | #include "config.h"
2 |
3 | #ifdef __OS_Android__
4 |
5 | #ifndef GRAPHICS_ANDROID_INCLUDED
6 | #define GRAPHICS_ANDROID_INCLUDED
7 |
8 | #include
9 | #include "graphic/graphic.h"
10 |
11 | using namespace tex;
12 |
13 | class Font_Android : public Font {
14 | private:
15 | float _size;
16 | shared_ptr<_jobject> _javaFont;
17 |
18 | Font_Android(const Font_Android&);
19 | void operator=(const Font_Android&);
20 |
21 | public:
22 | Font_Android() : _size(1), _javaFont(nullptr) {}
23 |
24 | void setSize(float size);
25 | void setJavaFont(jobject font);
26 | shared_ptr<_jobject> getJavaFont() const;
27 |
28 | virtual float getSize() const override;
29 | virtual shared_ptr deriveFont(int style) const override;
30 | virtual bool operator==(const Font& f) const override;
31 | virtual bool operator!=(const Font& f) const override;
32 | };
33 |
34 | class TextLayout_Android : public TextLayout {
35 | private:
36 | shared_ptr _font;
37 | const wstring _txt;
38 |
39 | TextLayout_Android(const TextLayout_Android&);
40 | void operator=(const TextLayout_Android&);
41 |
42 | public:
43 | TextLayout_Android(const wstring& txt, const shared_ptr font)
44 | : _txt(txt), _font(font) {}
45 |
46 | virtual void getBounds(_out_ Rect& bounds) override;
47 | virtual void draw(Graphics2D& g2, float x, float y) override;
48 | };
49 |
50 | class Graphics2D_Android : public Graphics2D {
51 | private:
52 | jobject _jrecorder;
53 | float* _t;
54 | color _color;
55 | const Font* _font;
56 | Stroke _stroke;
57 |
58 | void makeRecord(int action, jobject arg, const jfloat* args, int argsLen);
59 |
60 | Graphics2D_Android(const Graphics2D_Android&);
61 | void operator=(const Graphics2D_Android&);
62 |
63 | public:
64 | Graphics2D_Android(jobject jrecorder);
65 |
66 | ~Graphics2D_Android();
67 |
68 | virtual void setColor(color c) override;
69 | virtual color getColor() const override;
70 | virtual void setStroke(const Stroke& s) override;
71 | virtual const Stroke& getStroke() const override;
72 | virtual void setStrokeWidth(float w) override;
73 | virtual const Font* getFont() const override;
74 | virtual void setFont(const Font* font) override;
75 | virtual void translate(float dx, float dy) override;
76 | virtual void scale(float sx, float sy) override;
77 | virtual void rotate(float angle) override;
78 | virtual void rotate(float angle, float px, float py) override;
79 | virtual void reset() override;
80 | virtual float sx() const override;
81 | virtual float sy() const override;
82 | virtual void drawChar(wchar_t c, float x, float y) override;
83 | virtual void drawText(const wstring& c, float x, float y) override;
84 | virtual void drawLine(float x1, float y1, float x2, float y2) override;
85 | virtual void drawRect(float x, float y, float w, float h) override;
86 | virtual void fillRect(float x, float y, float w, float h) override;
87 | virtual void drawRoundRect(float x, float y, float w, float h, float rx, float ry) override;
88 | virtual void fillRoundRect(float x, float y, float w, float h, float rx, float ry) override;
89 | };
90 |
91 | #endif // GRAPHICS_ANDROID_INCLUDED
92 | #endif // __OS_Android__
93 |
--------------------------------------------------------------------------------
/libtex/src/main/jni/port/jni_def.cpp:
--------------------------------------------------------------------------------
1 | #include "jni_def.h"
2 | #include "jni_log.h"
3 |
4 | JavaVM* gJVM;
5 |
6 | /** io/nano/tex/Rect */
7 | jfieldID gFieldRectX, gFieldRectY, gFieldRectW, gFieldRectH;
8 |
9 | /** io/nano/tex/TextLayout */
10 | jclass gClassTextLayout;
11 | jmethodID gMethodGetBounds;
12 |
13 | /** io/nano/tex/Font */
14 | jclass gClassFont;
15 | jmethodID gMethodDeriveFont;
16 | jmethodID gMethodCreateFontFromName;
17 | jmethodID gMethodCreateFontFromFile;
18 |
19 | /** io/nano/tex/ActionRecorder */
20 | jmethodID gMethodRecord;
21 |
22 | JNIEnv* getJNIEnv() {
23 | JNIEnv* env = 0;
24 | gJVM->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_6);
25 | return env;
26 | }
27 |
28 | static void load(JNIEnv* env) {
29 | // io/nano/tex/Rect
30 | jclass rect = env->FindClass("io/nano/tex/Rect");
31 | gFieldRectX = env->GetFieldID(rect, "x", "F");
32 | gFieldRectY = env->GetFieldID(rect, "y", "F");
33 | gFieldRectW = env->GetFieldID(rect, "w", "F");
34 | gFieldRectH = env->GetFieldID(rect, "h", "F");
35 | // io/nano/tex/TextLayout
36 | jclass layout = env->FindClass("io/nano/tex/TextLayout");
37 | gMethodGetBounds = env->GetStaticMethodID(
38 | layout,
39 | "getBounds",
40 | "(Ljava/lang/String;Lio/nano/tex/Font;)Lio/nano/tex/Rect;");
41 | gClassTextLayout = (jclass)env->NewGlobalRef(layout);
42 | // io/nano/tex/Font
43 | jclass font = env->FindClass("io/nano/tex/Font");
44 | gClassFont = (jclass)env->NewGlobalRef(font);
45 | gMethodDeriveFont = env->GetMethodID(
46 | gClassFont,
47 | "deriveFont",
48 | "(I)Lio/nano/tex/Font;");
49 | gMethodCreateFontFromName = env->GetStaticMethodID(
50 | gClassFont,
51 | "create",
52 | "(Ljava/lang/String;IF)Lio/nano/tex/Font;");
53 | gMethodCreateFontFromFile = env->GetStaticMethodID(
54 | gClassFont,
55 | "create",
56 | "(Ljava/lang/String;F)Lio/nano/tex/Font;");
57 | // io/nano/tex/ActionRecorder
58 | jclass recorder = env->FindClass("io/nano/tex/ActionRecorder");
59 | gMethodRecord = env->GetMethodID(
60 | recorder,
61 | "record",
62 | "(ILjava/lang/Object;[F)V");
63 | }
64 |
65 | extern int registerLaTeX(JNIEnv* env);
66 | extern int registerTeXRender(JNIEnv* env);
67 |
68 | extern "C" JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved) {
69 | gJVM = vm;
70 |
71 | LOGI("Load jni, initialize java methods...");
72 |
73 | JNIEnv* env = 0;
74 | vm->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_6);
75 |
76 | registerLaTeX(env);
77 | registerTeXRender(env);
78 |
79 | load(env);
80 |
81 | return JNI_VERSION_1_6;
82 | }
83 |
--------------------------------------------------------------------------------
/libtex/src/main/jni/port/jni_def.h:
--------------------------------------------------------------------------------
1 | #ifndef JNI_DEF_INCLUDED
2 | #define JNI_DEF_INCLUDED
3 |
4 | #include
5 |
6 | #ifdef __cplusplus
7 | extern "C" {
8 | #endif
9 |
10 | /** io/nano/tex/Rect */
11 | extern jfieldID gFieldRectX, gFieldRectY, gFieldRectW, gFieldRectH;
12 |
13 | /** io/nano/tex/TextLayout */
14 | extern jclass gClassTextLayout;
15 | extern jmethodID gMethodGetBounds;
16 |
17 | /** io/nano/tex/Font */
18 | extern jclass gClassFont;
19 | extern jmethodID gMethodDeriveFont;
20 | extern jmethodID gMethodCreateFontFromName;
21 | extern jmethodID gMethodCreateFontFromFile;
22 |
23 | /** io/nano/tex/ActionRecorder */
24 | extern jmethodID gMethodRecord;
25 |
26 | #ifdef __cplusplus
27 | }
28 | #endif
29 |
30 | /** Get the jni environment */
31 | JNIEnv* getJNIEnv();
32 |
33 | #endif // JNI_DEF_INCLUDED
34 |
--------------------------------------------------------------------------------
/libtex/src/main/jni/port/jni_help.cpp:
--------------------------------------------------------------------------------
1 | #include "jni_help.h"
2 | #include "jni_log.h"
3 |
4 | #include
5 |
6 | template
7 | class scoped_local_ref {
8 | private:
9 | C_JNIEnv* _env;
10 | T _localRef;
11 |
12 | scoped_local_ref(const scoped_local_ref&);
13 | void operator=(const scoped_local_ref&);
14 |
15 | public:
16 | scoped_local_ref(C_JNIEnv* env, T localRef = nullptr)
17 | : _env(env), _localRef(localRef) {}
18 |
19 | void reset(T localRef = nullptr) {
20 | if (_localRef != nullptr) {
21 | (*_env)->DeleteLocalRef(reinterpret_cast(_env), _localRef);
22 | _localRef = nullptr;
23 | }
24 | }
25 |
26 | T get() const {
27 | return _localRef;
28 | }
29 |
30 | ~scoped_local_ref() {
31 | reset();
32 | }
33 | };
34 |
35 | static jclass findClass(C_JNIEnv* env, const char* className) {
36 | JNIEnv* e = reinterpret_cast(env);
37 | return (*env)->FindClass(e, className);
38 | }
39 |
40 | extern "C" int jniRegisterNativeMethods(
41 | C_JNIEnv* env, const char* className,
42 | const JNINativeMethod* gMethods, int numMethods) {
43 | JNIEnv* e = reinterpret_cast(env);
44 |
45 | LOGI("Registering %s's %d native methods...", className, numMethods);
46 |
47 | scoped_local_ref c(env, findClass(env, className));
48 | if (c.get() == NULL) {
49 | char* msg;
50 | asprintf(&msg, "Native registration unable to find class '%s'; aborting...", className);
51 | e->FatalError(msg);
52 | }
53 |
54 | if ((*env)->RegisterNatives(e, c.get(), gMethods, numMethods) < 0) {
55 | char* msg;
56 | asprintf(&msg, "RegisterNatives failed for '%s'; aborting...", className);
57 | e->FatalError(msg);
58 | }
59 |
60 | return 0;
61 | }
62 |
--------------------------------------------------------------------------------
/libtex/src/main/jni/port/jni_help.h:
--------------------------------------------------------------------------------
1 | #ifndef JNI_HELP_INCLUDED
2 | #define JNI_HELP_INCLUDED
3 |
4 | #include
5 |
6 | #ifndef NELEM
7 | #define NELEM(x) ((int)(sizeof(x) / sizeof((x)[0])))
8 | #endif
9 |
10 | #ifdef __cplusplus
11 | extern "C" {
12 | #endif
13 |
14 | /*
15 | * Register one or more native methods with a particular class.
16 | * "className" looks like "java/lang/String". Aborts on failure.
17 | * TODO: fix all callers and change the return type to void.
18 | */
19 | int jniRegisterNativeMethods(
20 | C_JNIEnv* env, const char* className,
21 | const JNINativeMethod* gMethods, int numMethods);
22 |
23 | #ifdef __cplusplus
24 | }
25 | #endif
26 |
27 | #if defined(__cplusplus)
28 | inline int jniRegisterNativeMethods(
29 | JNIEnv* env, const char* className,
30 | const JNINativeMethod* gMethods, int numMethods) {
31 | return jniRegisterNativeMethods(&env->functions, className, gMethods, numMethods);
32 | }
33 | #endif
34 |
35 | #endif // JNI_HELP_INCLUDED
36 |
--------------------------------------------------------------------------------
/libtex/src/main/jni/port/jni_latex.cpp:
--------------------------------------------------------------------------------
1 | #include "jni_def.h"
2 | #include "jni_help.h"
3 | #include "jni_log.h"
4 | #include "latex.h"
5 |
6 | #include
7 | #include
8 |
9 | using namespace std;
10 | using namespace tex;
11 |
12 | static jboolean LaTeX_init(JNIEnv* env, jclass clazz, jstring resDir) {
13 | try {
14 | const char* rootDir = env->GetStringUTFChars(resDir, NULL);
15 | LOGI("Resources root dir: %s, initialize now...", rootDir);
16 | LaTeX::init(rootDir);
17 | env->ReleaseStringUTFChars(resDir, rootDir);
18 | LOGI("Initialized successfully.");
19 | return true;
20 | } catch (ex_tex& e) {
21 | LOGE("Failed to initialize the LaTeX engine, caused by: %s", e.what());
22 | return false;
23 | }
24 | }
25 |
26 | static void LaTeX_release(JNIEnv* env, jclass clazz) {
27 | LOGI("Release LaTeX engine...");
28 | LaTeX::release();
29 | }
30 |
31 | static jlong LaTeX_parse(
32 | JNIEnv* env, jclass clazz,
33 | jstring ltx, jint width, jfloat textSize, jfloat lineSpace, jint foreground) {
34 | wstring value;
35 | const jchar* raw = env->GetStringChars(ltx, NULL);
36 | size_t len = env->GetStringLength(ltx);
37 | value.assign(raw, raw + len);
38 | env->ReleaseStringChars(ltx, raw);
39 | const char* str = env->GetStringUTFChars(ltx, NULL);
40 | LOGI("Parse: %s", str);
41 | env->ReleaseStringUTFChars(ltx, str);
42 | try {
43 | TeXRender* r = LaTeX::parse(value, width, textSize, lineSpace, foreground);
44 | return reinterpret_cast(r);
45 | } catch (exception& e) {
46 | LOGE("Failed to parse LaTeX, caused by: %s", e.what());
47 | return 0;
48 | }
49 | }
50 |
51 | static void LaTeX_setDebug(JNIEnv* env, jclass clazz, jboolean debug) {
52 | bool b = static_cast(debug);
53 | LaTeX::setDebug(b);
54 | }
55 |
56 | static JNINativeMethod sMethods[] = {
57 | {"nInit", "(Ljava/lang/String;)Z", (void*)LaTeX_init},
58 | {"nFree", "()V", (void*)LaTeX_release},
59 | {"nParse", "(Ljava/lang/String;IFFI)J", (void*)LaTeX_parse},
60 | {"nSetDebug", "(Z)V", (void*)LaTeX_setDebug}};
61 |
62 | int registerLaTeX(JNIEnv* env) {
63 | return jniRegisterNativeMethods(
64 | env, "io/nano/tex/LaTeX", sMethods, NELEM(sMethods));
65 | }
66 |
--------------------------------------------------------------------------------
/libtex/src/main/jni/port/jni_log.h:
--------------------------------------------------------------------------------
1 | #ifndef JNI_LOG_H_INCLUDED
2 | #define JNI_LOG_H_INCLUDED
3 |
4 | #include
5 | #include
6 | #define __JNI_DEBUG
7 | #define LOG_TAG "tex"
8 |
9 | #ifndef LOGD
10 | #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
11 | #endif
12 |
13 | #ifndef LOGE
14 | #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
15 | #endif
16 |
17 | #ifndef LOGI
18 | #define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
19 | #endif
20 |
21 | #endif // JNI_LOG_H_INCLUDED
22 |
--------------------------------------------------------------------------------
/libtex/src/main/jni/port/jni_render.cpp:
--------------------------------------------------------------------------------
1 | #include "config.h"
2 |
3 | #ifdef __OS_Android__
4 |
5 | #include "graphics_android.h"
6 | #include "jni_def.h"
7 | #include "jni_help.h"
8 | #include "jni_log.h"
9 |
10 | #include "latex.h"
11 |
12 | using namespace tex;
13 |
14 | static void TeXRender_draw(
15 | JNIEnv* env, jclass clazz,
16 | jlong ptr, jobject recorder, jint x, jint y) {
17 | TeXRender* r = reinterpret_cast(ptr);
18 | LOGI("Draw: %p, in position (%d, %d), with recorder: %p", r, x, y, recorder);
19 | Graphics2D_Android g2(recorder);
20 | r->draw(g2, x, y);
21 | }
22 |
23 | static jfloat TeXRender_getTextSize(JNIEnv* env, jclass clazz, jlong ptr) {
24 | TeXRender* r = reinterpret_cast(ptr);
25 | return r->getTextSize();
26 | }
27 |
28 | static jint TeXRender_getHeight(JNIEnv* env, jclass clazz, jlong ptr) {
29 | TeXRender* r = reinterpret_cast(ptr);
30 | return r->getHeight();
31 | }
32 |
33 | static jint TeXRender_getDepth(JNIEnv* env, jclass clazz, jlong ptr) {
34 | TeXRender* r = reinterpret_cast(ptr);
35 | return r->getDepth();
36 | }
37 |
38 | static jint TeXRender_getWidth(JNIEnv* env, jclass clazz, jlong ptr) {
39 | TeXRender* r = reinterpret_cast(ptr);
40 | return r->getWidth();
41 | }
42 |
43 | static jfloat TeXRender_getBaseline(JNIEnv* env, jclass clazz, jlong ptr) {
44 | TeXRender* r = reinterpret_cast(ptr);
45 | return r->getBaseline();
46 | }
47 |
48 | static void TeXRender_setTextSize(JNIEnv* env, jclass clazz, jlong ptr, jfloat size) {
49 | TeXRender* r = reinterpret_cast(ptr);
50 | r->setTextSize((float)size);
51 | }
52 |
53 | static void TeXRender_setForeground(JNIEnv* env, jclass clazz, jlong ptr, jint c) {
54 | TeXRender* r = reinterpret_cast(ptr);
55 | r->setForeground((color)c);
56 | }
57 |
58 | static void TeXRender_setWidth(JNIEnv* env, jclass clazz, jlong ptr, jint width, jint align) {
59 | TeXRender* r = reinterpret_cast(ptr);
60 | r->setWidth(width, align);
61 | }
62 |
63 | static void TeXRender_setHeight(JNIEnv* env, jclass clazz, jlong ptr, jint height, jint align) {
64 | TeXRender* r = reinterpret_cast(ptr);
65 | r->setHeight(height, align);
66 | }
67 |
68 | static void TeXRender_finalize(JNIEnv* env, jclass clazz, jlong ptr) {
69 | TeXRender* r = reinterpret_cast(ptr);
70 | LOGI("TeXRender finalize: %p", r);
71 | delete r;
72 | }
73 |
74 | static JNINativeMethod sMethods[] = {
75 | {"nDraw", "(JLio/nano/tex/ActionRecorder;II)V", (void*)TeXRender_draw},
76 | {"nGetTextSize", "(J)F", (void*)TeXRender_getTextSize},
77 | {"nGetHeight", "(J)I", (void*)TeXRender_getHeight},
78 | {"nGetDepth", "(J)I", (void*)TeXRender_getDepth},
79 | {"nGetWidth", "(J)I", (void*)TeXRender_getWidth},
80 | {"nGetBaseline", "(J)F", (void*)TeXRender_getBaseline},
81 | {"nSetTextSize", "(JF)V", (void*)TeXRender_setTextSize},
82 | {"nSetForeground", "(JI)V", (void*)TeXRender_setForeground},
83 | {"nSetWidth", "(JII)V", (void*)TeXRender_setWidth},
84 | {"nSetHeight", "(JII)V", (void*)TeXRender_setHeight},
85 | {"nFinalize", "(J)V", (void*)TeXRender_finalize}};
86 |
87 | int registerTeXRender(JNIEnv* env) {
88 | return jniRegisterNativeMethods(
89 | env, "io/nano/tex/TeXRender", sMethods, NELEM(sMethods));
90 | }
91 |
92 | #endif // __OS_Android__
93 |
--------------------------------------------------------------------------------
/libtex/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | libtex
3 |
4 |
--------------------------------------------------------------------------------
/readme/example.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NanoMichael/AndroidLaTeXMath/c0159021c7349656b38bb4a702234f4ccc76d4d3/readme/example.jpg
--------------------------------------------------------------------------------
/readme/logo.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app', ':libtex'
2 |
--------------------------------------------------------------------------------