This commit is contained in:
Brian Mwadime 2016-07-11 08:19:26 +03:00
Родитель 168f6c0d50
Коммит b523f9d4b5
51 изменённых файлов: 1251 добавлений и 5 удалений

Просмотреть файл

@ -54,7 +54,7 @@ android {
}
dependencies {
// compile fileTree(dir: 'libs', include: ['*.jar'])
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
// Android support libraries.
@ -73,9 +73,10 @@ dependencies {
compile 'com.google.guava:guava:18.0'
// Helps with displaying complex html tags
compile 'org.sufficientlysecure:html-textview:1.6'
// compile 'org.sufficientlysecure:html-textview:1.6'
compile project(":third_party:HtmlTextView")
// For Displaying gifs
compile 'pl.droidsonroids.gif:android-gif-drawable:1.1.16'
}
apply from: "../artifacts.gradle"
apply from: "../artifacts.gradle"

Двоичные данные
app/src/main/res/drawable-nodpi/1f60a.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 3.7 KiB

Двоичные данные
app/src/main/res/drawable-nodpi/1f60b.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 4.1 KiB

Двоичные данные
app/src/main/res/drawable-nodpi/1f60c.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 3.8 KiB

Двоичные данные
app/src/main/res/drawable-nodpi/1f60d.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 4.0 KiB

Двоичные данные
app/src/main/res/drawable-nodpi/1f60e.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 4.1 KiB

Двоичные данные
app/src/main/res/drawable-nodpi/1f60f.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 3.7 KiB

Двоичные данные
app/src/main/res/drawable-nodpi/1f61a.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 3.9 KiB

Двоичные данные
app/src/main/res/drawable-nodpi/1f61b.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 3.6 KiB

Двоичные данные
app/src/main/res/drawable-nodpi/1f61c.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 4.1 KiB

Двоичные данные
app/src/main/res/drawable-nodpi/1f61d.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 4.0 KiB

Двоичные данные
app/src/main/res/drawable-nodpi/1f61e.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 3.4 KiB

Двоичные данные
app/src/main/res/drawable-nodpi/1f61f.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 3.7 KiB

Двоичные данные
app/src/main/res/drawable-nodpi/1f62a.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 4.0 KiB

Двоичные данные
app/src/main/res/drawable-nodpi/1f62b.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 4.4 KiB

Двоичные данные
app/src/main/res/drawable-nodpi/1f62c.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 3.8 KiB

Двоичные данные
app/src/main/res/drawable-nodpi/1f62d.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 4.0 KiB

Двоичные данные
app/src/main/res/drawable-nodpi/1f62e.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 3.4 KiB

Двоичные данные
app/src/main/res/drawable-nodpi/1f62f.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 3.6 KiB

Просмотреть файл

@ -6,8 +6,6 @@ buildscript {
}
dependencies {
classpath 'com.android.tools.build:gradle:2.1.2'
// classpath 'com.google.gms:google-services:3.0.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}

Просмотреть файл

@ -1 +1,2 @@
include ':app'
include ':third_party:HtmlTextView'

33
third_party/HtmlTextView/.gitignore поставляемый Normal file
Просмотреть файл

@ -0,0 +1,33 @@
#Android specific
bin
gen
obj
lint.xml
local.properties
release.properties
ant.properties
*.class
*.apk
#Gradle
.gradle
build
gradle.properties
#Maven
target
pom.xml.*
#Eclipse
.project
.classpath
.settings
.metadata
#IntelliJ IDEA
.idea
*.iml
#Lint output
lint-report.html
lint-report_files/*

13
third_party/HtmlTextView/build.gradle поставляемый Normal file
Просмотреть файл

@ -0,0 +1,13 @@
apply plugin: 'com.android.library'
android {
compileSdkVersion 23
buildToolsVersion '23.0.3'
defaultConfig {
minSdkVersion 7
targetSdkVersion 23
versionCode 7
versionName '1.6'
}
}

7
third_party/HtmlTextView/src/main/AndroidManifest.xml поставляемый Normal file
Просмотреть файл

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.sufficientlysecure.htmltextview">
<application />
</manifest>

Просмотреть файл

@ -0,0 +1,40 @@
/*
* Copyright (C) 2016 Richard Thai
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sufficientlysecure.htmltextview;
import android.text.style.ClickableSpan;
/**
* This span defines what should happen if a table is clicked. This abstract class is defined so
* that applications can access the raw table HTML and do whatever they'd like to render it (e.g.
* show it in a WebView).
*/
public abstract class ClickableTableSpan extends ClickableSpan {
protected String mTableHtml;
// This sucks, but we need this so that each table can get its own ClickableTableSpan.
// Otherwise, we end up removing the clicking from earlier tables.
public abstract ClickableTableSpan newInstance();
public void setTableHtml(String tableHtml) {
this.mTableHtml = tableHtml;
}
public String getTableHtml() {
return mTableHtml;
}
}

Просмотреть файл

@ -0,0 +1,94 @@
/*
* Copyright (C) 2016 Richard Thai
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sufficientlysecure.htmltextview;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.text.style.ReplacementSpan;
/**
* This span defines how a table should be rendered in the HtmlTextView. The default implementation
* is a cop-out which replaces the HTML table with some text ("[tap for table]" is the default).
*
* This is to be used in conjunction with the ClickableTableSpan which will redirect a click to the
* text some application-defined action (i.e. render the raw HTML in a WebView).
*/
public class DrawTableLinkSpan extends ReplacementSpan {
private int mWidth;
private static final String DEFAULT_TABLE_LINK_TEXT = "";
private static float DEFAULT_TEXT_SIZE = 80f;
private static int DEFAULT_TEXT_COLOR = Color.BLUE;
protected String mTableLinkText = DEFAULT_TABLE_LINK_TEXT;
protected float mTextSize = DEFAULT_TEXT_SIZE;
protected int mTextColor = DEFAULT_TEXT_COLOR;
// This sucks, but we need this so that each table can get drawn.
// Otherwise, we end up with the default table link text (nothing) for earlier tables.
public DrawTableLinkSpan newInstance() {
final DrawTableLinkSpan drawTableLinkSpan = new DrawTableLinkSpan();
drawTableLinkSpan.setTableLinkText(mTableLinkText);
drawTableLinkSpan.setTextSize(mTextSize);
drawTableLinkSpan.setTextColor(mTextColor);
return drawTableLinkSpan;
}
@Override
public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
mWidth = (int) paint.measureText(mTableLinkText, 0, mTableLinkText.length());
mTextSize = paint.getTextSize();
return mWidth;
}
@Override
public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
final Paint paint2 = new Paint();
paint2.setStyle(Paint.Style.STROKE);
paint2.setColor(mTextColor);
paint2.setAntiAlias(true);
paint2.setTextSize(mTextSize);
canvas.drawText(mTableLinkText, x, bottom, paint2);
}
public void setTableLinkText(String tableLinkText) {
this.mTableLinkText = tableLinkText;
}
public void setTextSize(float textSize) {
this.mTextSize = textSize;
}
public void setTextColor(int textColor) {
this.mTextColor = textColor;
}
public String getTableLinkText() {
return mTableLinkText;
}
public float getTextSize() {
return mTextSize;
}
public int getTextColor() {
return mTextColor;
}
}

