Switch to androidsvg SVG library.

This library has much better support for the SVG standard.
This commit is contained in:
Peter Osterlund 2019-04-13 09:12:00 +02:00
parent 1fd3492edd
commit 3c361195d8
10 changed files with 99 additions and 1848 deletions

View File

@ -57,6 +57,7 @@ dependencies {
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation project(':CuckooChessEngine')
implementation 'com.caverock:androidsvg-aar:1.3'
}
// Build the ECO database

View File

@ -1,306 +0,0 @@
package com.larvalabs.svgandroid;
/*
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You 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.
*/
/**
* Parses numbers from SVG text. Based on the Batik Number Parser (Apache 2 License).
*
* @author Apache Software Foundation, Larva Labs LLC
*/
public class ParserHelper {
private char current;
private CharSequence s;
public int pos;
private int n;
public ParserHelper(CharSequence s, int pos) {
this.s = s;
this.pos = pos;
n = s.length();
current = s.charAt(pos);
}
private char read() {
if (pos < n) {
pos++;
}
if (pos == n) {
return '\0';
} else {
return s.charAt(pos);
}
}
public void skipWhitespace() {
while (pos < n) {
if (Character.isWhitespace(s.charAt(pos))) {
advance();
} else {
break;
}
}
}
public void skipNumberSeparator() {
while (pos < n) {
char c = s.charAt(pos);
switch (c) {
case ' ':
case ',':
case '\n':
case '\t':
advance();
break;
default:
return;
}
}
}
public void advance() {
current = read();
}
/**
* Parses the content of the buffer and converts it to a float.
*/
public float parseFloat() {
int mant = 0;
int mantDig = 0;
boolean mantPos = true;
boolean mantRead = false;
int exp = 0;
int expDig = 0;
int expAdj = 0;
boolean expPos = true;
switch (current) {
case '-':
mantPos = false;
// fallthrough
case '+':
current = read();
}
m1: switch (current) {
default:
return Float.NaN;
case '.':
break;
case '0':
mantRead = true;
l: for (;;) {
current = read();
switch (current) {
case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
break l;
case '.': case 'e': case 'E':
break m1;
default:
return 0.0f;
case '0':
}
}
case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
mantRead = true;
l: for (;;) {
if (mantDig < 9) {
mantDig++;
mant = mant * 10 + (current - '0');
} else {
expAdj++;
}
current = read();
switch (current) {
default:
break l;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
}
}
}
if (current == '.') {
current = read();
m2: switch (current) {
default:
case 'e': case 'E':
if (!mantRead) {
reportUnexpectedCharacterError( current );
return 0.0f;
}
break;
case '0':
if (mantDig == 0) {
l: for (;;) {
current = read();
expAdj--;
switch (current) {
case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
break l;
default:
if (!mantRead) {
return 0.0f;
}
break m2;
case '0':
}
}
}
case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
l: for (;;) {
if (mantDig < 9) {
mantDig++;
mant = mant * 10 + (current - '0');
expAdj--;
}
current = read();
switch (current) {
default:
break l;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
}
}
}
}
switch (current) {
case 'e': case 'E':
current = read();
switch (current) {
default:
reportUnexpectedCharacterError( current );
return 0f;
case '-':
expPos = false;
case '+':
current = read();
switch (current) {
default:
reportUnexpectedCharacterError( current );
return 0f;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
}
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
}
en: switch (current) {
case '0':
l: for (;;) {
current = read();
switch (current) {
case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
break l;
default:
break en;
case '0':
}
}
case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
l: for (;;) {
if (expDig < 3) {
expDig++;
exp = exp * 10 + (current - '0');
}
current = read();
switch (current) {
default:
break l;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
}
}
}
default:
}
if (!expPos) {
exp = -exp;
}
exp += expAdj;
if (!mantPos) {
mant = -mant;
}
return buildFloat(mant, exp);
}
private void reportUnexpectedCharacterError(char c) {
throw new RuntimeException("Unexpected char '" + c + "'.");
}
/**
* Computes a float from mantissa and exponent.
*/
public static float buildFloat(int mant, int exp) {
if (exp < -125 || mant == 0) {
return 0.0f;
}
if (exp >= 128) {
return (mant > 0)
? Float.POSITIVE_INFINITY
: Float.NEGATIVE_INFINITY;
}
if (exp == 0) {
return mant;
}
if (mant >= (1 << 26)) {
mant++; // round up trailing bits if they will be dropped.
}
return (float) ((exp > 0) ? mant * pow10[exp] : mant / pow10[-exp]);
}
/**
* Array of powers of ten. Using double instead of float gives a tiny bit more precision.
*/
private static final double[] pow10 = new double[128];
static {
for (int i = 0; i < pow10.length; i++) {
pow10[i] = Math.pow(10, i);
}
}
public float nextFloat() {
skipWhitespace();
float f = parseFloat();
skipNumberSeparator();
return f;
}
}