Просмотреть файл

@ -0,0 +1,28 @@
package org.sufficientlysecure.htmltextview;
public class EmojiUtils {
public static String convertTag(String str){
return str
.replaceAll("<", "&lt;")
.replaceAll(":)","<img src=\"1f60a\"/>")
.replaceAll(":)","<img src=\"1f60b\"/>")
.replaceAll(":)","<img src=\"1f60c\"/>")
.replaceAll(":)","<img src=\"1f60d\"/>")
.replaceAll(":)","<img src=\"1f60e\"/>")
.replaceAll(":)","<img src=\"1f60f\"/>")
.replaceAll(":)","<img src=\"1f61a\"/>")
.replaceAll(":)","<img src=\"1f61b\"/>")
.replaceAll(":)","<img src=\"1f61c\"/>")
.replaceAll(":)","<img src=\"1f61d\"/>")
.replaceAll(":)","<img src=\"1f61e\"/>")
.replaceAll(":)","<img src=\"1f61f\"/>")
.replaceAll(":)","<img src=\"1f62a\"/>")
.replaceAll(":)","<img src=\"1f62b\"/>")
.replaceAll(":)","<img src=\"1f62c\"/>")
.replaceAll(":)","<img src=\"1f62d\"/>")
.replaceAll(":)","<img src=\"1f62e\"/>")
.replaceAll(":)","<img src=\"1f62f\"/>")
;
}
}

Просмотреть файл

@ -0,0 +1,54 @@
/*
* Copyright (C) 2014 Dominik Schürmann <dominik@dominikschuermann.de>
* Copyright (C) 2014 drawk
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sufficientlysecure.htmltextview;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.util.Log;
/**
* Copied from http://stackoverflow.com/a/22298833
*/
public class HtmlLocalImageGetter implements Html.ImageGetter {
Context c;
public HtmlLocalImageGetter(Context c) {
this.c = c;
}
public Drawable getDrawable(String source) {
int id = c.getResources().getIdentifier(source, "drawable", c.getPackageName());
if (id == 0) {
// the drawable resource wasn't found in our package, maybe it is a stock android drawable?
id = c.getResources().getIdentifier(source, "drawable", "android");
}
if (id == 0) {
// prevent a crash if the resource still can't be found
Log.e(HtmlTextView.TAG, "source could not be found: " + source);
return null;
} else {
Drawable d = c.getResources().getDrawable(id);
d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
return d;
}
}
}

Просмотреть файл

@ -0,0 +1,148 @@
/*
* Copyright (C) 2013 Antarix Tandon
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sufficientlysecure.htmltextview;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.text.Html.ImageGetter;
import android.util.Log;
import android.view.View;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.URI;
import java.net.URL;
public class HtmlRemoteImageGetter implements ImageGetter {
View container;
URI baseUri;
/**
* Construct the URLImageParser which will execute AsyncTask and refresh the container
*/
public HtmlRemoteImageGetter(View t, String baseUrl) {
this.container = t;
if (baseUrl != null) {
this.baseUri = URI.create(baseUrl);
}
}
public Drawable getDrawable(String source) {
UrlDrawable urlDrawable = new UrlDrawable();
// get the actual source
ImageGetterAsyncTask asyncTask = new ImageGetterAsyncTask(urlDrawable, this);
asyncTask.execute(source);
// return reference to URLDrawable which will asynchronously load the image specified in the src tag
return urlDrawable;
}
/**
* Static inner {@link AsyncTask} that keeps a {@link WeakReference} to the {@link UrlDrawable}
* and {@link HtmlRemoteImageGetter}.
* <p>
* This way, if the AsyncTask has a longer life span than the UrlDrawable,
* we won't leak the UrlDrawable or the HtmlRemoteImageGetter.
*/
private static class ImageGetterAsyncTask extends AsyncTask<String, Void, Drawable> {
private final WeakReference<UrlDrawable> drawableReference;
private final WeakReference<HtmlRemoteImageGetter> imageGetterReference;
private String source;
public ImageGetterAsyncTask(UrlDrawable d, HtmlRemoteImageGetter imageGetter) {
this.drawableReference = new WeakReference<>(d);
this.imageGetterReference = new WeakReference<>(imageGetter);
}
@Override
protected Drawable doInBackground(String... params) {
source = params[0];
return fetchDrawable(source);
}
@Override
protected void onPostExecute(Drawable result) {
if (result == null) {
Log.w(HtmlTextView.TAG, "Drawable result is null! (source: " + source + ")");
return;
}
final UrlDrawable urlDrawable = drawableReference.get();
if (urlDrawable == null) {
return;
}
// set the correct bound according to the result from HTTP call
urlDrawable.setBounds(0, 0, 0 + result.getIntrinsicWidth(), 0 + result.getIntrinsicHeight());
// change the reference of the current drawable to the result from the HTTP call
urlDrawable.drawable = result;
final HtmlRemoteImageGetter imageGetter = imageGetterReference.get();
if (imageGetter == null) {
return;
}
// redraw the image by invalidating the container
imageGetter.container.invalidate();
}
/**
* Get the Drawable from URL
*/
public Drawable fetchDrawable(String urlString) {
try {
InputStream is = fetch(urlString);
Drawable drawable = Drawable.createFromStream(is, "src");
drawable.setBounds(0, 0, 0 + drawable.getIntrinsicWidth(), 0 + drawable.getIntrinsicHeight());
return drawable;
} catch (Exception e) {
return null;
}
}
private InputStream fetch(String urlString) throws IOException {
URL url;
final HtmlRemoteImageGetter imageGetter = imageGetterReference.get();
if (imageGetter == null) {
return null;
}
if (imageGetter.baseUri != null) {
url = imageGetter.baseUri.resolve(urlString).toURL();
} else {
url = URI.create(urlString).toURL();
}
return (InputStream) url.getContent();
}
}
@SuppressWarnings("deprecation")
public class UrlDrawable extends BitmapDrawable {
protected Drawable drawable;
@Override
public void draw(Canvas canvas) {
// override the draw to facilitate refresh function later
if (drawable != null) {
drawable.draw(canvas);
}
}
}
}

Просмотреть файл