View File

@ -1,122 +0,0 @@
package com.larvalabs.svgandroid;
import android.graphics.Picture;
import android.graphics.RectF;
import android.graphics.drawable.PictureDrawable;
/*
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You 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.
*/
/**
* Describes a vector Picture object, and optionally its bounds.
*
* @author Larva Labs, LLC
*/
public class SVG {
/**
* The parsed Picture object.
*/
private Picture picture;
/**
* These are the bounds for the SVG specified as a hidden "bounds" layer in the SVG.
*/
private RectF bounds;
/**
* These are the estimated bounds of the SVG computed from the SVG elements while parsing.
* Note that this could be null if there was a failure to compute limits (ie. an empty SVG).
*/
private RectF limits = null;
/**
* Construct a new SVG.
* @param picture the parsed picture object.
* @param bounds the bounds computed from the "bounds" layer in the SVG.
*/
SVG(Picture picture, RectF bounds) {
this.picture = picture;
this.bounds = bounds;
}
/**
* Set the limits of the SVG, which are the estimated bounds computed by the parser.
* @param limits the bounds computed while parsing the SVG, may not be entirely accurate.
*/
void setLimits(RectF limits) {
this.limits = limits;
}
/**
* Create a picture drawable from the SVG.
* @return the PictureDrawable.
*/
public PictureDrawable createPictureDrawable() {
return new PictureDrawable(picture);
// return new PictureDrawable(picture) {
// @Override
// public int getIntrinsicWidth() {
// if (bounds != null) {
// return (int) bounds.width();
// } else if (limits != null) {
// return (int) limits.width();
// } else {
// return -1;
// }
// }
//
// @Override
// public int getIntrinsicHeight() {
// if (bounds != null) {
// return (int) bounds.height();
// } else if (limits != null) {
// return (int) limits.height();
// } else {
// return -1;
// }
// }
// };
}
/**
* Get the parsed SVG picture data.
* @return the picture.
*/
public Picture getPicture() {
return picture;
}
/**
* Gets the bounding rectangle for the SVG, if one was specified.
* @return rectangle representing the bounds.
*/
public RectF getBounds() {
return bounds;
}
/**
* Gets the bounding rectangle for the SVG that was computed upon parsing.
* It may not be entirely accurate for certain curves or transformations,
* but is often better than nothing.
* @return rectangle representing the computed bounds.
*/
public RectF getLimits() {
return limits;
}
}

View File

@ -1,23 +0,0 @@
package com.larvalabs.svgandroid;
/**
* Runtime exception thrown when there is a problem parsing an SVG.
*
* @author Larva Labs, LLC
*/
public class SVGParseException extends RuntimeException {
private static final long serialVersionUID = 1L;
public SVGParseException(String s) {
super(s);
}
public SVGParseException(String s, Throwable throwable) {
super(s, throwable);
}
public SVGParseException(Throwable throwable) {
super(throwable);
}
}

View File

@ -1,26 +0,0 @@
/**
* Provides a mechanism to parse a limited version of SVG Basic 1.1 files in to <code>android.graphics.Picture</code>
* objects.
*
* This allows vector graphics files to be saved out of illustration software (such as Adobe Illustrator) as SVG Basic
* and then used directly in an Android app. The <code>android.graphics.Picture</code> is a very optimized and
* convenient vector graphics class. Performance is very good on a wide array of Android devices.
* <p/>
* Note that only SVG features that can be directly converted in to Android graphics calls are supported.
* The following SVG Basic 1.1 features are not supported and will be ignored by the parser:
* <ul>
* <li>All text and font features.
* <li>Styles.
* <li>Symbols, conditional processing.
* <li>Patterns.
* <li>Masks, filters and views.
* <li>Interactivity, linking, scripting and animation.
* </ul>
* Even with the above features missing, users will find that most Illustrator drawings will render perfectly well on
* Android with this library.
*
* See the {@link com.larvalabs.svgandroid.SVGParser SVGParser} class for instructions on how to use the parser.
*
* @see com.larvalabs.svgandroid.SVGParser
*/
package com.larvalabs.svgandroid;