@ -0,0 +1,341 @@
/*
* Copyright (C) 2013-2015 Dominik Schürmann <dominik@dominikschuermann.de>
* Copyright (C) 2013-2015 Juha Kuitunen
* Copyright (C) 2013 Mohammed Lakkadshaw
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sufficientlysecure.htmltextview;
import android.text.Editable;
import android.text.Html;
import android.text.Layout;
import android.text.Spannable;
import android.text.Spanned;
import android.text.style.AlignmentSpan;
import android.text.style.BulletSpan;
import android.text.style.LeadingMarginSpan;
import android.text.style.StrikethroughSpan;
import android.text.style.TypefaceSpan;
import android.util.Log;
import org.xml.sax.XMLReader;
import java.util.Stack;
/**
* Some parts of this code are based on android.text.Html
*/
public class HtmlTagHandler implements Html.TagHandler {
/**
* Keeps track of lists (ol, ul). On bottom of Stack is the outermost list
* and on top of Stack is the most nested list
*/
Stack<String> lists = new Stack<>();
/**
* Tracks indexes of ordered lists so that after a nested list ends
* we can continue with correct index of outer list
*/
Stack<Integer> olNextIndex = new Stack<>();
/**
* List indentation in pixels. Nested lists use multiple of this.
*/
/**
* Running HTML table string based off of the root table tag. Root table tag being the tag which
* isn't embedded within any other table tag. Example:
* <!-- This is the root level opening table tag. This is where we keep track of tables. -->
* <table>
* ...
* <table> <!-- Non-root table tags -->
* ...
* </table>
* ...
* </table>
* <!-- This is the root level closing table tag and the end of the string we track. -->
*/
StringBuilder tableHtmlBuilder = new StringBuilder();
/**
* Tells us which level of table tag we're on; ultimately used to find the root table tag.
*/
int tableTagLevel = 0;
private static final int indent = 10;
private static final int listItemIndent = indent * 2;
private static final BulletSpan bullet = new BulletSpan(indent);
private ClickableTableSpan mClickableTableSpan;
private DrawTableLinkSpan mDrawTableLinkSpan;
private static class Ul {
}
private static class Ol {
}
private static class Code {
}
private static class Center {
}
private static class Strike {
}
private static class Table {
}
private static class Tr {
}
private static class Th {
}
private static class Td {
}
@Override
public void handleTag(final boolean opening, final String tag, Editable output, final XMLReader xmlReader) {
if (opening) {
// opening tag
if (HtmlTextView.DEBUG) {
Log.d(HtmlTextView.TAG, "opening, output: " + output.toString());
}
if (tag.equalsIgnoreCase("ul")) {
lists.push(tag);
} else if (tag.equalsIgnoreCase("ol")) {
lists.push(tag);
olNextIndex.push(1);
} else if (tag.equalsIgnoreCase("li")) {
if (output.length() > 0 && output.charAt(output.length() - 1) != '\n') {
output.append("\n");
}
String parentList = lists.peek();
if (parentList.equalsIgnoreCase("ol")) {
start(output, new Ol());
output.append(olNextIndex.peek().toString()).append(". ");
olNextIndex.push(olNextIndex.pop() + 1);
} else if (parentList.equalsIgnoreCase("ul")) {
start(output, new Ul());
}
} else if (tag.equalsIgnoreCase("code")) {
start(output, new Code());
} else if (tag.equalsIgnoreCase("center")) {
start(output, new Center());
} else if (tag.equalsIgnoreCase("s") || tag.equalsIgnoreCase("strike")) {
start(output, new Strike());
} else if (tag.equalsIgnoreCase("table")) {
start(output, new Table());
if (tableTagLevel == 0) {
tableHtmlBuilder = new StringBuilder();
// We need some text for the table to be replaced by the span because
// the other tags will remove their text when their text is extracted
output.append("table placeholder");
}
tableTagLevel++;
}
else if (tag.equalsIgnoreCase("tr")) {
start(output, new Tr());
} else if (tag.equalsIgnoreCase("th")) {
start(output, new Th());
} else if (tag.equalsIgnoreCase("td")) {
start(output, new Td());
}
} else {
// closing tag
if (HtmlTextView.DEBUG) {
Log.d(HtmlTextView.TAG, "closing, output: " + output.toString());
}
if (tag.equalsIgnoreCase("ul")) {
lists.pop();
} else if (tag.equalsIgnoreCase("ol")) {
lists.pop();
olNextIndex.pop();
} else if (tag.equalsIgnoreCase("li")) {
if (lists.peek().equalsIgnoreCase("ul")) {
if (output.length() > 0 && output.charAt(output.length() - 1) != '\n') {
output.append("\n");
}
// Nested BulletSpans increases distance between bullet and text, so we must prevent it.
int bulletMargin = indent;
if (lists.size() > 1) {
bulletMargin = indent - bullet.getLeadingMargin(true);
if (lists.size() > 2) {
// This get's more complicated when we add a LeadingMarginSpan into the same line:
// we have also counter it's effect to BulletSpan
bulletMargin -= (lists.size() - 2) * listItemIndent;
}
}
BulletSpan newBullet = new BulletSpan(bulletMargin);
end(output, Ul.class, false,
new LeadingMarginSpan.Standard(listItemIndent * (lists.size() - 1)),
newBullet);
} else if (lists.peek().equalsIgnoreCase("ol")) {
if (output.length() > 0 && output.charAt(output.length() - 1) != '\n') {
output.append("\n");
}
int numberMargin = listItemIndent * (lists.size() - 1);
if (lists.size() > 2) {
// Same as in ordered lists: counter the effect of nested Spans
numberMargin -= (lists.size() - 2) * listItemIndent;
}
end(output, Ol.class, false, new LeadingMarginSpan.Standard(numberMargin));
}
} else if (tag.equalsIgnoreCase("code")) {
end(output, Code.class, false, new TypefaceSpan("monospace"));
} else if (tag.equalsIgnoreCase("center")) {
end(output, Center.class, true, new AlignmentSpan.Standard(Layout.Alignment.ALIGN_CENTER));
} else if (tag.equalsIgnoreCase("s") || tag.equalsIgnoreCase("strike")) {
end(output, Strike.class, false, new StrikethroughSpan());
} else if (tag.equalsIgnoreCase("table")) {
tableTagLevel--;
// When we're back at the root-level table
if (tableTagLevel == 0) {
final String tableHtml = tableHtmlBuilder.toString();
ClickableTableSpan clickableTableSpan = null;
if (mClickableTableSpan != null) {
clickableTableSpan = mClickableTableSpan.newInstance();
clickableTableSpan.setTableHtml(tableHtml);
}
DrawTableLinkSpan drawTableLinkSpan = null;
if (mDrawTableLinkSpan != null) {
drawTableLinkSpan = mDrawTableLinkSpan.newInstance();
}
end(output, Table.class, false, drawTableLinkSpan, clickableTableSpan);
} else {
end(output, Table.class, false);
}
}
else if (tag.equalsIgnoreCase("tr")) {
end(output, Tr.class, false);
} else if (tag.equalsIgnoreCase("th")) {
end(output, Th.class, false);
} else if (tag.equalsIgnoreCase("td")) {
end(output, Td.class, false);
}
}
storeTableTags(opening, tag);
}
/**
* If we're arriving at a table tag or are already within a table tag, then we should store it
* the raw HTML for our ClickableTableSpan
*/
private void storeTableTags(boolean opening, String tag) {
if (tableTagLevel > 0 || tag.equalsIgnoreCase("table")) {
tableHtmlBuilder.append("<");
if (!opening) {
tableHtmlBuilder.append("/");
}
tableHtmlBuilder
.append(tag.toLowerCase())
.append(">");
}
}
/**
* Mark the opening tag by using private classes
*/
private void start(Editable output, Object mark) {
int len = output.length();
output.setSpan(mark, len, len, Spannable.SPAN_MARK_MARK);
if (HtmlTextView.DEBUG) {
Log.d(HtmlTextView.TAG, "len: " + len);
}
}
/**
* Modified from {@link android.text.Html}
*/
private void end(Editable output, Class kind, boolean paragraphStyle, Object... replaces) {
Object obj = getLast(output, kind);
// start of the tag
int where = output.getSpanStart(obj);
// end of the tag
int len = output.length();
// If we're in a table, then we need to store the raw HTML for later
if (tableTagLevel > 0) {
final CharSequence extractedSpanText = extractSpanText(output, kind);
tableHtmlBuilder.append(extractedSpanText);
}
output.removeSpan(obj);
if (where != len) {
int thisLen = len;
// paragraph styles like AlignmentSpan need to end with a new line!
if (paragraphStyle) {
output.append("\n");
thisLen++;
}
for (Object replace : replaces) {
output.setSpan(replace, where, thisLen, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
if (HtmlTextView.DEBUG) {
Log.d(HtmlTextView.TAG, "where: " + where);
Log.d(HtmlTextView.TAG, "thisLen: " + thisLen);
}
}
}
/**
* Returns the text contained within a span and deletes it from the output string
*/
private CharSequence extractSpanText(Editable output, Class kind) {
final Object obj = getLast(output, kind);
// start of the tag
final int where = output.getSpanStart(obj);
// end of the tag
final int len = output.length();
final CharSequence extractedSpanText = output.subSequence(where, len);
output.delete(where, len);
return extractedSpanText;
}
/**
* Get last marked position of a specific tag kind (private class)
*/
private static Object getLast(Editable text, Class kind) {
Object[] objs = text.getSpans(0, text.length(), kind);
if (objs.length == 0) {
return null;
} else {
for (int i = objs.length; i > 0; i--) {
if (text.getSpanFlags(objs[i - 1]) == Spannable.SPAN_MARK_MARK) {
return objs[i - 1];
}
}
return null;
}
}
public void setClickableTableSpan(ClickableTableSpan clickableTableSpan) {
this.mClickableTableSpan = clickableTableSpan;
}
public void setDrawTableLinkSpan(DrawTableLinkSpan drawTableLinkSpan) {
this.mDrawTableLinkSpan = drawTableLinkSpan;
}
}

Просмотреть файл

@ -0,0 +1,191 @@
/*
* Copyright (C) 2013-2014 Dominik Schürmann <dominik@dominikschuermann.de>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sufficientlysecure.htmltextview;
import android.content.Context;
import android.text.Html;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import java.io.InputStream;
import java.util.Scanner;
public class HtmlTextView extends JellyBeanSpanFixTextView {
public static final String TAG = "HtmlTextView";
public static final boolean DEBUG = false;
boolean mDontConsumeNonUrlClicks = true;
boolean mLinkHit;
private boolean removeFromHtmlSpace = false;
private ClickableTableSpan mClickableTableSpan;
private DrawTableLinkSpan mDrawTableLinkSpan;
public HtmlTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public HtmlTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public HtmlTextView(Context context) {
super(context);
}
/**
* Note that this must be called before setting text for it to work
*/
public void setRemoveFromHtmlSpace(boolean removeFromHtmlSpace) {
this.removeFromHtmlSpace = removeFromHtmlSpace;
}
public interface ImageGetter {
}
public static class LocalImageGetter implements ImageGetter {
}
public static class RemoteImageGetter implements ImageGetter {
public String baseUrl;
public RemoteImageGetter() {
}
public RemoteImageGetter(String baseUrl) {
this.baseUrl = baseUrl;
}
}
/**
* http://stackoverflow.com/questions/309424/read-convert-an-inputstream-to-a-string
*/
static private String convertStreamToString(InputStream is) {
Scanner s = new Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
@Override
public boolean onTouchEvent(MotionEvent event) {
mLinkHit = false;
boolean res = super.onTouchEvent(event);
if (mDontConsumeNonUrlClicks) {
return mLinkHit;
}
return res;
}
/**
* Loads HTML from a raw resource, i.e., a HTML file in res/raw/.
* This allows translatable resource (e.g., res/raw-de/ for german).
* The containing HTML is parsed to Android's Spannable format and then displayed.
*
* @param context Context
* @param resId for example: R.raw.help
*/
public void setHtmlFromRawResource(Context context, int resId, ImageGetter imageGetter) {
// load html from html file from /res/raw
InputStream inputStreamText = context.getResources().openRawResource(resId);
setHtmlFromString(convertStreamToString(inputStreamText), imageGetter);
}
/**
* Parses String containing HTML to Android's Spannable format and displays it in this TextView.
*
* @param html String containing HTML, for example: "<b>Hello world!</b>"
*/
public void setHtmlFromString(String html, ImageGetter imageGetter) {
Html.ImageGetter htmlImageGetter;
if (imageGetter instanceof LocalImageGetter) {
htmlImageGetter = new HtmlLocalImageGetter(getContext());
} else if (imageGetter instanceof RemoteImageGetter) {
htmlImageGetter = new HtmlRemoteImageGetter(this,
((RemoteImageGetter) imageGetter).baseUrl);
} else {
Log.e(TAG, "Wrong imageGetter!");
return;
}
setHtmlFromStringWithHtmlImageGetter(html, htmlImageGetter);
}
/**
* Parses String containing HTML to Android's Spannable format and displays it in this TextView.
* Using the implementation of Html.ImageGetter provided. This allows using external libraries
* for fetching and caching images.
*
* @param html String containing HTML, for example: "<b>Hello world!</b>"
* @param htmlImageGetter for fetching images
*/
public void setHtmlFromStringWithHtmlImageGetter(String html, Html.ImageGetter htmlImageGetter) {
// this uses Android's Html class for basic parsing, and HtmlTagHandler
final HtmlTagHandler htmlTagHandler = new HtmlTagHandler();
htmlTagHandler.setClickableTableSpan(mClickableTableSpan);
htmlTagHandler.setDrawTableLinkSpan(mDrawTableLinkSpan);
if (removeFromHtmlSpace) {
setText(removeHtmlBottomPadding(Html.fromHtml(html, htmlImageGetter, htmlTagHandler)));
} else {
setText(Html.fromHtml(html, htmlImageGetter, htmlTagHandler));
}
// make links work
setMovementMethod(LocalLinkMovementMethod.getInstance());
}
/**
* @deprecated
*/
public void setHtmlFromRawResource(Context context, int resId, boolean useLocalDrawables) {
if (useLocalDrawables) {
setHtmlFromRawResource(context, resId, new LocalImageGetter());
} else {
setHtmlFromRawResource(context, resId, new RemoteImageGetter());
}
}
/**
* @deprecated
*/
public void setHtmlFromString(String html, boolean useLocalDrawables) {
if (useLocalDrawables) {
setHtmlFromString(html, new LocalImageGetter());
} else {
setHtmlFromString(html, new RemoteImageGetter());
}
}
public void setClickableTableSpan(ClickableTableSpan clickableTableSpan) {
this.mClickableTableSpan = clickableTableSpan;
}
public void setDrawTableLinkSpan(DrawTableLinkSpan drawTableLinkSpan) {
this.mDrawTableLinkSpan = drawTableLinkSpan;
}
private CharSequence removeHtmlBottomPadding(CharSequence text) {
if (text == null) {
return null;
} else if (text.length() == 0) {
return text;
}
while (text.charAt(text.length() - 1) == '\n') {
text = text.subSequence(0, text.length() - 1);
}
return text;
}
}

Просмотреть файл

@ -0,0 +1,214 @@
/*
* Copyright (C) 2013 Dominik Schürmann <dominik@dominikschuermann.de>
* Copyright (C) 2012 Pierre-Yves Ricau <py.ricau@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sufficientlysecure.htmltextview;
import java.util.ArrayList;
import java.util.List;
import android.annotation.SuppressLint;
import android.content.Context;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.TextView;
/**
* <p/>
* A {@link android.widget.TextView} that insert spaces around its text spans where needed to prevent
* {@link IndexOutOfBoundsException} in {@link #onMeasure(int, int)} on Jelly Bean.
* <p/>
* When {@link #onMeasure(int, int)} throws an exception, we try to fix the text by adding spaces
* around spans, until it works again. We then try removing some of the added spans, to minimize the
* insertions.
* <p/>
* The fix is time consuming (a few ms, it depends on the size of your text), but it should only
* happen once per text change.
* <p/>
* See http://code.google.com/p/android/issues/detail?id=35466
* <p/>
* From https://gist.github.com/pyricau/3424004 with fix from comments
*/
public class JellyBeanSpanFixTextView extends TextView {
private static class FixingResult {
public final boolean fixed;
public final List<Object> spansWithSpacesBefore;
public final List<Object> spansWithSpacesAfter;
public static FixingResult fixed(List<Object> spansWithSpacesBefore,
List<Object> spansWithSpacesAfter) {
return new FixingResult(true, spansWithSpacesBefore, spansWithSpacesAfter);
}
public static FixingResult notFixed() {
return new FixingResult(false, null, null);
}
private FixingResult(boolean fixed, List<Object> spansWithSpacesBefore,
List<Object> spansWithSpacesAfter) {
this.fixed = fixed;
this.spansWithSpacesBefore = spansWithSpacesBefore;
this.spansWithSpacesAfter = spansWithSpacesAfter;
}
}
public JellyBeanSpanFixTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public JellyBeanSpanFixTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public JellyBeanSpanFixTextView(Context context) {
super(context);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
try {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
} catch (IndexOutOfBoundsException e) {
fixOnMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
/**
* If possible, fixes the Spanned text by adding spaces around spans when needed.
*/
private void fixOnMeasure(int widthMeasureSpec, int heightMeasureSpec) {
CharSequence text = getText();
if (text instanceof Spanned) {
SpannableStringBuilder builder = new SpannableStringBuilder(text);
fixSpannedWithSpaces(builder, widthMeasureSpec, heightMeasureSpec);
} else {
if (HtmlTextView.DEBUG) {
Log.d(HtmlTextView.TAG, "The text isn't a Spanned");
}
fallbackToString(widthMeasureSpec, heightMeasureSpec);
}
}
/**
* Add spaces around spans until the text is fixed, and then removes the unneeded spaces
*/
private void fixSpannedWithSpaces(SpannableStringBuilder builder, int widthMeasureSpec,
int heightMeasureSpec) {
long startFix = System.currentTimeMillis();
FixingResult result = addSpacesAroundSpansUntilFixed(builder, widthMeasureSpec,
heightMeasureSpec);
if (result.fixed) {
removeUnneededSpaces(widthMeasureSpec, heightMeasureSpec, builder, result);
} else {
fallbackToString(widthMeasureSpec, heightMeasureSpec);
}
if (HtmlTextView.DEBUG) {
long fixDuration = System.currentTimeMillis() - startFix;
Log.d(HtmlTextView.TAG, "fixSpannedWithSpaces() duration in ms: " + fixDuration);
}
}
private FixingResult addSpacesAroundSpansUntilFixed(SpannableStringBuilder builder,
int widthMeasureSpec, int heightMeasureSpec) {
Object[] spans = builder.getSpans(0, builder.length(), Object.class);
List<Object> spansWithSpacesBefore = new ArrayList<>(spans.length);
List<Object> spansWithSpacesAfter = new ArrayList<>(spans.length);
for (Object span : spans) {
int spanStart = builder.getSpanStart(span);
if (isNotSpace(builder, spanStart - 1)) {
builder.insert(spanStart, " ");
spansWithSpacesBefore.add(span);
}
int spanEnd = builder.getSpanEnd(span);
if (isNotSpace(builder, spanEnd)) {
builder.insert(spanEnd, " ");
spansWithSpacesAfter.add(span);
}
try {
setTextAndMeasure(builder, widthMeasureSpec, heightMeasureSpec);
return FixingResult.fixed(spansWithSpacesBefore, spansWithSpacesAfter);
} catch (IndexOutOfBoundsException ignored) {
}
}
if (HtmlTextView.DEBUG) {
Log.d(HtmlTextView.TAG, "Could not fix the Spanned by adding spaces around spans");
}
return FixingResult.notFixed();
}
private boolean isNotSpace(CharSequence text, int where) {
return where < 0 || where >= text.length() || text.charAt(where) != ' ';
}
@SuppressLint("WrongCall")
private void setTextAndMeasure(CharSequence text, int widthMeasureSpec, int heightMeasureSpec) {
setText(text);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
@SuppressLint("WrongCall")
private void removeUnneededSpaces(int widthMeasureSpec, int heightMeasureSpec,
SpannableStringBuilder builder, FixingResult result) {
for (Object span : result.spansWithSpacesAfter) {
int spanEnd = builder.getSpanEnd(span);
builder.delete(spanEnd, spanEnd + 1);
try {
setTextAndMeasure(builder, widthMeasureSpec, heightMeasureSpec);
} catch (IndexOutOfBoundsException ignored) {
builder.insert(spanEnd, " ");
}
}
boolean needReset = true;
for (Object span : result.spansWithSpacesBefore) {
int spanStart = builder.getSpanStart(span);
builder.delete(spanStart - 1, spanStart);
try {
setTextAndMeasure(builder, widthMeasureSpec, heightMeasureSpec);
needReset = false;
} catch (IndexOutOfBoundsException ignored) {
needReset = true;
int newSpanStart = spanStart - 1;
builder.insert(newSpanStart, " ");
}
}
if (needReset) {
setText(builder);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
private void fallbackToString(int widthMeasureSpec, int heightMeasureSpec) {
if (HtmlTextView.DEBUG) {
Log.d(HtmlTextView.TAG, "Fallback to unspanned text");
}
String fallbackText = getText().toString();
setTextAndMeasure(fallbackText, widthMeasureSpec, heightMeasureSpec);
}
}

Просмотреть файл

@ -0,0 +1,83 @@
/*
* Copyright (C) 2015 Heliangwei
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sufficientlysecure.htmltextview;
import android.text.Layout;
import android.text.Selection;
import android.text.Spannable;
import android.text.method.LinkMovementMethod;
import android.text.method.Touch;
import android.text.style.ClickableSpan;
import android.view.MotionEvent;
import android.widget.TextView;
/**
* Copied from http://stackoverflow.com/questions/8558732
*/
public class LocalLinkMovementMethod extends LinkMovementMethod {
static LocalLinkMovementMethod sInstance;
public static LocalLinkMovementMethod getInstance() {
if (sInstance == null)
sInstance = new LocalLinkMovementMethod();
return sInstance;
}
@Override
public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) {
int action = event.getAction();
if (action == MotionEvent.ACTION_UP ||
action == MotionEvent.ACTION_DOWN) {
int x = (int) event.getX();
int y = (int) event.getY();
x -= widget.getTotalPaddingLeft();
y -= widget.getTotalPaddingTop();
x += widget.getScrollX();
y += widget.getScrollY();
Layout layout = widget.getLayout();
int line = layout.getLineForVertical(y);
int off = layout.getOffsetForHorizontal(line, x);
ClickableSpan[] link = buffer.getSpans(off, off, ClickableSpan.class);
if (link.length != 0) {
if (action == MotionEvent.ACTION_UP) {
link[0].onClick(widget);
} else if (action == MotionEvent.ACTION_DOWN) {
Selection.setSelection(buffer,
buffer.getSpanStart(link[0]),
buffer.getSpanEnd(link[0]));
}
if (widget instanceof HtmlTextView) {
((HtmlTextView) widget).mLinkHit = true;
}
return true;
} else {
Selection.removeSelection(buffer);
Touch.onTouchEvent(widget, buffer, event);
return false;
}
}
return Touch.onTouchEvent(widget, buffer, event);
}
}

Двоичные данные
third_party/HtmlTextView/src/main/res/drawable-nodpi/1f60a.png поставляемый Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 3.7 KiB

Двоичные данные
third_party/HtmlTextView/src/main/res/drawable-nodpi/1f60b.png поставляемый Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 4.1 KiB

Двоичные данные
third_party/HtmlTextView/src/main/res/drawable-nodpi/1f60c.png поставляемый Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 3.8 KiB

Двоичные данные
third_party/HtmlTextView/src/main/res/drawable-nodpi/1f60d.png поставляемый Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 4.0 KiB

Двоичные данные
third_party/HtmlTextView/src/main/res/drawable-nodpi/1f60e.png поставляемый Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 4.1 KiB

Двоичные данные
third_party/HtmlTextView/src/main/res/drawable-nodpi/1f60f.png поставляемый Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 3.7 KiB

Двоичные данные
third_party/HtmlTextView/src/main/res/drawable-nodpi/1f61a.png поставляемый Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 3.9 KiB

Двоичные данные
third_party/HtmlTextView/src/main/res/drawable-nodpi/1f61b.png поставляемый Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 3.6 KiB

Двоичные данные
third_party/HtmlTextView/src/main/res/drawable-nodpi/1f61c.png поставляемый Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 4.1 KiB

Двоичные данные
third_party/HtmlTextView/src/main/res/drawable-nodpi/1f61d.png поставляемый Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 4.0 KiB

Двоичные данные
third_party/HtmlTextView/src/main/res/drawable-nodpi/1f61e.png поставляемый Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 3.4 KiB

Двоичные данные
third_party/HtmlTextView/src/main/res/drawable-nodpi/1f61f.png поставляемый Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 3.7 KiB

Двоичные данные
third_party/HtmlTextView/src/main/res/drawable-nodpi/1f62a.png поставляемый Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 4.0 KiB

Двоичные данные
third_party/HtmlTextView/src/main/res/drawable-nodpi/1f62b.png поставляемый Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 4.4 KiB

Двоичные данные
third_party/HtmlTextView/src/main/res/drawable-nodpi/1f62c.png поставляемый Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 3.8 KiB

Двоичные данные
third_party/HtmlTextView/src/main/res/drawable-nodpi/1f62d.png поставляемый Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 4.0 KiB

Двоичные данные
third_party/HtmlTextView/src/main/res/drawable-nodpi/1f62e.png поставляемый Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 3.4 KiB

Двоичные данные
third_party/HtmlTextView/src/main/res/drawable-nodpi/1f62f.png поставляемый Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 3.6 KiB