View File

@ -75,10 +75,10 @@ import tourguide.tourguide.Sequence;
import tourguide.tourguide.ToolTip;
import tourguide.tourguide.TourGuide;
import com.caverock.androidsvg.SVG;
import com.caverock.androidsvg.SVGParseException;
import com.kalab.chess.enginesupport.ChessEngine;
import com.kalab.chess.enginesupport.ChessEngineResolver;
import com.larvalabs.svgandroid.SVG;
import com.larvalabs.svgandroid.SVGParser;
import android.Manifest;
import android.annotation.SuppressLint;
@ -1458,7 +1458,11 @@ public class DroidFish extends Activity
bHeight = bHeight * 3 / 2;
}
}
SVG svg = SVGParser.getSVGFromResource(getResources(), R.raw.touch);
SVG svg = null;
try {
svg = SVG.getFromResource(getResources(), R.raw.touch);
} catch (SVGParseException ignore) {
}
setButtonData(custom1Button, bWidth, bHeight, custom1ButtonActions.getIcon(), svg);
setButtonData(custom2Button, bWidth, bHeight, custom2ButtonActions.getIcon(), svg);
setButtonData(custom3Button, bWidth, bHeight, custom3ButtonActions.getIcon(), svg);
@ -1470,7 +1474,11 @@ public class DroidFish extends Activity
@SuppressWarnings("deprecation")
private void setButtonData(ImageButton button, int bWidth, int bHeight,
int svgResId, SVG touched) {
SVG svg = SVGParser.getSVGFromResource(getResources(), svgResId);
SVG svg = null;
try {
svg = SVG.getFromResource(getResources(), svgResId);
} catch (SVGParseException ignore) {
}
button.setBackgroundDrawable(new SVGPictureDrawable(svg));
StateListDrawable sld = new StateListDrawable();

View File

@ -3,10 +3,16 @@ package org.petero.droidfish;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import com.larvalabs.svgandroid.SVG;
import com.larvalabs.svgandroid.SVGParser;
import com.caverock.androidsvg.SVG;
import com.caverock.androidsvg.SVGParseException;
import org.petero.droidfish.gamelogic.Piece;
@ -51,17 +57,20 @@ public class PieceSet {
nameToPieceType.put("bn.svg", Piece.BKNIGHT);
nameToPieceType.put("bp.svg", Piece.BPAWN);
parseSvgData(cachedWhiteColor, cachedBlackColor);
parseSvgData();
}
/** Re-parse SVG data if piece properties have changed. */
final void readPrefs(SharedPreferences settings) {
boolean modified = false; // FIXME!! check for new piece set
if (modified)
parseSvgData();
ColorTheme ct = ColorTheme.instance();
int whiteColor = ct.getColor(ColorTheme.BRIGHT_PIECE);
int blackColor = ct.getColor(ColorTheme.DARK_PIECE);
if (whiteColor != cachedWhiteColor || blackColor != cachedBlackColor) {
if (modified || whiteColor != cachedWhiteColor || blackColor != cachedBlackColor) {
recycleBitmaps();
parseSvgData(whiteColor, blackColor);
cachedWhiteColor = whiteColor;
cachedBlackColor = blackColor;
cachedSquareSize = -1;
@ -78,10 +87,7 @@ public class PieceSet {
return bitmapTable[pType];
}
private void parseSvgData(int whiteColor, int blackColor) {
HashMap<Integer,Integer> colorReplace = new HashMap<>();
colorReplace.put(0xffffffff, whiteColor);
colorReplace.put(0xff000000, blackColor);
private void parseSvgData() {
try {
ZipInputStream zis = getZipStream();
ZipEntry entry;
@ -97,7 +103,10 @@ public class PieceSet {
bos.write(buf, 0, len);
buf = bos.toByteArray();
ByteArrayInputStream bis = new ByteArrayInputStream(buf);
svgTable[pType] = SVGParser.getSVGFromInputStream(bis, colorReplace);
try {
svgTable[pType] = SVG.getFromInputStream(bis);
} catch (SVGParseException ignore) {
}
}
}
zis.closeEntry();
@ -123,14 +132,65 @@ public class PieceSet {
}
private void createBitmaps(int sqSize) {
Paint colorPaint = new Paint();
{
float[] f = new float[3];
float[] o = new float[3];
for (int i = 0; i < 3; i++) {
int shift = 16 - i * 8;
int w = (cachedWhiteColor >>> shift) & 0xff;
int b = (cachedBlackColor >>> shift) & 0xff;
o[i] = b;
f[i] = (w - b) / (float)255;
}
float[] cm = new float[] {
f[0], 0 , 0 , 0 , o[0],
0 , f[1], 0 , 0 , o[1],
0 , 0 , f[2], 0 , o[2],
0 , 0 , 0 , 1 , 0
};
colorPaint.setColorFilter(new ColorMatrixColorFilter(cm));
}
Paint alphaPaint = null;
int wAlpha = cachedWhiteColor >>> 24;
int bAlpha = cachedBlackColor >>> 24;
if (wAlpha != 0xff || bAlpha != 0xff) {
float o = bAlpha;
float k = (wAlpha - bAlpha) / (float)255;
float kr = 0.299f, kg = 0.587f, kb = 0.114f;
float[] cm = new float[] {
0 , 0 , 0 , 0 , 255,
0 , 0 , 0 , 0 , 255,
0 , 0 , 0 , 0 , 255,
kr*k, kg*k, kb*k, 0 , o
};
alphaPaint = new Paint();
alphaPaint.setColorFilter(new ColorMatrixColorFilter(cm));
alphaPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.MULTIPLY));
}
Bitmap svgBM = Bitmap.createBitmap(sqSize, sqSize, Bitmap.Config.ARGB_8888);
Matrix scaleMat = new Matrix();
for (int i = 0; i < Piece.nPieceTypes; i++) {
SVG svg = svgTable[i];
if (svg != null) {
svgBM.eraseColor(Color.TRANSPARENT);
Canvas canvas = new Canvas(svgBM);
canvas.drawPicture(svg.renderToPicture(), new Rect(0, 0, sqSize, sqSize));
Bitmap bm = Bitmap.createBitmap(sqSize, sqSize, Bitmap.Config.ARGB_8888);
Canvas bmCanvas = new Canvas(bm);
bmCanvas.drawPicture(svg.getPicture(), new Rect(0, 0, sqSize, sqSize));
canvas = new Canvas(bm);
canvas.drawBitmap(svgBM, scaleMat, colorPaint);
if (alphaPaint != null)
canvas.drawBitmap(svgBM, scaleMat, alphaPaint);
bitmapTable[i] = bm;
}
}
svgBM.recycle();
}
}

View File

@ -18,14 +18,14 @@
package org.petero.droidfish;
import com.larvalabs.svgandroid.SVG;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.PictureDrawable;
import com.caverock.androidsvg.SVG;
/**
* Like PictureDrawable but scales the picture according to current drawing bounds.
*/
@ -38,20 +38,19 @@ public class SVGPictureDrawable extends PictureDrawable {
private Bitmap cachedBitmap;
public SVGPictureDrawable(SVG svg) {
super(svg.getPicture());
RectF bounds = svg.getBounds();
RectF limits = svg.getLimits();
if (bounds != null) {
iWidth = (int)bounds.width();
iHeight = (int)bounds.height();
} else if (limits != null) {
iWidth = (int)limits.width();
iHeight = (int)limits.height();
} else {
iWidth = -1;
iHeight = -1;
super(svg.renderToPicture());
int w = (int)svg.getDocumentWidth();
int h = (int)svg.getDocumentHeight();
if (w == -1 || h == -1) {
RectF box = svg.getDocumentViewBox();
if (box != null) {
w = (int)box.width();
h = (int)box.height();
}
}
iWidth = w;
iHeight = h;
}
@Override
public int getIntrinsicWidth() {

View File

@ -18,7 +18,7 @@ allprojects {
repositories {
google()
jcenter()
mavenCentral()
}
}